Merge "Remove local fork of ABSL." into main am: afdf68b952
Original change: https://android-review.googlesource.com/c/platform/external/webrtc/+/3407261
Change-Id: I5a1351fb82f7d70008c055e33b157ae3be4f5452
Signed-off-by: Automerger Merge Worker <android-build-automerger-merge-worker@system.gserviceaccount.com>
diff --git a/third_party/abseil-cpp/.github/ISSUE_TEMPLATE/00-bug_report.md b/third_party/abseil-cpp/.github/ISSUE_TEMPLATE/00-bug_report.md
deleted file mode 100644
index 1edf3de..0000000
--- a/third_party/abseil-cpp/.github/ISSUE_TEMPLATE/00-bug_report.md
+++ /dev/null
@@ -1,41 +0,0 @@
----
-name: Bug report
-about: Create a report to help us improve
-title: ''
-labels: 'bug'
-assignees: ''
----
-
-**Describe the bug**
-
-Include a clear and concise description of what the problem is, including what
-you expected to happen, and what actually happened.
-
-**Steps to reproduce the bug**
-
-It's important that we are able to reproduce the problem that you are
-experiencing. Please provide all code and relevant steps to reproduce the
-problem, including your `BUILD`/`CMakeLists.txt` file and build commands. Links
-to a GitHub branch or [godbolt.org](https://godbolt.org/) that demonstrate the
-problem are also helpful.
-
-**What version of Abseil are you using?**
-
-**What operating system and version are you using**
-
-If you are using a Linux distribution please include the name and version of the
-distribution as well.
-
-**What compiler and version are you using?**
-
-Please include the output of `gcc -v` or `clang -v`, or the equivalent for your
-compiler.
-
-**What build system are you using?**
-
-Please include the output of `bazel --version` or `cmake --version`, or the
-equivalent for your build system.
-
-**Additional context**
-
-Add any other context about the problem here.
diff --git a/third_party/abseil-cpp/.github/ISSUE_TEMPLATE/90-question.md b/third_party/abseil-cpp/.github/ISSUE_TEMPLATE/90-question.md
deleted file mode 100644
index 84cf349..0000000
--- a/third_party/abseil-cpp/.github/ISSUE_TEMPLATE/90-question.md
+++ /dev/null
@@ -1,7 +0,0 @@
----
-name: Question
-about: Have a question? Ask us anything! :-)
-title: ''
-labels: 'question'
-assignees: ''
----
diff --git a/third_party/abseil-cpp/.github/ISSUE_TEMPLATE/config.yml b/third_party/abseil-cpp/.github/ISSUE_TEMPLATE/config.yml
deleted file mode 100644
index 0086358..0000000
--- a/third_party/abseil-cpp/.github/ISSUE_TEMPLATE/config.yml
+++ /dev/null
@@ -1 +0,0 @@
-blank_issues_enabled: true
diff --git a/third_party/abseil-cpp/ABSEIL_ISSUE_TEMPLATE.md b/third_party/abseil-cpp/ABSEIL_ISSUE_TEMPLATE.md
deleted file mode 100644
index ed5461f..0000000
--- a/third_party/abseil-cpp/ABSEIL_ISSUE_TEMPLATE.md
+++ /dev/null
@@ -1,22 +0,0 @@
-Please submit a new Abseil Issue using the template below:
-
-## [Short title of proposed API change(s)]
-
---------------------------------------------------------------------------------
---------------------------------------------------------------------------------
-
-## Background
-
-[Provide the background information that is required in order to evaluate the
-proposed API changes. No controversial claims should be made here. If there are
-design constraints that need to be considered, they should be presented here
-**along with justification for those constraints**. Linking to other docs is
-good, but please keep the **pertinent information as self contained** as
-possible in this section.]
-
-## Proposed API Change (s)
-
-[Please clearly describe the API change(s) being proposed. If multiple changes,
-please keep them clearly distinguished. When possible, **use example code
-snippets to illustrate before-after API usages**. List pros-n-cons. Highlight
-the main questions that you want to be answered. Given the Abseil project compatibility requirements, describe why the API change is safe.]
diff --git a/third_party/abseil-cpp/AUTHORS b/third_party/abseil-cpp/AUTHORS
deleted file mode 100644
index 976d31d..0000000
--- a/third_party/abseil-cpp/AUTHORS
+++ /dev/null
@@ -1,6 +0,0 @@
-# This is the list of Abseil authors for copyright purposes.
-#
-# This does not necessarily list everyone who has contributed code, since in
-# some cases, their employer may be the copyright holder. To see the full list
-# of contributors, see the revision history in source control.
-Google Inc.
diff --git a/third_party/abseil-cpp/Android.bp b/third_party/abseil-cpp/Android.bp
deleted file mode 100644
index c5c99ff..0000000
--- a/third_party/abseil-cpp/Android.bp
+++ /dev/null
@@ -1,53 +0,0 @@
-package {
- default_applicable_licenses: [
- "external_webrtc_third_party_abseil-cpp_license",
- ],
-}
-
-// Added automatically by a large-scale-change that took the approach of
-// 'apply every license found to every target'. While this makes sure we respect
-// every license restriction, it may not be entirely correct.
-//
-// e.g. GPL in an MIT project might only apply to the contrib/ directory.
-//
-// Please consider splitting the single license below into multiple licenses,
-// taking care not to lose any license_kind information, and overriding the
-// default license using the 'licenses: [...]' property on targets as needed.
-//
-// For unused files, consider creating a 'fileGroup' with "//visibility:private"
-// to attach the license to, and including a comment whether the files may be
-// used in the current project.
-// See: http://go/android-license-faq
-license {
- name: "external_webrtc_third_party_abseil-cpp_license",
- visibility: [":__subpackages__"],
- license_kinds: [
- "SPDX-license-identifier-Apache-2.0",
- "legacy_unencumbered",
- ],
- license_text: [
- "LICENSE",
- ],
-}
-
-cc_defaults {
- name: "libwebrtc_absl_defaults",
- cflags: ["-Wno-deprecated-builtins"],
- visibility: [
- "//external/webrtc:__subpackages__",
- "//device/google/cuttlefish/host/frontend/webrtc:__subpackages__",
- ],
-}
-
-cc_library_headers {
- name: "libwebrtc_absl_headers",
- defaults: ["libwebrtc_absl_defaults"],
- // vendor needed for libpreprocessing effects.
- vendor: true,
- host_supported: true,
- export_include_dirs: ["."],
- visibility: [
- "//frameworks/av/media/libeffects/preprocessing:__subpackages__",
- ],
-}
-
diff --git a/third_party/abseil-cpp/BUILD.bazel b/third_party/abseil-cpp/BUILD.bazel
deleted file mode 100644
index 79fb0ec..0000000
--- a/third_party/abseil-cpp/BUILD.bazel
+++ /dev/null
@@ -1,25 +0,0 @@
-#
-# 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.
-#
-
-package(default_visibility = ["//visibility:public"])
-
-licenses(["notice"]) # Apache 2.0
-
-# Expose license for external usage through bazel.
-exports_files([
- "AUTHORS",
- "LICENSE",
-])
diff --git a/third_party/abseil-cpp/BUILD.gn b/third_party/abseil-cpp/BUILD.gn
deleted file mode 100644
index e1c5dab..0000000
--- a/third_party/abseil-cpp/BUILD.gn
+++ /dev/null
@@ -1,265 +0,0 @@
-# Copyright 2018 The Chromium Authors
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# Flags specified here must not impact ABI. Code compiled with and without these
-# opts will be linked together, and in some cases headers compiled with and
-# without these options will be part of the same program.
-
-import("//build/config/c++/c++.gni")
-import("//build/config/nacl/config.gni")
-import("//build/config/sanitizers/sanitizers.gni")
-import("//build/toolchain/toolchain.gni")
-import("//build_overrides/build.gni")
-import("//third_party/abseil-cpp/absl.gni")
-
-config("absl_component_build") {
- defines = [ "ABSL_CONSUME_DLL" ]
-}
-
-assert(!is_nacl || is_nacl_saigo,
- "base must not be built in most nacl toolchains")
-
-component("absl") {
- public_deps = [ ":absl_component_deps" ]
- if (is_component_build) {
- public_configs = [ ":absl_component_build" ]
-
- if (is_win && is_clang) {
- if (current_cpu == "x64") {
- if (is_debug) {
- sources = [ "symbols_x64_dbg.def" ]
- } else {
- if (is_asan) {
- sources = [ "symbols_x64_rel_asan.def" ]
- } else {
- sources = [ "symbols_x64_rel.def" ]
- }
- }
- }
- if (current_cpu == "x86") {
- if (is_debug) {
- sources = [ "symbols_x86_dbg.def" ]
- } else {
- sources = [ "symbols_x86_rel.def" ]
- }
- }
- if (current_cpu == "arm64") {
- if (is_debug) {
- sources = [ "symbols_arm64_dbg.def" ]
- } else {
- sources = [ "symbols_arm64_rel.def" ]
- }
- }
- }
- }
-}
-
-group("absl_component_deps") {
- public_deps = [
- "//third_party/abseil-cpp/absl/algorithm:container",
- "//third_party/abseil-cpp/absl/base",
- "//third_party/abseil-cpp/absl/base:config",
- "//third_party/abseil-cpp/absl/base:core_headers",
- "//third_party/abseil-cpp/absl/cleanup",
- "//third_party/abseil-cpp/absl/container:btree",
- "//third_party/abseil-cpp/absl/container:fixed_array",
- "//third_party/abseil-cpp/absl/container:flat_hash_map",
- "//third_party/abseil-cpp/absl/container:flat_hash_set",
- "//third_party/abseil-cpp/absl/container:inlined_vector",
- "//third_party/abseil-cpp/absl/container:node_hash_map",
- "//third_party/abseil-cpp/absl/container:node_hash_set",
- "//third_party/abseil-cpp/absl/debugging:failure_signal_handler",
- "//third_party/abseil-cpp/absl/debugging:stacktrace",
- "//third_party/abseil-cpp/absl/debugging:symbolize",
- "//third_party/abseil-cpp/absl/functional:any_invocable",
- "//third_party/abseil-cpp/absl/functional:bind_front",
- "//third_party/abseil-cpp/absl/functional:function_ref",
- "//third_party/abseil-cpp/absl/hash",
- "//third_party/abseil-cpp/absl/log:die_if_null",
- "//third_party/abseil-cpp/absl/memory",
- "//third_party/abseil-cpp/absl/meta:type_traits",
- "//third_party/abseil-cpp/absl/numeric:bits",
- "//third_party/abseil-cpp/absl/numeric:int128",
- "//third_party/abseil-cpp/absl/random",
- "//third_party/abseil-cpp/absl/random:distributions",
- "//third_party/abseil-cpp/absl/status",
- "//third_party/abseil-cpp/absl/status:statusor",
- "//third_party/abseil-cpp/absl/strings",
- "//third_party/abseil-cpp/absl/strings:cord",
- "//third_party/abseil-cpp/absl/strings:str_format",
- "//third_party/abseil-cpp/absl/synchronization",
- "//third_party/abseil-cpp/absl/time",
- "//third_party/abseil-cpp/absl/types:optional",
- "//third_party/abseil-cpp/absl/types:span",
- "//third_party/abseil-cpp/absl/types:variant",
- "//third_party/abseil-cpp/absl/utility",
- ]
-
- # The following dependencies currently don't build with NaCl.
- # TODO(https://crbug.com/1114625): Fix build errors and remove this section.
- if (is_nacl) {
- public_deps -=
- [ "//third_party/abseil-cpp/absl/debugging:failure_signal_handler" ]
- }
-
- visibility = [ ":absl" ]
-}
-
-group("default") {
- deps = [
- "absl/types:any",
- "absl/types:bad_any_cast",
- "absl/types:bad_optional_access",
- "absl/types:optional",
- "absl/types:span",
- ]
-}
-
-config("absl_include_config") {
- include_dirs = [ "." ]
-}
-
-config("absl_define_config") {
- defines = [ "ABSL_ALLOCATOR_NOTHROW=1" ]
-
- if (is_win && !use_custom_libcxx) {
- defines += [
- # See crbug.com/1101367: Acknowledge extended alignment when using
- # MSVC's standard library.
- "_ENABLE_EXTENDED_ALIGNED_STORAGE",
- ]
- }
-}
-
-config("absl_default_cflags_cc") {
- cflags_cc = []
- if (is_clang) {
- cflags_cc += [
- # TODO(crbug.com/588506): Explicitly enable conversion warnings.
- "-Wbool-conversion",
- "-Wconstant-conversion",
- "-Wenum-conversion",
- "-Wint-conversion",
- "-Wliteral-conversion",
- "-Wnon-literal-null-conversion",
- "-Wnull-conversion",
- "-Wobjc-literal-conversion",
- "-Wstring-conversion",
- ]
- if (!is_nacl) {
- cflags_cc += [ "-Wbitfield-enum-conversion" ]
- }
- }
-}
-
-config("absl_test_cflags_cc") {
- cflags_cc = []
- if (is_clang || !is_win) {
- cflags_cc += [
- "-Wno-conversion-null",
- "-Wno-missing-declarations",
- "-Wno-unused-function",
- "-Wno-unused-parameter",
- "-Wno-unused-private-field",
- ]
- }
- if (is_win) {
- cflags_cc += [
- "/wd4101", # unreferenced local variable
- ]
- }
-}
-
-config("absl_test_config") {
- cflags_cc = []
- if (is_win && !is_clang) {
- cflags_cc += [ "/wd4996" ]
- }
- if (is_clang) {
- cflags_cc += [
- "-Wno-deprecated-declarations",
- "-Wno-unused-private-field",
- "-Wno-unused-function",
- ]
- }
-}
-
-if (build_with_chromium) {
- import("//testing/test.gni")
-
- if (!is_component_build) {
- test("absl_tests") {
- testonly = true
- deps = [
- "absl/algorithm:algorithm_test",
- "absl/algorithm:container_test",
- "absl/base:config_test",
- "absl/base:prefetch_test",
- "absl/cleanup:cleanup_test",
- "absl/container:common_policy_traits_test",
- "absl/container:inlined_vector_test",
- "absl/container:node_slot_policy_test",
- "absl/container:sample_element_size_test",
- "absl/functional:any_invocable_test",
- "absl/hash:hash_test",
- "absl/hash:low_level_hash_test",
- "absl/log:basic_log_test",
- "absl/log:check_test",
- "absl/log:die_if_null_test",
- "absl/log:flags_test",
- "absl/log:globals_test",
- "absl/log:log_entry_test",
- "absl/log:log_format_test",
- "absl/log:log_macro_hygiene_test",
- "absl/log:log_modifier_methods_test",
- "absl/log:log_sink_test",
- "absl/log:log_streamer_test",
- "absl/log:scoped_mock_log_test",
- "absl/log:stripping_test",
- "absl/log/internal:stderr_log_sink_test",
- "absl/memory:memory_test",
- "absl/meta:type_traits_test",
- "absl/profiling:exponential_biased_test",
- "absl/profiling:periodic_sampler_test",
- "absl/status:statusor_test",
- "absl/strings:ascii_test",
- "absl/strings:cord_buffer_test",
- "absl/strings:cord_data_edge_test",
- "absl/strings:cord_rep_btree_navigator_test",
- "absl/strings:cord_rep_btree_reader_test",
- "absl/strings:cord_rep_btree_test",
- "absl/strings:cord_rep_crc_test",
- "absl/strings:cordz_functions_test",
- "absl/strings:cordz_info_statistics_test",
- "absl/strings:cordz_info_test",
- "absl/strings:cordz_test",
- "absl/strings:cordz_update_scope_test",
- "absl/strings:cordz_update_tracker_test",
- "absl/strings:damerau_levenshtein_distance_test",
- "absl/strings:match_test",
- "absl/strings:str_replace_test",
- "absl/strings:string_view_test",
- "absl/types:optional_test",
- "absl/types:variant_test",
- "//third_party/googletest:gtest_main",
- ]
- }
- }
-
- test("absl_hardening_tests") {
- testonly = true
- sources = [ "absl_hardening_test.cc" ]
- deps = [
- "//base/test:run_all_unittests",
- "//third_party/abseil-cpp/absl/base:config",
- "//third_party/abseil-cpp/absl/container:fixed_array",
- "//third_party/abseil-cpp/absl/container:inlined_vector",
- "//third_party/abseil-cpp/absl/strings",
- "//third_party/abseil-cpp/absl/types:optional",
- "//third_party/abseil-cpp/absl/types:span",
- "//third_party/abseil-cpp/absl/types:variant",
- "//third_party/googletest:gtest",
- ]
- }
-}
diff --git a/third_party/abseil-cpp/CMake/AbseilDll.cmake b/third_party/abseil-cpp/CMake/AbseilDll.cmake
deleted file mode 100644
index a4560df..0000000
--- a/third_party/abseil-cpp/CMake/AbseilDll.cmake
+++ /dev/null
@@ -1,609 +0,0 @@
-include(CMakeParseArguments)
-include(GNUInstallDirs)
-
-set(ABSL_INTERNAL_DLL_FILES
- "algorithm/algorithm.h"
- "algorithm/container.h"
- "base/attributes.h"
- "base/call_once.h"
- "base/casts.h"
- "base/config.h"
- "base/const_init.h"
- "base/dynamic_annotations.h"
- "base/internal/atomic_hook.h"
- "base/internal/cycleclock.cc"
- "base/internal/cycleclock.h"
- "base/internal/cycleclock_config.h"
- "base/internal/direct_mmap.h"
- "base/internal/endian.h"
- "base/internal/errno_saver.h"
- "base/internal/fast_type_id.h"
- "base/internal/hide_ptr.h"
- "base/internal/identity.h"
- "base/internal/invoke.h"
- "base/internal/inline_variable.h"
- "base/internal/low_level_alloc.cc"
- "base/internal/low_level_alloc.h"
- "base/internal/low_level_scheduling.h"
- "base/internal/per_thread_tls.h"
- "base/internal/prefetch.h"
- "base/internal/pretty_function.h"
- "base/internal/raw_logging.cc"
- "base/internal/raw_logging.h"
- "base/internal/scheduling_mode.h"
- "base/internal/scoped_set_env.cc"
- "base/internal/scoped_set_env.h"
- "base/internal/strerror.h"
- "base/internal/strerror.cc"
- "base/internal/spinlock.cc"
- "base/internal/spinlock.h"
- "base/internal/spinlock_wait.cc"
- "base/internal/spinlock_wait.h"
- "base/internal/sysinfo.cc"
- "base/internal/sysinfo.h"
- "base/internal/thread_identity.cc"
- "base/internal/thread_identity.h"
- "base/internal/throw_delegate.cc"
- "base/internal/throw_delegate.h"
- "base/internal/tsan_mutex_interface.h"
- "base/internal/unaligned_access.h"
- "base/internal/unscaledcycleclock.cc"
- "base/internal/unscaledcycleclock.h"
- "base/internal/unscaledcycleclock_config.h"
- "base/log_severity.cc"
- "base/log_severity.h"
- "base/macros.h"
- "base/optimization.h"
- "base/options.h"
- "base/policy_checks.h"
- "base/port.h"
- "base/thread_annotations.h"
- "cleanup/cleanup.h"
- "cleanup/internal/cleanup.h"
- "container/btree_map.h"
- "container/btree_set.h"
- "container/fixed_array.h"
- "container/flat_hash_map.h"
- "container/flat_hash_set.h"
- "container/inlined_vector.h"
- "container/internal/btree.h"
- "container/internal/btree_container.h"
- "container/internal/common.h"
- "container/internal/common_policy_traits.h"
- "container/internal/compressed_tuple.h"
- "container/internal/container_memory.h"
- "container/internal/counting_allocator.h"
- "container/internal/hash_function_defaults.h"
- "container/internal/hash_policy_traits.h"
- "container/internal/hashtable_debug.h"
- "container/internal/hashtable_debug_hooks.h"
- "container/internal/hashtablez_sampler.cc"
- "container/internal/hashtablez_sampler.h"
- "container/internal/hashtablez_sampler_force_weak_definition.cc"
- "container/internal/inlined_vector.h"
- "container/internal/layout.h"
- "container/internal/node_slot_policy.h"
- "container/internal/raw_hash_map.h"
- "container/internal/raw_hash_set.cc"
- "container/internal/raw_hash_set.h"
- "container/internal/tracked.h"
- "container/node_hash_map.h"
- "container/node_hash_set.h"
- "debugging/failure_signal_handler.cc"
- "debugging/failure_signal_handler.h"
- "debugging/leak_check.h"
- "debugging/stacktrace.cc"
- "debugging/stacktrace.h"
- "debugging/symbolize.cc"
- "debugging/symbolize.h"
- "debugging/internal/address_is_readable.cc"
- "debugging/internal/address_is_readable.h"
- "debugging/internal/demangle.cc"
- "debugging/internal/demangle.h"
- "debugging/internal/elf_mem_image.cc"
- "debugging/internal/elf_mem_image.h"
- "debugging/internal/examine_stack.cc"
- "debugging/internal/examine_stack.h"
- "debugging/internal/stack_consumption.cc"
- "debugging/internal/stack_consumption.h"
- "debugging/internal/stacktrace_config.h"
- "debugging/internal/symbolize.h"
- "debugging/internal/vdso_support.cc"
- "debugging/internal/vdso_support.h"
- "functional/any_invocable.h"
- "functional/internal/front_binder.h"
- "functional/bind_front.h"
- "functional/function_ref.h"
- "functional/internal/any_invocable.h"
- "functional/internal/function_ref.h"
- "hash/hash.h"
- "hash/internal/city.h"
- "hash/internal/city.cc"
- "hash/internal/hash.h"
- "hash/internal/hash.cc"
- "hash/internal/spy_hash_state.h"
- "hash/internal/low_level_hash.h"
- "hash/internal/low_level_hash.cc"
- "memory/memory.h"
- "meta/type_traits.h"
- "numeric/bits.h"
- "numeric/int128.cc"
- "numeric/int128.h"
- "numeric/internal/bits.h"
- "numeric/internal/representation.h"
- "profiling/internal/exponential_biased.cc"
- "profiling/internal/exponential_biased.h"
- "profiling/internal/periodic_sampler.cc"
- "profiling/internal/periodic_sampler.h"
- "profiling/internal/sample_recorder.h"
- "random/bernoulli_distribution.h"
- "random/beta_distribution.h"
- "random/bit_gen_ref.h"
- "random/discrete_distribution.cc"
- "random/discrete_distribution.h"
- "random/distributions.h"
- "random/exponential_distribution.h"
- "random/gaussian_distribution.cc"
- "random/gaussian_distribution.h"
- "random/internal/distribution_caller.h"
- "random/internal/fastmath.h"
- "random/internal/fast_uniform_bits.h"
- "random/internal/generate_real.h"
- "random/internal/iostream_state_saver.h"
- "random/internal/mock_helpers.h"
- "random/internal/nonsecure_base.h"
- "random/internal/pcg_engine.h"
- "random/internal/platform.h"
- "random/internal/pool_urbg.cc"
- "random/internal/pool_urbg.h"
- "random/internal/randen.cc"
- "random/internal/randen.h"
- "random/internal/randen_detect.cc"
- "random/internal/randen_detect.h"
- "random/internal/randen_engine.h"
- "random/internal/randen_hwaes.cc"
- "random/internal/randen_hwaes.h"
- "random/internal/randen_round_keys.cc"
- "random/internal/randen_slow.cc"
- "random/internal/randen_slow.h"
- "random/internal/randen_traits.h"
- "random/internal/salted_seed_seq.h"
- "random/internal/seed_material.cc"
- "random/internal/seed_material.h"
- "random/internal/sequence_urbg.h"
- "random/internal/traits.h"
- "random/internal/uniform_helper.h"
- "random/internal/wide_multiply.h"
- "random/log_uniform_int_distribution.h"
- "random/poisson_distribution.h"
- "random/random.h"
- "random/seed_gen_exception.cc"
- "random/seed_gen_exception.h"
- "random/seed_sequences.cc"
- "random/seed_sequences.h"
- "random/uniform_int_distribution.h"
- "random/uniform_real_distribution.h"
- "random/zipf_distribution.h"
- "status/internal/status_internal.h"
- "status/internal/statusor_internal.h"
- "status/status.h"
- "status/status.cc"
- "status/statusor.h"
- "status/statusor.cc"
- "status/status_payload_printer.h"
- "status/status_payload_printer.cc"
- "strings/ascii.cc"
- "strings/ascii.h"
- "strings/charconv.cc"
- "strings/charconv.h"
- "strings/cord.cc"
- "strings/cord.h"
- "strings/cord_analysis.cc"
- "strings/cord_analysis.h"
- "strings/cord_buffer.cc"
- "strings/cord_buffer.h"
- "strings/escaping.cc"
- "strings/escaping.h"
- "strings/internal/charconv_bigint.cc"
- "strings/internal/charconv_bigint.h"
- "strings/internal/charconv_parse.cc"
- "strings/internal/charconv_parse.h"
- "strings/internal/cord_data_edge.h"
- "strings/internal/cord_internal.cc"
- "strings/internal/cord_internal.h"
- "strings/internal/cord_rep_btree.cc"
- "strings/internal/cord_rep_btree.h"
- "strings/internal/cord_rep_btree_navigator.cc"
- "strings/internal/cord_rep_btree_navigator.h"
- "strings/internal/cord_rep_btree_reader.cc"
- "strings/internal/cord_rep_btree_reader.h"
- "strings/internal/cord_rep_crc.cc"
- "strings/internal/cord_rep_crc.h"
- "strings/internal/cord_rep_consume.h"
- "strings/internal/cord_rep_consume.cc"
- "strings/internal/cord_rep_flat.h"
- "strings/internal/cord_rep_ring.cc"
- "strings/internal/cord_rep_ring.h"
- "strings/internal/cord_rep_ring_reader.h"
- "strings/internal/cordz_functions.cc"
- "strings/internal/cordz_functions.h"
- "strings/internal/cordz_handle.cc"
- "strings/internal/cordz_handle.h"
- "strings/internal/cordz_info.cc"
- "strings/internal/cordz_info.h"
- "strings/internal/cordz_sample_token.cc"
- "strings/internal/cordz_sample_token.h"
- "strings/internal/cordz_statistics.h"
- "strings/internal/cordz_update_scope.h"
- "strings/internal/cordz_update_tracker.h"
- "strings/internal/damerau_levenshtein_distance.h"
- "strings/internal/damerau_levenshtein_distance.cc"
- "strings/internal/stl_type_traits.h"
- "strings/internal/string_constant.h"
- "strings/internal/stringify_sink.h"
- "strings/internal/stringify_sink.cc"
- "strings/match.cc"
- "strings/match.h"
- "strings/numbers.cc"
- "strings/numbers.h"
- "strings/str_format.h"
- "strings/str_cat.cc"
- "strings/str_cat.h"
- "strings/str_join.h"
- "strings/str_replace.cc"
- "strings/str_replace.h"
- "strings/str_split.cc"
- "strings/str_split.h"
- "strings/string_view.cc"
- "strings/string_view.h"
- "strings/strip.h"
- "strings/substitute.cc"
- "strings/substitute.h"
- "strings/internal/char_map.h"
- "strings/internal/escaping.h"
- "strings/internal/escaping.cc"
- "strings/internal/memutil.cc"
- "strings/internal/memutil.h"
- "strings/internal/ostringstream.cc"
- "strings/internal/ostringstream.h"
- "strings/internal/pow10_helper.cc"
- "strings/internal/pow10_helper.h"
- "strings/internal/resize_uninitialized.h"
- "strings/internal/str_format/arg.cc"
- "strings/internal/str_format/arg.h"
- "strings/internal/str_format/bind.cc"
- "strings/internal/str_format/bind.h"
- "strings/internal/str_format/checker.h"
- "strings/internal/str_format/extension.cc"
- "strings/internal/str_format/extension.h"
- "strings/internal/str_format/float_conversion.cc"
- "strings/internal/str_format/float_conversion.h"
- "strings/internal/str_format/output.cc"
- "strings/internal/str_format/output.h"
- "strings/internal/str_format/parser.cc"
- "strings/internal/str_format/parser.h"
- "strings/internal/str_join_internal.h"
- "strings/internal/str_split_internal.h"
- "strings/internal/utf8.cc"
- "strings/internal/utf8.h"
- "synchronization/barrier.cc"
- "synchronization/barrier.h"
- "synchronization/blocking_counter.cc"
- "synchronization/blocking_counter.h"
- "synchronization/mutex.cc"
- "synchronization/mutex.h"
- "synchronization/notification.cc"
- "synchronization/notification.h"
- "synchronization/internal/create_thread_identity.cc"
- "synchronization/internal/create_thread_identity.h"
- "synchronization/internal/futex.h"
- "synchronization/internal/graphcycles.cc"
- "synchronization/internal/graphcycles.h"
- "synchronization/internal/kernel_timeout.h"
- "synchronization/internal/per_thread_sem.cc"
- "synchronization/internal/per_thread_sem.h"
- "synchronization/internal/thread_pool.h"
- "synchronization/internal/waiter.cc"
- "synchronization/internal/waiter.h"
- "time/civil_time.cc"
- "time/civil_time.h"
- "time/clock.cc"
- "time/clock.h"
- "time/duration.cc"
- "time/format.cc"
- "time/time.cc"
- "time/time.h"
- "time/internal/cctz/include/cctz/civil_time.h"
- "time/internal/cctz/include/cctz/civil_time_detail.h"
- "time/internal/cctz/include/cctz/time_zone.h"
- "time/internal/cctz/include/cctz/zone_info_source.h"
- "time/internal/cctz/src/civil_time_detail.cc"
- "time/internal/cctz/src/time_zone_fixed.cc"
- "time/internal/cctz/src/time_zone_fixed.h"
- "time/internal/cctz/src/time_zone_format.cc"
- "time/internal/cctz/src/time_zone_if.cc"
- "time/internal/cctz/src/time_zone_if.h"
- "time/internal/cctz/src/time_zone_impl.cc"
- "time/internal/cctz/src/time_zone_impl.h"
- "time/internal/cctz/src/time_zone_info.cc"
- "time/internal/cctz/src/time_zone_info.h"
- "time/internal/cctz/src/time_zone_libc.cc"
- "time/internal/cctz/src/time_zone_libc.h"
- "time/internal/cctz/src/time_zone_lookup.cc"
- "time/internal/cctz/src/time_zone_posix.cc"
- "time/internal/cctz/src/time_zone_posix.h"
- "time/internal/cctz/src/tzfile.h"
- "time/internal/cctz/src/zone_info_source.cc"
- "types/any.h"
- "types/bad_any_cast.cc"
- "types/bad_any_cast.h"
- "types/bad_optional_access.cc"
- "types/bad_optional_access.h"
- "types/bad_variant_access.cc"
- "types/bad_variant_access.h"
- "types/compare.h"
- "types/internal/conformance_aliases.h"
- "types/internal/conformance_archetype.h"
- "types/internal/conformance_profile.h"
- "types/internal/parentheses.h"
- "types/internal/transform_args.h"
- "types/internal/variant.h"
- "types/optional.h"
- "types/internal/optional.h"
- "types/span.h"
- "types/internal/span.h"
- "types/variant.h"
- "utility/utility.h"
- "debugging/leak_check.cc"
-)
-
-set(ABSL_INTERNAL_DLL_TARGETS
- "algorithm"
- "algorithm_container"
- "any"
- "any_invocable"
- "atomic_hook"
- "bad_any_cast"
- "bad_any_cast_impl"
- "bad_optional_access"
- "bad_variant_access"
- "base"
- "base_internal"
- "bind_front"
- "bits"
- "btree"
- "city"
- "civil_time"
- "compare"
- "compressed_tuple"
- "config"
- "container"
- "container_common"
- "container_memory"
- "cord"
- "core_headers"
- "counting_allocator"
- "debugging"
- "debugging_internal"
- "demangle_internal"
- "dynamic_annotations"
- "endian"
- "examine_stack"
- "exponential_biased"
- "failure_signal_handler"
- "fixed_array"
- "flat_hash_map"
- "flat_hash_set"
- "function_ref"
- "graphcycles_internal"
- "hash"
- "hash_function_defaults"
- "hash_policy_traits"
- "hashtable_debug"
- "hashtable_debug_hooks"
- "hashtablez_sampler"
- "inlined_vector"
- "inlined_vector_internal"
- "int128"
- "kernel_timeout_internal"
- "layout"
- "leak_check"
- "log_severity"
- "malloc_internal"
- "memory"
- "meta"
- "node_hash_map"
- "node_hash_set"
- "node_slot_policy"
- "numeric"
- "optional"
- "periodic_sampler"
- "pow10_helper"
- "pretty_function"
- "random_bit_gen_ref"
- "random_distributions"
- "random_internal_distribution_caller"
- "random_internal_distributions"
- "random_internal_explicit_seed_seq"
- "random_internal_fastmath"
- "random_internal_fast_uniform_bits"
- "random_internal_generate_real"
- "random_internal_iostream_state_saver"
- "random_internal_nonsecure_base"
- "random_internal_pcg_engine"
- "random_internal_platform"
- "random_internal_pool_urbg"
- "random_internal_randen"
- "random_internal_randen_engine"
- "random_internal_randen_hwaes"
- "random_internal_randen_hwaes_impl"
- "random_internal_randen_slow"
- "random_internal_salted_seed_seq"
- "random_internal_seed_material"
- "random_internal_sequence_urbg"
- "random_internal_traits"
- "random_internal_uniform_helper"
- "random_internal_wide_multiply"
- "random_random"
- "random_seed_gen_exception"
- "random_seed_sequences"
- "raw_hash_map"
- "raw_hash_set"
- "raw_logging_internal"
- "sample_recorder"
- "scoped_set_env"
- "span"
- "spinlock_wait"
- "spy_hash_state"
- "stack_consumption"
- "stacktrace"
- "status"
- "str_format"
- "str_format_internal"
- "strings"
- "strings_internal"
- "symbolize"
- "synchronization"
- "thread_pool"
- "throw_delegate"
- "time"
- "time_zone"
- "tracked"
- "type_traits"
- "utility"
- "variant"
-)
-
-function(_absl_target_compile_features_if_available TARGET TYPE FEATURE)
- if(FEATURE IN_LIST CMAKE_CXX_COMPILE_FEATURES)
- target_compile_features(${TARGET} ${TYPE} ${FEATURE})
- else()
- message(WARNING "Feature ${FEATURE} is unknown for the CXX compiler")
- endif()
-endfunction()
-
-include(CheckCXXSourceCompiles)
-
-check_cxx_source_compiles(
- [==[
-#ifdef _MSC_VER
-# if _MSVC_LANG < 201700L
-# error "The compiler defaults or is configured for C++ < 17"
-# endif
-#elif __cplusplus < 201700L
-# error "The compiler defaults or is configured for C++ < 17"
-#endif
-int main() { return 0; }
-]==]
- ABSL_INTERNAL_AT_LEAST_CXX17)
-
-if(ABSL_INTERNAL_AT_LEAST_CXX17)
- set(ABSL_INTERNAL_CXX_STD_FEATURE cxx_std_17)
-else()
- set(ABSL_INTERNAL_CXX_STD_FEATURE cxx_std_14)
-endif()
-
-function(absl_internal_dll_contains)
- cmake_parse_arguments(ABSL_INTERNAL_DLL
- ""
- "OUTPUT;TARGET"
- ""
- ${ARGN}
- )
-
- STRING(REGEX REPLACE "^absl::" "" _target ${ABSL_INTERNAL_DLL_TARGET})
-
- list(FIND
- ABSL_INTERNAL_DLL_TARGETS
- "${_target}"
- _index)
-
- if (${_index} GREATER -1)
- set(${ABSL_INTERNAL_DLL_OUTPUT} 1 PARENT_SCOPE)
- else()
- set(${ABSL_INTERNAL_DLL_OUTPUT} 0 PARENT_SCOPE)
- endif()
-endfunction()
-
-function(absl_internal_dll_targets)
- cmake_parse_arguments(ABSL_INTERNAL_DLL
- ""
- "OUTPUT"
- "DEPS"
- ${ARGN}
- )
-
- set(_deps "")
- foreach(dep IN LISTS ABSL_INTERNAL_DLL_DEPS)
- absl_internal_dll_contains(TARGET ${dep} OUTPUT _contains)
- if (_contains)
- list(APPEND _deps abseil_dll)
- else()
- list(APPEND _deps ${dep})
- endif()
- endforeach()
-
- # Because we may have added the DLL multiple times
- list(REMOVE_DUPLICATES _deps)
- set(${ABSL_INTERNAL_DLL_OUTPUT} "${_deps}" PARENT_SCOPE)
-endfunction()
-
-function(absl_make_dll)
- add_library(
- abseil_dll
- SHARED
- "${ABSL_INTERNAL_DLL_FILES}"
- )
- target_link_libraries(
- abseil_dll
- PRIVATE
- ${ABSL_DEFAULT_LINKOPTS}
- )
- set_property(TARGET abseil_dll PROPERTY LINKER_LANGUAGE "CXX")
- target_include_directories(
- abseil_dll
- PUBLIC
- "$<BUILD_INTERFACE:${ABSL_COMMON_INCLUDE_DIRS}>"
- $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
- )
-
- target_compile_options(
- abseil_dll
- PRIVATE
- ${ABSL_DEFAULT_COPTS}
- )
-
- target_compile_definitions(
- abseil_dll
- PRIVATE
- ABSL_BUILD_DLL
- NOMINMAX
- INTERFACE
- ${ABSL_CC_LIB_DEFINES}
- ABSL_CONSUME_DLL
- )
-
- if(ABSL_PROPAGATE_CXX_STD)
- # Abseil libraries require C++14 as the current minimum standard. When
- # compiled with C++17 (either because it is the compiler's default or
- # explicitly requested), then Abseil requires C++17.
- _absl_target_compile_features_if_available(${_NAME} PUBLIC ${ABSL_INTERNAL_CXX_STD_FEATURE})
- else()
- # Note: This is legacy (before CMake 3.8) behavior. Setting the
- # target-level CXX_STANDARD property to ABSL_CXX_STANDARD (which is
- # initialized by CMAKE_CXX_STANDARD) should have no real effect, since
- # that is the default value anyway.
- #
- # CXX_STANDARD_REQUIRED does guard against the top-level CMake project
- # not having enabled CMAKE_CXX_STANDARD_REQUIRED (which prevents
- # "decaying" to an older standard if the requested one isn't available).
- set_property(TARGET ${_NAME} PROPERTY CXX_STANDARD ${ABSL_CXX_STANDARD})
- set_property(TARGET ${_NAME} PROPERTY CXX_STANDARD_REQUIRED ON)
- endif()
-
- install(TARGETS abseil_dll EXPORT ${PROJECT_NAME}Targets
- RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
- LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
- ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
- )
-endfunction()
diff --git a/third_party/abseil-cpp/CMake/AbseilHelpers.cmake b/third_party/abseil-cpp/CMake/AbseilHelpers.cmake
deleted file mode 100644
index 8e08d3f..0000000
--- a/third_party/abseil-cpp/CMake/AbseilHelpers.cmake
+++ /dev/null
@@ -1,449 +0,0 @@
-#
-# Copyright 2017 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(CMakeParseArguments)
-include(AbseilConfigureCopts)
-include(AbseilDll)
-
-# The IDE folder for Abseil that will be used if Abseil is included in a CMake
-# project that sets
-# set_property(GLOBAL PROPERTY USE_FOLDERS ON)
-# For example, Visual Studio supports folders.
-if(NOT DEFINED ABSL_IDE_FOLDER)
- set(ABSL_IDE_FOLDER Abseil)
-endif()
-
-if(ABSL_USE_SYSTEM_INCLUDES)
- set(ABSL_INTERNAL_INCLUDE_WARNING_GUARD SYSTEM)
-else()
- set(ABSL_INTERNAL_INCLUDE_WARNING_GUARD "")
-endif()
-
-# absl_cc_library()
-#
-# CMake function to imitate Bazel's cc_library rule.
-#
-# Parameters:
-# NAME: name of target (see Note)
-# HDRS: List of public header files for the library
-# SRCS: List of source files for the library
-# DEPS: List of other libraries to be linked in to the binary targets
-# COPTS: List of private compile options
-# DEFINES: List of public defines
-# LINKOPTS: List of link options
-# PUBLIC: Add this so that this library will be exported under absl::
-# Also in IDE, target will appear in Abseil folder while non PUBLIC will be in Abseil/internal.
-# TESTONLY: When added, this target will only be built if both
-# BUILD_TESTING=ON and ABSL_BUILD_TESTING=ON.
-#
-# Note:
-# By default, absl_cc_library will always create a library named absl_${NAME},
-# and alias target absl::${NAME}. The absl:: form should always be used.
-# This is to reduce namespace pollution.
-#
-# absl_cc_library(
-# NAME
-# awesome
-# HDRS
-# "a.h"
-# SRCS
-# "a.cc"
-# )
-# absl_cc_library(
-# NAME
-# fantastic_lib
-# SRCS
-# "b.cc"
-# DEPS
-# absl::awesome # not "awesome" !
-# PUBLIC
-# )
-#
-# absl_cc_library(
-# NAME
-# main_lib
-# ...
-# DEPS
-# absl::fantastic_lib
-# )
-#
-# TODO: Implement "ALWAYSLINK"
-function(absl_cc_library)
- cmake_parse_arguments(ABSL_CC_LIB
- "DISABLE_INSTALL;PUBLIC;TESTONLY"
- "NAME"
- "HDRS;SRCS;COPTS;DEFINES;LINKOPTS;DEPS"
- ${ARGN}
- )
-
- if(ABSL_CC_LIB_TESTONLY AND
- NOT ((BUILD_TESTING AND ABSL_BUILD_TESTING) OR
- (ABSL_BUILD_TEST_HELPERS AND ABSL_CC_LIB_PUBLIC)))
- return()
- endif()
-
- if(ABSL_ENABLE_INSTALL)
- set(_NAME "${ABSL_CC_LIB_NAME}")
- else()
- set(_NAME "absl_${ABSL_CC_LIB_NAME}")
- endif()
-
- # Check if this is a header-only library
- # Note that as of February 2019, many popular OS's (for example, Ubuntu
- # 16.04 LTS) only come with cmake 3.5 by default. For this reason, we can't
- # use list(FILTER...)
- set(ABSL_CC_SRCS "${ABSL_CC_LIB_SRCS}")
- foreach(src_file IN LISTS ABSL_CC_SRCS)
- if(${src_file} MATCHES ".*\\.(h|inc)")
- list(REMOVE_ITEM ABSL_CC_SRCS "${src_file}")
- endif()
- endforeach()
-
- if(ABSL_CC_SRCS STREQUAL "")
- set(ABSL_CC_LIB_IS_INTERFACE 1)
- else()
- set(ABSL_CC_LIB_IS_INTERFACE 0)
- endif()
-
- # Determine this build target's relationship to the DLL. It's one of four things:
- # 1. "dll" -- This target is part of the DLL
- # 2. "dll_dep" -- This target is not part of the DLL, but depends on the DLL.
- # Note that we assume any target not in the DLL depends on the
- # DLL. This is not a technical necessity but a convenience
- # which happens to be true, because nearly every target is
- # part of the DLL.
- # 3. "shared" -- This is a shared library, perhaps on a non-windows platform
- # where DLL doesn't make sense.
- # 4. "static" -- This target does not depend on the DLL and should be built
- # statically.
- if (${ABSL_BUILD_DLL})
- if(ABSL_ENABLE_INSTALL)
- absl_internal_dll_contains(TARGET ${_NAME} OUTPUT _in_dll)
- else()
- absl_internal_dll_contains(TARGET ${ABSL_CC_LIB_NAME} OUTPUT _in_dll)
- endif()
- if (${_in_dll})
- # This target should be replaced by the DLL
- set(_build_type "dll")
- set(ABSL_CC_LIB_IS_INTERFACE 1)
- else()
- # Building a DLL, but this target is not part of the DLL
- set(_build_type "dll_dep")
- endif()
- elseif(BUILD_SHARED_LIBS)
- set(_build_type "shared")
- else()
- set(_build_type "static")
- endif()
-
- # Generate a pkg-config file for every library:
- if((_build_type STREQUAL "static" OR _build_type STREQUAL "shared")
- AND ABSL_ENABLE_INSTALL)
- if(NOT ABSL_CC_LIB_TESTONLY)
- if(absl_VERSION)
- set(PC_VERSION "${absl_VERSION}")
- else()
- set(PC_VERSION "head")
- endif()
- foreach(dep ${ABSL_CC_LIB_DEPS})
- if(${dep} MATCHES "^absl::(.*)")
- # Join deps with commas.
- if(PC_DEPS)
- set(PC_DEPS "${PC_DEPS},")
- endif()
- set(PC_DEPS "${PC_DEPS} absl_${CMAKE_MATCH_1} = ${PC_VERSION}")
- endif()
- endforeach()
- foreach(cflag ${ABSL_CC_LIB_COPTS})
- if(${cflag} MATCHES "^(-Wno|/wd)")
- # These flags are needed to suppress warnings that might fire in our headers.
- set(PC_CFLAGS "${PC_CFLAGS} ${cflag}")
- elseif(${cflag} MATCHES "^(-W|/w[1234eo])")
- # Don't impose our warnings on others.
- elseif(${cflag} MATCHES "^-m")
- # Don't impose CPU instruction requirements on others, as
- # the code performs feature detection on runtime.
- else()
- set(PC_CFLAGS "${PC_CFLAGS} ${cflag}")
- endif()
- endforeach()
- string(REPLACE ";" " " PC_LINKOPTS "${ABSL_CC_LIB_LINKOPTS}")
- FILE(GENERATE OUTPUT "${CMAKE_BINARY_DIR}/lib/pkgconfig/absl_${_NAME}.pc" CONTENT "\
-prefix=${CMAKE_INSTALL_PREFIX}\n\
-exec_prefix=\${prefix}\n\
-libdir=${CMAKE_INSTALL_FULL_LIBDIR}\n\
-includedir=${CMAKE_INSTALL_FULL_INCLUDEDIR}\n\
-\n\
-Name: absl_${_NAME}\n\
-Description: Abseil ${_NAME} library\n\
-URL: https://abseil.io/\n\
-Version: ${PC_VERSION}\n\
-Requires:${PC_DEPS}\n\
-Libs: -L\${libdir} ${PC_LINKOPTS} $<$<NOT:$<BOOL:${ABSL_CC_LIB_IS_INTERFACE}>>:-labsl_${_NAME}>\n\
-Cflags: -I\${includedir}${PC_CFLAGS}\n")
- INSTALL(FILES "${CMAKE_BINARY_DIR}/lib/pkgconfig/absl_${_NAME}.pc"
- DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig")
- endif()
- endif()
-
- if(NOT ABSL_CC_LIB_IS_INTERFACE)
- if(_build_type STREQUAL "dll_dep")
- # This target depends on the DLL. When adding dependencies to this target,
- # any depended-on-target which is contained inside the DLL is replaced
- # with a dependency on the DLL.
- add_library(${_NAME} STATIC "")
- target_sources(${_NAME} PRIVATE ${ABSL_CC_LIB_SRCS} ${ABSL_CC_LIB_HDRS})
- absl_internal_dll_targets(
- DEPS ${ABSL_CC_LIB_DEPS}
- OUTPUT _dll_deps
- )
- target_link_libraries(${_NAME}
- PUBLIC ${_dll_deps}
- PRIVATE
- ${ABSL_CC_LIB_LINKOPTS}
- ${ABSL_DEFAULT_LINKOPTS}
- )
-
- if (ABSL_CC_LIB_TESTONLY)
- set(_gtest_link_define "GTEST_LINKED_AS_SHARED_LIBRARY=1")
- else()
- set(_gtest_link_define)
- endif()
-
- target_compile_definitions(${_NAME}
- PUBLIC
- ABSL_CONSUME_DLL
- "${_gtest_link_define}"
- )
-
- elseif(_build_type STREQUAL "static" OR _build_type STREQUAL "shared")
- add_library(${_NAME} "")
- target_sources(${_NAME} PRIVATE ${ABSL_CC_LIB_SRCS} ${ABSL_CC_LIB_HDRS})
- target_link_libraries(${_NAME}
- PUBLIC ${ABSL_CC_LIB_DEPS}
- PRIVATE
- ${ABSL_CC_LIB_LINKOPTS}
- ${ABSL_DEFAULT_LINKOPTS}
- )
- else()
- message(FATAL_ERROR "Invalid build type: ${_build_type}")
- endif()
-
- # Linker language can be inferred from sources, but in the case of DLLs we
- # don't have any .cc files so it would be ambiguous. We could set it
- # explicitly only in the case of DLLs but, because "CXX" is always the
- # correct linker language for static or for shared libraries, we set it
- # unconditionally.
- set_property(TARGET ${_NAME} PROPERTY LINKER_LANGUAGE "CXX")
-
- target_include_directories(${_NAME} ${ABSL_INTERNAL_INCLUDE_WARNING_GUARD}
- PUBLIC
- "$<BUILD_INTERFACE:${ABSL_COMMON_INCLUDE_DIRS}>"
- $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
- )
- target_compile_options(${_NAME}
- PRIVATE ${ABSL_CC_LIB_COPTS})
- target_compile_definitions(${_NAME} PUBLIC ${ABSL_CC_LIB_DEFINES})
-
- # Add all Abseil targets to a a folder in the IDE for organization.
- if(ABSL_CC_LIB_PUBLIC)
- set_property(TARGET ${_NAME} PROPERTY FOLDER ${ABSL_IDE_FOLDER})
- elseif(ABSL_CC_LIB_TESTONLY)
- set_property(TARGET ${_NAME} PROPERTY FOLDER ${ABSL_IDE_FOLDER}/test)
- else()
- set_property(TARGET ${_NAME} PROPERTY FOLDER ${ABSL_IDE_FOLDER}/internal)
- endif()
-
- if(ABSL_PROPAGATE_CXX_STD)
- # Abseil libraries require C++14 as the current minimum standard. When
- # compiled with C++17 (either because it is the compiler's default or
- # explicitly requested), then Abseil requires C++17.
- _absl_target_compile_features_if_available(${_NAME} PUBLIC ${ABSL_INTERNAL_CXX_STD_FEATURE})
- else()
- # Note: This is legacy (before CMake 3.8) behavior. Setting the
- # target-level CXX_STANDARD property to ABSL_CXX_STANDARD (which is
- # initialized by CMAKE_CXX_STANDARD) should have no real effect, since
- # that is the default value anyway.
- #
- # CXX_STANDARD_REQUIRED does guard against the top-level CMake project
- # not having enabled CMAKE_CXX_STANDARD_REQUIRED (which prevents
- # "decaying" to an older standard if the requested one isn't available).
- set_property(TARGET ${_NAME} PROPERTY CXX_STANDARD ${ABSL_CXX_STANDARD})
- set_property(TARGET ${_NAME} PROPERTY CXX_STANDARD_REQUIRED ON)
- endif()
-
- # When being installed, we lose the absl_ prefix. We want to put it back
- # to have properly named lib files. This is a no-op when we are not being
- # installed.
- if(ABSL_ENABLE_INSTALL)
- set_target_properties(${_NAME} PROPERTIES
- OUTPUT_NAME "absl_${_NAME}"
- SOVERSION 0
- )
- endif()
- else()
- # Generating header-only library
- add_library(${_NAME} INTERFACE)
- target_include_directories(${_NAME} ${ABSL_INTERNAL_INCLUDE_WARNING_GUARD}
- INTERFACE
- "$<BUILD_INTERFACE:${ABSL_COMMON_INCLUDE_DIRS}>"
- $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
- )
-
- if (_build_type STREQUAL "dll")
- set(ABSL_CC_LIB_DEPS abseil_dll)
- endif()
-
- target_link_libraries(${_NAME}
- INTERFACE
- ${ABSL_CC_LIB_DEPS}
- ${ABSL_CC_LIB_LINKOPTS}
- ${ABSL_DEFAULT_LINKOPTS}
- )
- target_compile_definitions(${_NAME} INTERFACE ${ABSL_CC_LIB_DEFINES})
-
- if(ABSL_PROPAGATE_CXX_STD)
- # Abseil libraries require C++14 as the current minimum standard.
- # Top-level application CMake projects should ensure a consistent C++
- # standard for all compiled sources by setting CMAKE_CXX_STANDARD.
- _absl_target_compile_features_if_available(${_NAME} INTERFACE ${ABSL_INTERNAL_CXX_STD_FEATURE})
-
- # (INTERFACE libraries can't have the CXX_STANDARD property set, so there
- # is no legacy behavior else case).
- endif()
- endif()
-
- # TODO currently we don't install googletest alongside abseil sources, so
- # installed abseil can't be tested.
- if(NOT ABSL_CC_LIB_TESTONLY AND ABSL_ENABLE_INSTALL)
- install(TARGETS ${_NAME} EXPORT ${PROJECT_NAME}Targets
- RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
- LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
- ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
- )
- endif()
-
- add_library(absl::${ABSL_CC_LIB_NAME} ALIAS ${_NAME})
-endfunction()
-
-# absl_cc_test()
-#
-# CMake function to imitate Bazel's cc_test rule.
-#
-# Parameters:
-# NAME: name of target (see Usage below)
-# SRCS: List of source files for the binary
-# DEPS: List of other libraries to be linked in to the binary targets
-# COPTS: List of private compile options
-# DEFINES: List of public defines
-# LINKOPTS: List of link options
-#
-# Note:
-# By default, absl_cc_test will always create a binary named absl_${NAME}.
-# This will also add it to ctest list as absl_${NAME}.
-#
-# Usage:
-# absl_cc_library(
-# NAME
-# awesome
-# HDRS
-# "a.h"
-# SRCS
-# "a.cc"
-# PUBLIC
-# )
-#
-# absl_cc_test(
-# NAME
-# awesome_test
-# SRCS
-# "awesome_test.cc"
-# DEPS
-# absl::awesome
-# GTest::gmock
-# GTest::gtest_main
-# )
-function(absl_cc_test)
- if(NOT (BUILD_TESTING AND ABSL_BUILD_TESTING))
- return()
- endif()
-
- cmake_parse_arguments(ABSL_CC_TEST
- ""
- "NAME"
- "SRCS;COPTS;DEFINES;LINKOPTS;DEPS"
- ${ARGN}
- )
-
- set(_NAME "absl_${ABSL_CC_TEST_NAME}")
-
- add_executable(${_NAME} "")
- target_sources(${_NAME} PRIVATE ${ABSL_CC_TEST_SRCS})
- target_include_directories(${_NAME}
- PUBLIC ${ABSL_COMMON_INCLUDE_DIRS}
- PRIVATE ${GMOCK_INCLUDE_DIRS} ${GTEST_INCLUDE_DIRS}
- )
-
- if (${ABSL_BUILD_DLL})
- target_compile_definitions(${_NAME}
- PUBLIC
- ${ABSL_CC_TEST_DEFINES}
- ABSL_CONSUME_DLL
- GTEST_LINKED_AS_SHARED_LIBRARY=1
- )
-
- # Replace dependencies on targets inside the DLL with abseil_dll itself.
- absl_internal_dll_targets(
- DEPS ${ABSL_CC_TEST_DEPS}
- OUTPUT ABSL_CC_TEST_DEPS
- )
- else()
- target_compile_definitions(${_NAME}
- PUBLIC
- ${ABSL_CC_TEST_DEFINES}
- )
- endif()
- target_compile_options(${_NAME}
- PRIVATE ${ABSL_CC_TEST_COPTS}
- )
-
- target_link_libraries(${_NAME}
- PUBLIC ${ABSL_CC_TEST_DEPS}
- PRIVATE ${ABSL_CC_TEST_LINKOPTS}
- )
- # Add all Abseil targets to a folder in the IDE for organization.
- set_property(TARGET ${_NAME} PROPERTY FOLDER ${ABSL_IDE_FOLDER}/test)
-
- if(ABSL_PROPAGATE_CXX_STD)
- # Abseil libraries require C++14 as the current minimum standard.
- # Top-level application CMake projects should ensure a consistent C++
- # standard for all compiled sources by setting CMAKE_CXX_STANDARD.
- _absl_target_compile_features_if_available(${_NAME} PUBLIC ${ABSL_INTERNAL_CXX_STD_FEATURE})
- else()
- # Note: This is legacy (before CMake 3.8) behavior. Setting the
- # target-level CXX_STANDARD property to ABSL_CXX_STANDARD (which is
- # initialized by CMAKE_CXX_STANDARD) should have no real effect, since
- # that is the default value anyway.
- #
- # CXX_STANDARD_REQUIRED does guard against the top-level CMake project
- # not having enabled CMAKE_CXX_STANDARD_REQUIRED (which prevents
- # "decaying" to an older standard if the requested one isn't available).
- set_property(TARGET ${_NAME} PROPERTY CXX_STANDARD ${ABSL_CXX_STANDARD})
- set_property(TARGET ${_NAME} PROPERTY CXX_STANDARD_REQUIRED ON)
- endif()
-
- add_test(NAME ${_NAME} COMMAND ${_NAME})
-endfunction()
diff --git a/third_party/abseil-cpp/CMake/Googletest/CMakeLists.txt.in b/third_party/abseil-cpp/CMake/Googletest/CMakeLists.txt.in
deleted file mode 100644
index 75691b1..0000000
--- a/third_party/abseil-cpp/CMake/Googletest/CMakeLists.txt.in
+++ /dev/null
@@ -1,14 +0,0 @@
-cmake_minimum_required(VERSION 3.10)
-
-project(googletest-external NONE)
-
-include(ExternalProject)
-ExternalProject_Add(googletest
- URL "${absl_gtest_download_url}" # May be empty
- SOURCE_DIR "${absl_gtest_src_dir}"
- BINARY_DIR "${absl_gtest_build_dir}"
- CONFIGURE_COMMAND ""
- BUILD_COMMAND ""
- INSTALL_COMMAND ""
- TEST_COMMAND ""
-)
diff --git a/third_party/abseil-cpp/CMake/Googletest/DownloadGTest.cmake b/third_party/abseil-cpp/CMake/Googletest/DownloadGTest.cmake
deleted file mode 100644
index 9d071c9..0000000
--- a/third_party/abseil-cpp/CMake/Googletest/DownloadGTest.cmake
+++ /dev/null
@@ -1,41 +0,0 @@
-# Integrates googletest at configure time. Based on the instructions at
-# https://github.com/google/googletest/tree/master/googletest#incorporating-into-an-existing-cmake-project
-
-# Set up the external googletest project, downloading the latest from Github
-# master if requested.
-configure_file(
- ${CMAKE_CURRENT_LIST_DIR}/CMakeLists.txt.in
- ${CMAKE_BINARY_DIR}/googletest-external/CMakeLists.txt
-)
-
-set(ABSL_SAVE_CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS})
-set(ABSL_SAVE_CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY})
-if (BUILD_SHARED_LIBS)
- set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DGTEST_CREATE_SHARED_LIBRARY=1")
-endif()
-
-# Configure and build the googletest source.
-execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" .
- RESULT_VARIABLE result
- WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-external )
-if(result)
- message(FATAL_ERROR "CMake step for googletest failed: ${result}")
-endif()
-
-execute_process(COMMAND ${CMAKE_COMMAND} --build .
- RESULT_VARIABLE result
- WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-external)
-if(result)
- message(FATAL_ERROR "Build step for googletest failed: ${result}")
-endif()
-
-set(CMAKE_CXX_FLAGS ${ABSL_SAVE_CMAKE_CXX_FLAGS})
-set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${ABSL_SAVE_CMAKE_RUNTIME_OUTPUT_DIRECTORY})
-
-# Prevent overriding the parent project's compiler/linker settings on Windows
-set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
-
-# Add googletest directly to our build. This defines the gtest and gtest_main
-# targets.
-add_subdirectory(${absl_gtest_src_dir} ${absl_gtest_build_dir} EXCLUDE_FROM_ALL)
diff --git a/third_party/abseil-cpp/CMake/README.md b/third_party/abseil-cpp/CMake/README.md
deleted file mode 100644
index 19fb327..0000000
--- a/third_party/abseil-cpp/CMake/README.md
+++ /dev/null
@@ -1,188 +0,0 @@
-# Abseil CMake Build Instructions
-
-Abseil comes with a CMake build script ([CMakeLists.txt](../CMakeLists.txt))
-that can be used on a wide range of platforms ("C" stands for cross-platform.).
-If you don't have CMake installed already, you can download it for free from
-<https://www.cmake.org/>.
-
-CMake works by generating native makefiles or build projects that can
-be used in the compiler environment of your choice.
-
-For API/ABI compatibility reasons, we strongly recommend building Abseil in a
-subdirectory of your project or as an embedded dependency.
-
-## Incorporating Abseil Into a CMake Project
-
-The recommendations below are similar to those for using CMake within the
-googletest framework
-(<https://github.com/google/googletest/blob/master/googletest/README.md#incorporating-into-an-existing-cmake-project>)
-
-### Step-by-Step Instructions
-
-1. If you want to build the Abseil tests, integrate the Abseil dependency
-[Google Test](https://github.com/google/googletest) into your CMake
-project. To disable Abseil tests, you have to pass either
-`-DBUILD_TESTING=OFF` or `-DABSL_BUILD_TESTING=OFF` when configuring your
-project with CMake.
-
-2. Download Abseil and copy it into a subdirectory in your CMake project or add
-Abseil as a [git submodule](https://git-scm.com/docs/git-submodule) in your
-CMake project.
-
-3. You can then use the CMake command
-[`add_subdirectory()`](https://cmake.org/cmake/help/latest/command/add_subdirectory.html)
-to include Abseil directly in your CMake project.
-
-4. Add the **absl::** target you wish to use to the
-[`target_link_libraries()`](https://cmake.org/cmake/help/latest/command/target_link_libraries.html)
-section of your executable or of your library.<br>
-Here is a short CMakeLists.txt example of an application project using Abseil.
-
-```cmake
-cmake_minimum_required(VERSION 3.10)
-project(my_app_project)
-
-# Pick the C++ standard to compile with.
-# Abseil currently supports C++14, C++17, and C++20.
-set(CMAKE_CXX_STANDARD 14)
-set(CMAKE_CXX_STANDARD_REQUIRED ON)
-
-add_subdirectory(abseil-cpp)
-
-add_executable(my_exe source.cpp)
-target_link_libraries(my_exe absl::base absl::synchronization absl::strings)
-```
-
-Note that if you are developing a library designed for use by other clients, you
-should instead leave `CMAKE_CXX_STANDARD` unset (or only set if being built as
-the current top-level CMake project) and configure the minimum required C++
-standard at the target level. If you require a later minimum C++ standard than
-Abseil does, it's a good idea to also enforce that `CMAKE_CXX_STANDARD` (which
-will control Abseil library targets) is set to at least that minimum. For
-example:
-
-```cmake
-cmake_minimum_required(VERSION 3.10)
-project(my_lib_project)
-
-# Leave C++ standard up to the root application, so set it only if this is the
-# current top-level CMake project.
-if(CMAKE_SOURCE_DIR STREQUAL my_lib_project_SOURCE_DIR)
- set(CMAKE_CXX_STANDARD 17)
- set(CMAKE_CXX_STANDARD_REQUIRED ON)
-endif()
-
-add_subdirectory(abseil-cpp)
-
-add_library(my_lib source.cpp)
-target_link_libraries(my_lib absl::base absl::synchronization absl::strings)
-
-# Enforce that my_lib requires C++17. Important to document for clients that they
-# must set CMAKE_CXX_STANDARD to 17 or higher for proper Abseil ABI compatibility
-# (since otherwise, Abseil library targets could be compiled with a lower C++
-# standard than my_lib).
-target_compile_features(my_lib PUBLIC cxx_std_17)
-if(CMAKE_CXX_STANDARD LESS 17)
- message(FATAL_ERROR
- "my_lib_project requires CMAKE_CXX_STANDARD >= 17 (got: ${CMAKE_CXX_STANDARD})")
-endif()
-```
-
-Then the top-level application project that uses your library is responsible for
-setting a consistent `CMAKE_CXX_STANDARD` that is sufficiently high.
-
-### Running Abseil Tests with CMake
-
-Use the `-DABSL_BUILD_TESTING=ON` flag to run Abseil tests. Note that
-BUILD_TESTING must also be on (the default).
-
-You will need to provide Abseil with a Googletest dependency. There are two
-options for how to do this:
-
-* Use `-DABSL_USE_GOOGLETEST_HEAD`. This will automatically download the latest
-Googletest source into the build directory at configure time. Googletest will
-then be compiled directly alongside Abseil's tests.
-* Manually integrate Googletest with your build. See
-https://github.com/google/googletest/blob/master/googletest/README.md#using-cmake
-for more information on using Googletest in a CMake project.
-
-For example, to run just the Abseil tests, you could use this script:
-
-```
-cd path/to/abseil-cpp
-mkdir build
-cd build
-cmake -DABSL_BUILD_TESTING=ON -DABSL_USE_GOOGLETEST_HEAD=ON ..
-make -j
-ctest
-```
-
-Currently, we only run our tests with CMake in a Linux environment, but we are
-working on the rest of our supported platforms. See
-https://github.com/abseil/abseil-cpp/projects/1 and
-https://github.com/abseil/abseil-cpp/issues/109 for more information.
-
-### Available Abseil CMake Public Targets
-
-Here's a non-exhaustive list of Abseil CMake public targets:
-
-```cmake
-absl::algorithm
-absl::base
-absl::debugging
-absl::flat_hash_map
-absl::flags
-absl::memory
-absl::meta
-absl::numeric
-absl::random_random
-absl::strings
-absl::synchronization
-absl::time
-absl::utility
-```
-
-## Traditional CMake Set-Up
-
-For larger projects, it may make sense to use the traditional CMake set-up where you build and install projects separately.
-
-First, you'd need to build and install Google Test:
-```
-cmake -S /source/googletest -B /build/googletest -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/installation/dir -DBUILD_GMOCK=ON
-cmake --build /build/googletest --target install
-```
-
-Then you need to configure and build Abseil. Make sure you enable `ABSL_USE_EXTERNAL_GOOGLETEST` and `ABSL_FIND_GOOGLETEST`. You also need to enable `ABSL_ENABLE_INSTALL` so that you can install Abseil itself.
-```
-cmake -S /source/abseil-cpp -B /build/abseil-cpp -DCMAKE_PREFIX_PATH=/installation/dir -DCMAKE_INSTALL_PREFIX=/installation/dir -DABSL_ENABLE_INSTALL=ON -DABSL_USE_EXTERNAL_GOOGLETEST=ON -DABSL_FIND_GOOGLETEST=ON
-cmake --build /temporary/build/abseil-cpp
-```
-
-(`CMAKE_PREFIX_PATH` is where you already have Google Test installed; `CMAKE_INSTALL_PREFIX` is where you want to have Abseil installed; they can be different.)
-
-Run the tests:
-```
-ctest --test-dir /temporary/build/abseil-cpp
-```
-
-And finally install:
-```
-cmake --build /temporary/build/abseil-cpp --target install
-```
-
-# CMake Option Synposis
-
-## Enable Standard CMake Installation
-
-`-DABSL_ENABLE_INSTALL=ON`
-
-## Google Test Options
-
-`-DABSL_BUILD_TESTING=ON` must be set to enable testing
-
-- Have Abseil download and build Google Test for you: `-DABSL_USE_EXTERNAL_GOOGLETEST=OFF` (default)
- - Download and build latest Google Test: `-DABSL_USE_GOOGLETEST_HEAD=ON`
- - Download specific Google Test version (ZIP archive): `-DABSL_GOOGLETEST_DOWNLOAD_URL=https://.../version.zip`
- - Use Google Test from specific local directory: `-DABSL_LOCAL_GOOGLETEST_DIR=/path/to/googletest`
-- Use Google Test included elsewhere in your project: `-DABSL_USE_EXTERNAL_GOOGLETEST=ON`
-- Use standard CMake `find_package(CTest)` to find installed Google Test: `-DABSL_USE_EXTERNAL_GOOGLETEST=ON -DABSL_FIND_GOOGLETEST=ON`
diff --git a/third_party/abseil-cpp/CMake/abslConfig.cmake.in b/third_party/abseil-cpp/CMake/abslConfig.cmake.in
deleted file mode 100644
index 62d246d..0000000
--- a/third_party/abseil-cpp/CMake/abslConfig.cmake.in
+++ /dev/null
@@ -1,8 +0,0 @@
-# absl CMake configuration file.
-
-include(CMakeFindDependencyMacro)
-find_dependency(Threads)
-
-@PACKAGE_INIT@
-
-include ("${CMAKE_CURRENT_LIST_DIR}/@PROJECT_NAME@Targets.cmake")
diff --git a/third_party/abseil-cpp/CMake/install_test_project/CMakeLists.txt b/third_party/abseil-cpp/CMake/install_test_project/CMakeLists.txt
deleted file mode 100644
index 30c23b2..0000000
--- a/third_party/abseil-cpp/CMake/install_test_project/CMakeLists.txt
+++ /dev/null
@@ -1,25 +0,0 @@
-#
-# Copyright 2019 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.
-
-# A simple CMakeLists.txt for testing cmake installation
-
-cmake_minimum_required(VERSION 3.10)
-project(absl_cmake_testing CXX)
-
-add_executable(simple simple.cc)
-
-find_package(absl REQUIRED)
-
-target_link_libraries(simple absl::strings absl::config)
diff --git a/third_party/abseil-cpp/CMake/install_test_project/simple.cc b/third_party/abseil-cpp/CMake/install_test_project/simple.cc
deleted file mode 100644
index 7daa7f0..0000000
--- a/third_party/abseil-cpp/CMake/install_test_project/simple.cc
+++ /dev/null
@@ -1,32 +0,0 @@
-//
-// Copyright 2019 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 <iostream>
-#include "absl/base/config.h"
-#include "absl/strings/substitute.h"
-
-#if !defined(ABSL_LTS_RELEASE_VERSION) || ABSL_LTS_RELEASE_VERSION != 99998877
-#error ABSL_LTS_RELEASE_VERSION is not set correctly.
-#endif
-
-#if !defined(ABSL_LTS_RELEASE_PATCH_LEVEL) || ABSL_LTS_RELEASE_PATCH_LEVEL != 0
-#error ABSL_LTS_RELEASE_PATCH_LEVEL is not set correctly.
-#endif
-
-int main(int argc, char** argv) {
- for (int i = 0; i < argc; ++i) {
- std::cout << absl::Substitute("Arg $0: $1\n", i, argv[i]);
- }
-}
diff --git a/third_party/abseil-cpp/CMake/install_test_project/test.sh b/third_party/abseil-cpp/CMake/install_test_project/test.sh
deleted file mode 100755
index cc028ba..0000000
--- a/third_party/abseil-cpp/CMake/install_test_project/test.sh
+++ /dev/null
@@ -1,112 +0,0 @@
-#!/bin/bash
-#
-# Copyright 2019 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.
-#
-# Unit and integration tests for Abseil LTS CMake installation
-
-# Fail on any error. Treat unset variables an error. Print commands as executed.
-set -euox pipefail
-
-absl_dir=/abseil-cpp
-absl_build_dir=/buildfs
-googletest_builddir=/googletest_builddir
-project_dir="${absl_dir}"/CMake/install_test_project
-project_build_dir=/buildfs/project-build
-
-build_shared_libs="OFF"
-if [ "${LINK_TYPE:-}" = "DYNAMIC" ]; then
- build_shared_libs="ON"
-fi
-
-# Build and install GoogleTest
-mkdir "${googletest_builddir}"
-pushd "${googletest_builddir}"
-curl -L "${ABSL_GOOGLETEST_DOWNLOAD_URL}" --output "${ABSL_GOOGLETEST_COMMIT}".zip
-unzip "${ABSL_GOOGLETEST_COMMIT}".zip
-pushd "googletest-${ABSL_GOOGLETEST_COMMIT}"
-mkdir build
-pushd build
-cmake -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS="${build_shared_libs}" ..
-make -j $(nproc)
-make install
-ldconfig
-popd
-popd
-popd
-
-# Run the LTS transformations
-./create_lts.py 99998877
-
-# Build and install Abseil
-pushd "${absl_build_dir}"
-cmake "${absl_dir}" \
- -DABSL_USE_EXTERNAL_GOOGLETEST=ON \
- -DABSL_FIND_GOOGLETEST=ON \
- -DCMAKE_BUILD_TYPE=Release \
- -DABSL_BUILD_TESTING=ON \
- -DBUILD_SHARED_LIBS="${build_shared_libs}"
-make -j $(nproc)
-ctest -j $(nproc) --output-on-failure
-make install
-ldconfig
-popd
-
-# Test the project against the installed Abseil
-mkdir -p "${project_build_dir}"
-pushd "${project_build_dir}"
-cmake "${project_dir}"
-cmake --build . --target simple
-
-output="$(${project_build_dir}/simple "printme" 2>&1)"
-if [[ "${output}" != *"Arg 1: printme"* ]]; then
- echo "Faulty output on simple project:"
- echo "${output}"
- exit 1
-fi
-
-popd
-
-if ! grep absl::strings "/usr/local/lib/cmake/absl/abslTargets.cmake"; then
- cat "/usr/local/lib/cmake/absl/abslTargets.cmake"
- echo "CMake targets named incorrectly"
- exit 1
-fi
-
-pushd "${HOME}"
-cat > hello-abseil.cc << EOF
-#include <cstdlib>
-
-#include "absl/strings/str_format.h"
-
-int main(int argc, char **argv) {
- absl::PrintF("Hello Abseil!\n");
- return EXIT_SUCCESS;
-}
-EOF
-
-if [ "${LINK_TYPE:-}" != "DYNAMIC" ]; then
- pc_args=($(pkg-config --cflags --libs --static absl_str_format))
- g++ -static -o hello-abseil hello-abseil.cc "${pc_args[@]}"
-else
- pc_args=($(pkg-config --cflags --libs absl_str_format))
- g++ -o hello-abseil hello-abseil.cc "${pc_args[@]}"
-fi
-hello="$(./hello-abseil)"
-[[ "${hello}" == "Hello Abseil!" ]]
-
-popd
-
-echo "Install test complete!"
-exit 0
diff --git a/third_party/abseil-cpp/CMakeLists.txt b/third_party/abseil-cpp/CMakeLists.txt
deleted file mode 100644
index 9e10257..0000000
--- a/third_party/abseil-cpp/CMakeLists.txt
+++ /dev/null
@@ -1,249 +0,0 @@
-#
-# Copyright 2017 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.
-#
-
-# https://github.com/google/oss-policies-info/blob/main/foundational-cxx-support-matrix.md
-# As of 2022-09-06, CMake 3.10 is the minimum supported version.
-cmake_minimum_required(VERSION 3.10)
-
-# Compiler id for Apple Clang is now AppleClang.
-if (POLICY CMP0025)
- cmake_policy(SET CMP0025 NEW)
-endif (POLICY CMP0025)
-
-# if command can use IN_LIST
-if (POLICY CMP0057)
- cmake_policy(SET CMP0057 NEW)
-endif (POLICY CMP0057)
-
-# Project version variables are the empty string if version is unspecified
-if (POLICY CMP0048)
- cmake_policy(SET CMP0048 NEW)
-endif (POLICY CMP0048)
-
-# option() honor variables
-if (POLICY CMP0077)
- cmake_policy(SET CMP0077 NEW)
-endif (POLICY CMP0077)
-
-# Allow the user to specify the MSVC runtime
-if (POLICY CMP0091)
- cmake_policy(SET CMP0091 NEW)
-endif (POLICY CMP0091)
-
-# try_compile() honors the CMAKE_CXX_STANDARD value
-if (POLICY CMP0067)
- cmake_policy(SET CMP0067 NEW)
-endif (POLICY CMP0067)
-
-project(absl LANGUAGES CXX)
-include(CTest)
-
-# Output directory is correct by default for most build setups. However, when
-# building Abseil as a DLL, it is important to have the DLL in the same
-# directory as the executable using it. Thus, we put all executables in a single
-# /bin directory.
-set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
-
-# when absl is included as subproject (i.e. using add_subdirectory(abseil-cpp))
-# in the source tree of a project that uses it, install rules are disabled.
-if(NOT CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
- option(ABSL_ENABLE_INSTALL "Enable install rule" OFF)
-else()
- option(ABSL_ENABLE_INSTALL "Enable install rule" ON)
-endif()
-
-option(ABSL_PROPAGATE_CXX_STD
- "Use CMake C++ standard meta features (e.g. cxx_std_14) that propagate to targets that link to Abseil"
- OFF) # TODO: Default to ON for CMake 3.8 and greater.
-if((${CMAKE_VERSION} VERSION_GREATER_EQUAL 3.8) AND (NOT ABSL_PROPAGATE_CXX_STD))
- message(WARNING "A future Abseil release will default ABSL_PROPAGATE_CXX_STD to ON for CMake 3.8 and up. We recommend enabling this option to ensure your project still builds correctly.")
-endif()
-
-option(ABSL_USE_SYSTEM_INCLUDES
- "Silence warnings in Abseil headers by marking them as SYSTEM includes"
- OFF)
-
-list(APPEND CMAKE_MODULE_PATH
- ${CMAKE_CURRENT_LIST_DIR}/CMake
- ${CMAKE_CURRENT_LIST_DIR}/absl/copts
-)
-
-include(CMakePackageConfigHelpers)
-include(GNUInstallDirs)
-include(AbseilDll)
-include(AbseilHelpers)
-
-
-##
-## Using absl targets
-##
-## all public absl targets are
-## exported with the absl:: prefix
-##
-## e.g absl::base absl::synchronization absl::strings ....
-##
-## DO NOT rely on the internal targets outside of the prefix
-
-
-# include current path
-list(APPEND ABSL_COMMON_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR})
-
-if("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
- set(ABSL_USING_CLANG ON)
-else()
- set(ABSL_USING_CLANG OFF)
-endif()
-
-# find dependencies
-## pthread
-find_package(Threads REQUIRED)
-
-include(CMakeDependentOption)
-
-option(ABSL_BUILD_TESTING
- "If ON, Abseil will build all of Abseil's own tests." OFF)
-
-option(ABSL_BUILD_TEST_HELPERS
- "If ON, Abseil will build libraries that you can use to write tests against Abseil code. This option requires that Abseil is configured to use GoogleTest."
- OFF)
-
-option(ABSL_USE_EXTERNAL_GOOGLETEST
- "If ON, Abseil will assume that the targets for GoogleTest are already provided by the including project. This makes sense when Abseil is used with add_subdirectory." OFF)
-
-cmake_dependent_option(ABSL_FIND_GOOGLETEST
- "If ON, Abseil will use find_package(GTest) rather than assuming that GoogleTest is already provided by the including project."
- ON
- "ABSL_USE_EXTERNAL_GOOGLETEST"
- OFF)
-
-
-option(ABSL_USE_GOOGLETEST_HEAD
- "If ON, abseil will download HEAD from GoogleTest at config time." OFF)
-
-set(ABSL_GOOGLETEST_DOWNLOAD_URL "" CACHE STRING "If set, download GoogleTest from this URL")
-
-set(ABSL_LOCAL_GOOGLETEST_DIR "/usr/src/googletest" CACHE PATH
- "If ABSL_USE_GOOGLETEST_HEAD is OFF and ABSL_GOOGLETEST_URL is not set, specifies the directory of a local GoogleTest checkout."
- )
-
-if((BUILD_TESTING AND ABSL_BUILD_TESTING) OR ABSL_BUILD_TEST_HELPERS)
- if (ABSL_USE_EXTERNAL_GOOGLETEST)
- if (ABSL_FIND_GOOGLETEST)
- find_package(GTest REQUIRED)
- elseif(NOT TARGET GTest::gtest)
- if(TARGET gtest)
- # When Google Test is included directly rather than through find_package, the aliases are missing.
- add_library(GTest::gtest ALIAS gtest)
- add_library(GTest::gtest_main ALIAS gtest_main)
- add_library(GTest::gmock ALIAS gmock)
- add_library(GTest::gmock_main ALIAS gmock_main)
- else()
- message(FATAL_ERROR "ABSL_USE_EXTERNAL_GOOGLETEST is ON and ABSL_FIND_GOOGLETEST is OFF, which means that the top-level project must build the Google Test project. However, the target gtest was not found.")
- endif()
- endif()
- else()
- set(absl_gtest_build_dir ${CMAKE_BINARY_DIR}/googletest-build)
- if(ABSL_USE_GOOGLETEST_HEAD AND ABSL_GOOGLETEST_DOWNLOAD_URL)
- message(FATAL_ERROR "Do not set both ABSL_USE_GOOGLETEST_HEAD and ABSL_GOOGLETEST_DOWNLOAD_URL")
- endif()
- if(ABSL_USE_GOOGLETEST_HEAD)
- set(absl_gtest_download_url "https://github.com/google/googletest/archive/main.zip")
- elseif(ABSL_GOOGLETEST_DOWNLOAD_URL)
- set(absl_gtest_download_url ${ABSL_GOOGLETEST_DOWNLOAD_URL})
- endif()
- if(absl_gtest_download_url)
- set(absl_gtest_src_dir ${CMAKE_BINARY_DIR}/googletest-src)
- else()
- set(absl_gtest_src_dir ${ABSL_LOCAL_GOOGLETEST_DIR})
- endif()
- include(CMake/Googletest/DownloadGTest.cmake)
- endif()
-endif()
-
-add_subdirectory(absl)
-
-if(ABSL_ENABLE_INSTALL)
- # absl:lts-remove-begin(system installation is supported for LTS releases)
- # We don't support system-wide installation
- list(APPEND SYSTEM_INSTALL_DIRS "/usr/local" "/usr" "/opt/" "/opt/local" "c:/Program Files/${PROJECT_NAME}")
- if(NOT DEFINED CMAKE_INSTALL_PREFIX OR CMAKE_INSTALL_PREFIX IN_LIST SYSTEM_INSTALL_DIRS)
- message(WARNING "\
- The default and system-level install directories are unsupported except in LTS \
- releases of Abseil. Please set CMAKE_INSTALL_PREFIX to install Abseil in your \
- source or build tree directly.\
- ")
- endif()
- # absl:lts-remove-end
-
- # install as a subdirectory only
- install(EXPORT ${PROJECT_NAME}Targets
- NAMESPACE absl::
- DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}"
- )
-
- configure_package_config_file(
- CMake/abslConfig.cmake.in
- "${PROJECT_BINARY_DIR}/${PROJECT_NAME}Config.cmake"
- INSTALL_DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}"
- )
- install(FILES "${PROJECT_BINARY_DIR}/${PROJECT_NAME}Config.cmake"
- DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}"
- )
-
- # Abseil only has a version in LTS releases. This mechanism is accomplished
- # Abseil's internal Copybara (https://github.com/google/copybara) workflows and
- # isn't visible in the CMake buildsystem itself.
- if(absl_VERSION)
- write_basic_package_version_file(
- "${PROJECT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake"
- COMPATIBILITY ExactVersion
- )
-
- install(FILES "${PROJECT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake"
- DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}"
- )
- endif() # absl_VERSION
-
- install(DIRECTORY absl
- DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
- FILES_MATCHING
- PATTERN "*.inc"
- PATTERN "*.h"
- PATTERN "copts" EXCLUDE
- PATTERN "testdata" EXCLUDE
- )
-
- file(READ "absl/base/options.h" ABSL_INTERNAL_OPTIONS_H_CONTENTS)
- if (ABSL_INTERNAL_AT_LEAST_CXX17)
- string(REGEX REPLACE
- "#define ABSL_OPTION_USE_STD_([^ ]*) 2"
- "#define ABSL_OPTION_USE_STD_\\1 1"
- ABSL_INTERNAL_OPTIONS_H_PINNED
- "${ABSL_INTERNAL_OPTIONS_H_CONTENTS}")
- else()
- string(REGEX REPLACE
- "#define ABSL_OPTION_USE_STD_([^ ]*) 2"
- "#define ABSL_OPTION_USE_STD_\\1 0"
- ABSL_INTERNAL_OPTIONS_H_PINNED
- "${ABSL_INTERNAL_OPTIONS_H_CONTENTS}")
- endif()
- file(WRITE "${CMAKE_BINARY_DIR}/options-pinned.h" "${ABSL_INTERNAL_OPTIONS_H_PINNED}")
-
- install(FILES "${CMAKE_BINARY_DIR}/options-pinned.h"
- DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/absl/base
- RENAME "options.h")
-
-endif() # ABSL_ENABLE_INSTALL
diff --git a/third_party/abseil-cpp/CONTRIBUTING.md b/third_party/abseil-cpp/CONTRIBUTING.md
deleted file mode 100644
index 9dadae9..0000000
--- a/third_party/abseil-cpp/CONTRIBUTING.md
+++ /dev/null
@@ -1,141 +0,0 @@
-# How to Contribute to Abseil
-
-We'd love to accept your patches and contributions to this project. There are
-just a few small guidelines you need to follow.
-
-NOTE: If you are new to GitHub, please start by reading [Pull Request
-howto](https://help.github.com/articles/about-pull-requests/)
-
-## Contributor License Agreement
-
-Contributions to this project must be accompanied by a Contributor License
-Agreement. You (or your employer) retain the copyright to your contribution,
-this simply gives us permission to use and redistribute your contributions as
-part of the project. Head over to <https://cla.developers.google.com/> to see
-your current agreements on file or to sign a new one.
-
-You generally only need to submit a CLA once, so if you've already submitted one
-(even if it was for a different project), you probably don't need to do it
-again.
-
-## Contribution Guidelines
-
-Potential contributors sometimes ask us if the Abseil project is the appropriate
-home for their utility library code or for specific functions implementing
-missing portions of the standard. Often, the answer to this question is "no".
-We’d like to articulate our thinking on this issue so that our choices can be
-understood by everyone and so that contributors can have a better intuition
-about whether Abseil might be interested in adopting a new library.
-
-### Priorities
-
-Although our mission is to augment the C++ standard library, our goal is not to
-provide a full forward-compatible implementation of the latest standard. For us
-to consider a library for inclusion in Abseil, it is not enough that a library
-is useful. We generally choose to release a library when it meets at least one
-of the following criteria:
-
-* **Widespread usage** - Using our internal codebase to help gauge usage, most
- of the libraries we've released have tens of thousands of users.
-* **Anticipated widespread usage** - Pre-adoption of some standard-compliant
- APIs may not have broad adoption initially but can be expected to pick up
- usage when it replaces legacy APIs. `absl::from_chars`, for example,
- replaces existing code that converts strings to numbers and will therefore
- likely see usage growth.
-* **High impact** - APIs that provide a key solution to a specific problem,
- such as `absl::FixedArray`, have higher impact than usage numbers may signal
- and are released because of their importance.
-* **Direct support for a library that falls under one of the above** - When we
- want access to a smaller library as an implementation detail for a
- higher-priority library we plan to release, we may release it, as we did
- with portions of `absl/meta/type_traits.h`. One consequence of this is that
- the presence of a library in Abseil does not necessarily mean that other
- similar libraries would be a high priority.
-
-### API Freeze Consequences
-
-Via the
-[Abseil Compatibility Guidelines](https://abseil.io/about/compatibility), we
-have promised a large degree of API stability. In particular, we will not make
-backward-incompatible changes to released APIs without also shipping a tool or
-process that can upgrade our users' code. We are not yet at the point of easily
-releasing such tools. Therefore, at this time, shipping a library establishes an
-API contract which is borderline unchangeable. (We can add new functionality,
-but we cannot easily change existing behavior.) This constraint forces us to
-very carefully review all APIs that we ship.
-
-
-## Coding Style
-
-To keep the source consistent, readable, diffable and easy to merge, we use a
-fairly rigid coding style, as defined by the
-[google-styleguide](https://github.com/google/styleguide) project. All patches
-will be expected to conform to the style outlined
-[here](https://google.github.io/styleguide/cppguide.html).
-
-## Guidelines for Pull Requests
-
-* If you are a Googler, it is preferable to first create an internal CL and
- have it reviewed and submitted. The code propagation process will deliver
- the change to GitHub.
-
-* Create **small PRs** that are narrowly focused on **addressing a single
- concern**. We often receive PRs that are trying to fix several things at a
- time, but if only one fix is considered acceptable, nothing gets merged and
- both author's & review's time is wasted. Create more PRs to address
- different concerns and everyone will be happy.
-
-* For speculative changes, consider opening an [Abseil
- issue](https://github.com/abseil/abseil-cpp/issues) and discussing it first.
- If you are suggesting a behavioral or API change, consider starting with an
- [Abseil proposal template](ABSEIL_ISSUE_TEMPLATE.md).
-
-* Provide a good **PR description** as a record of **what** change is being
- made and **why** it was made. Link to a GitHub issue if it exists.
-
-* Don't fix code style and formatting unless you are already changing that
- line to address an issue. Formatting of modified lines may be done using
- `git clang-format`. PRs with irrelevant changes won't be merged. If
- you do want to fix formatting or style, do that in a separate PR.
-
-* Unless your PR is trivial, you should expect there will be reviewer comments
- that you'll need to address before merging. We expect you to be reasonably
- responsive to those comments, otherwise the PR will be closed after 2-3
- weeks of inactivity.
-
-* Maintain **clean commit history** and use **meaningful commit messages**.
- PRs with messy commit history are difficult to review and won't be merged.
- Use `rebase -i upstream/master` to curate your commit history and/or to
- bring in latest changes from master (but avoid rebasing in the middle of a
- code review).
-
-* Keep your PR up to date with upstream/master (if there are merge conflicts,
- we can't really merge your change).
-
-* **All tests need to be passing** before your change can be merged. We
- recommend you **run tests locally** (see below)
-
-* Exceptions to the rules can be made if there's a compelling reason for doing
- so. That is - the rules are here to serve us, not the other way around, and
- the rules need to be serving their intended purpose to be valuable.
-
-* All submissions, including submissions by project members, require review.
-
-## Running Tests
-
-If you have [Bazel](https://bazel.build/) installed, use `bazel test
---test_tag_filters="-benchmark" ...` to run the unit tests.
-
-If you are running the Linux operating system and have
-[Docker](https://www.docker.com/) installed, you can also run the `linux_*.sh`
-scripts under the `ci/`(https://github.com/abseil/abseil-cpp/tree/master/ci)
-directory to test Abseil under a variety of conditions.
-
-## Abseil Committers
-
-The current members of the Abseil engineering team are the only committers at
-present.
-
-## Release Process
-
-Abseil lives at head, where latest-and-greatest code can be found.
diff --git a/third_party/abseil-cpp/DIR_METADATA b/third_party/abseil-cpp/DIR_METADATA
deleted file mode 100644
index 2aaf8e2..0000000
--- a/third_party/abseil-cpp/DIR_METADATA
+++ /dev/null
@@ -1,3 +0,0 @@
-monorail {
- component: "Internals>Core"
-}
diff --git a/third_party/abseil-cpp/FAQ.md b/third_party/abseil-cpp/FAQ.md
deleted file mode 100644
index fbd92ce..0000000
--- a/third_party/abseil-cpp/FAQ.md
+++ /dev/null
@@ -1,167 +0,0 @@
-# Abseil FAQ
-
-## Is Abseil the right home for my utility library?
-
-Most often the answer to the question is "no." As both the [About
-Abseil](https://abseil.io/about/) page and our [contributing
-guidelines](https://github.com/abseil/abseil-cpp/blob/master/CONTRIBUTING.md#contribution-guidelines)
-explain, Abseil contains a variety of core C++ library code that is widely used
-at [Google](https://www.google.com/). As such, Abseil's primary purpose is to be
-used as a dependency by Google's open source C++ projects. While we do hope that
-Abseil is also useful to the C++ community at large, this added constraint also
-means that we are unlikely to accept a contribution of utility code that isn't
-already widely used by Google.
-
-## How to I set the C++ dialect used to build Abseil?
-
-The short answer is that whatever mechanism you choose, you need to make sure
-that you set this option consistently at the global level for your entire
-project. If, for example, you want to set the C++ dialect to C++17, with
-[Bazel](https://bazel/build/) as the build system and `gcc` or `clang` as the
-compiler, there several ways to do this:
-* Pass `--cxxopt=-std=c++17` on the command line (for example, `bazel build
- --cxxopt=-std=c++17 ...`)
-* Set the environment variable `BAZEL_CXXOPTS` (for example,
- `BAZEL_CXXOPTS=-std=c++17`)
-* Add `build --cxxopt=-std=c++17` to your [`.bazelrc`
- file](https://docs.bazel.build/versions/master/guide.html#bazelrc)
-
-If you are using CMake as the build system, you'll need to add a line like
-`set(CMAKE_CXX_STANDARD 17)` to your top level `CMakeLists.txt` file. If you
-are developing a library designed to be used by other clients, you should
-instead leave `CMAKE_CXX_STANDARD` unset and configure the minimum C++ standard
-required by each of your library targets via `target_compile_features`. See the
-[CMake build
-instructions](https://github.com/abseil/abseil-cpp/blob/master/CMake/README.md)
-for more information.
-
-For a longer answer to this question and to understand why some other approaches
-don't work, see the answer to ["What is ABI and why don't you recommend using a
-pre-compiled version of
-Abseil?"](#what-is-abi-and-why-dont-you-recommend-using-a-pre-compiled-version-of-abseil)
-
-## What is ABI and why don't you recommend using a pre-compiled version of Abseil?
-
-For the purposes of this discussion, you can think of
-[ABI](https://en.wikipedia.org/wiki/Application_binary_interface) as the
-compiled representation of the interfaces in code. This is in contrast to
-[API](https://en.wikipedia.org/wiki/Application_programming_interface), which
-you can think of as the interfaces as defined by the code itself. [Abseil has a
-strong promise of API compatibility, but does not make any promise of ABI
-compatibility](https://abseil.io/about/compatibility). Let's take a look at what
-this means in practice.
-
-You might be tempted to do something like this in a
-[Bazel](https://bazel.build/) `BUILD` file:
-
-```
-# DON'T DO THIS!!!
-cc_library(
- name = "my_library",
- srcs = ["my_library.cc"],
- copts = ["-std=c++17"], # May create a mixed-mode compile!
- deps = ["@com_google_absl//absl/strings"],
-)
-```
-
-Applying `-std=c++17` to an individual target in your `BUILD` file is going to
-compile that specific target in C++17 mode, but it isn't going to ensure the
-Abseil library is built in C++17 mode, since the Abseil library itself is a
-different build target. If your code includes an Abseil header, then your
-program may contain conflicting definitions of the same
-class/function/variable/enum, etc. As a rule, all compile options that affect
-the ABI of a program need to be applied to the entire build on a global basis.
-
-C++ has something called the [One Definition
-Rule](https://en.wikipedia.org/wiki/One_Definition_Rule) (ODR). C++ doesn't
-allow multiple definitions of the same class/function/variable/enum, etc. ODR
-violations sometimes result in linker errors, but linkers do not always catch
-violations. Uncaught ODR violations can result in strange runtime behaviors or
-crashes that can be hard to debug.
-
-If you build the Abseil library and your code using different compile options
-that affect ABI, there is a good chance you will run afoul of the One Definition
-Rule. Examples of GCC compile options that affect ABI include (but aren't
-limited to) language dialect (e.g. `-std=`), optimization level (e.g. `-O2`),
-code generation flags (e.g. `-fexceptions`), and preprocessor defines
-(e.g. `-DNDEBUG`).
-
-If you use a pre-compiled version of Abseil, (for example, from your Linux
-distribution package manager or from something like
-[vcpkg](https://github.com/microsoft/vcpkg)) you have to be very careful to
-ensure ABI compatibility across the components of your program. The only way you
-can be sure your program is going to be correct regarding ABI is to ensure
-you've used the exact same compile options as were used to build the
-pre-compiled library. This does not mean that Abseil cannot work as part of a
-Linux distribution since a knowledgeable binary packager will have ensured that
-all packages have been built with consistent compile options. This is one of the
-reasons we warn against - though do not outright reject - using Abseil as a
-pre-compiled library.
-
-Another possible way that you might afoul of ABI issues is if you accidentally
-include two versions of Abseil in your program. Multiple versions of Abseil can
-end up within the same binary if your program uses the Abseil library and
-another library also transitively depends on Abseil (resulting in what is
-sometimes called the diamond dependency problem). In cases such as this you must
-structure your build so that all libraries use the same version of Abseil.
-[Abseil's strong promise of API compatibility between
-releases](https://abseil.io/about/compatibility) means the latest "HEAD" release
-of Abseil is almost certainly the right choice if you are doing as we recommend
-and building all of your code from source.
-
-For these reasons we recommend you avoid pre-compiled code and build the Abseil
-library yourself in a consistent manner with the rest of your code.
-
-## What is "live at head" and how do I do it?
-
-From Abseil's point-of-view, "live at head" means that every Abseil source
-release (which happens on an almost daily basis) is either API compatible with
-the previous release, or comes with an automated tool that you can run over code
-to make it compatible. In practice, the need to use an automated tool is
-extremely rare. This means that upgrading from one source release to another
-should be a routine practice that can and should be performed often.
-
-We recommend you update to the [latest commit in the `master` branch of
-Abseil](https://github.com/abseil/abseil-cpp/commits/master) as often as
-possible. Not only will you pick up bug fixes more quickly, but if you have good
-automated testing, you will catch and be able to fix any [Hyrum's
-Law](https://www.hyrumslaw.com/) dependency problems on an incremental basis
-instead of being overwhelmed by them and having difficulty isolating them if you
-wait longer between updates.
-
-If you are using the [Bazel](https://bazel.build/) build system and its
-[external dependencies](https://docs.bazel.build/versions/master/external.html)
-feature, updating the
-[`http_archive`](https://docs.bazel.build/versions/master/repo/http.html#http_archive)
-rule in your
-[`WORKSPACE`](https://docs.bazel.build/versions/master/be/workspace.html) for
-`com_google_abseil` to point to the [latest commit in the `master` branch of
-Abseil](https://github.com/abseil/abseil-cpp/commits/master) is all you need to
-do. For example, on February 11, 2020, the latest commit to the master branch
-was `98eb410c93ad059f9bba1bf43f5bb916fc92a5ea`. To update to this commit, you
-would add the following snippet to your `WORKSPACE` file:
-
-```
-http_archive(
- name = "com_google_absl",
- urls = ["https://github.com/abseil/abseil-cpp/archive/98eb410c93ad059f9bba1bf43f5bb916fc92a5ea.zip"], # 2020-02-11T18:50:53Z
- strip_prefix = "abseil-cpp-98eb410c93ad059f9bba1bf43f5bb916fc92a5ea",
- sha256 = "aabf6c57e3834f8dc3873a927f37eaf69975d4b28117fc7427dfb1c661542a87",
-)
-```
-
-To get the `sha256` of this URL, run `curl -sL --output -
-https://github.com/abseil/abseil-cpp/archive/98eb410c93ad059f9bba1bf43f5bb916fc92a5ea.zip
-| sha256sum -`.
-
-You can commit the updated `WORKSPACE` file to your source control every time
-you update, and if you have good automated testing, you might even consider
-automating this.
-
-One thing we don't recommend is using GitHub's `master.zip` files (for example
-[https://github.com/abseil/abseil-cpp/archive/master.zip](https://github.com/abseil/abseil-cpp/archive/master.zip)),
-which are always the latest commit in the `master` branch, to implement live at
-head. Since these `master.zip` URLs are not versioned, you will lose build
-reproducibility. In addition, some build systems, including Bazel, will simply
-cache this file, which means you won't actually be updating to the latest
-release until your cache is cleared or invalidated.
diff --git a/third_party/abseil-cpp/LICENSE b/third_party/abseil-cpp/LICENSE
deleted file mode 100644
index ccd61dc..0000000
--- a/third_party/abseil-cpp/LICENSE
+++ /dev/null
@@ -1,203 +0,0 @@
-
- Apache License
- Version 2.0, January 2004
- https://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "[]"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright [yyyy] [name of copyright owner]
-
- 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.
-
diff --git a/third_party/abseil-cpp/OWNERS.webrtc b/third_party/abseil-cpp/OWNERS.webrtc
deleted file mode 100644
index 2827b09..0000000
--- a/third_party/abseil-cpp/OWNERS.webrtc
+++ /dev/null
@@ -1,2 +0,0 @@
-danilchap@chromium.org
-mbonadei@chromium.org
diff --git a/third_party/abseil-cpp/README.chromium b/third_party/abseil-cpp/README.chromium
deleted file mode 100644
index 4f5341b..0000000
--- a/third_party/abseil-cpp/README.chromium
+++ /dev/null
@@ -1,37 +0,0 @@
-Name: Abseil
-Short Name: absl
-URL: https://github.com/abseil/abseil-cpp
-License: Apache 2.0
-License File: LICENSE
-Version: 0
-Revision: 0064d9db90d32d35e9f9d70e2df4ddf8d0ab1257
-Security Critical: yes
-
-Description:
-This directory contains the source code of Abseil for C++. This can be used by
-Chromium, subject to the guidance at
-https://chromium.googlesource.com/chromium/src/+/main/styleguide/c++/c++-features.md;
-it can be used without restriction by Chromium's dependencies, except that
-objects compiled into Chromium itself cannot use anything relying on
-absl::base_internal::FastTypeId (see https://crbug.com/1096380).
-
-How to update Abseil:
-
-1. Download the code from the Abseil git repository (see URL).
-
-2. Copy the content of the Abseil git repo to //third_party/abseil-cpp.
-
-3. From your source root run third_party/abseil-cpp/generate_def_files.py to
- regenerate Windows symbol definition files.
-
-Local Modifications:
-
-* absl/copts.bzl has been translated to //third_party/absl-cpp/BUILD.gn. Both
- files contain lists of compiler flags in order to reduce duplication.
-
-* All the BUILD.bazel files have been translated to BUILD.gn files.
-
-* Patches from //third_party/abseil-cpp/patches have been applied.
-
-* Increment this number to silence presubmits about modifying files in
- third_party when regenerating absl .def files: 2
diff --git a/third_party/abseil-cpp/README.md b/third_party/abseil-cpp/README.md
deleted file mode 100644
index 36e9b7c..0000000
--- a/third_party/abseil-cpp/README.md
+++ /dev/null
@@ -1,161 +0,0 @@
-# Abseil - C++ Common Libraries
-
-The repository contains the Abseil C++ library code. Abseil is an open-source
-collection of C++ code (compliant to C++14) designed to augment the C++
-standard library.
-
-## Table of Contents
-
-- [About Abseil](#about)
-- [Quickstart](#quickstart)
-- [Building Abseil](#build)
-- [Support](#support)
-- [Codemap](#codemap)
-- [Releases](#releases)
-- [License](#license)
-- [Links](#links)
-
-<a name="about"></a>
-## About Abseil
-
-Abseil is an open-source collection of C++ library code designed to augment
-the C++ standard library. The Abseil library code is collected from Google's
-own C++ code base, has been extensively tested and used in production, and
-is the same code we depend on in our daily coding lives.
-
-In some cases, Abseil provides pieces missing from the C++ standard; in
-others, Abseil provides alternatives to the standard for special needs
-we've found through usage in the Google code base. We denote those cases
-clearly within the library code we provide you.
-
-Abseil is not meant to be a competitor to the standard library; we've
-just found that many of these utilities serve a purpose within our code
-base, and we now want to provide those resources to the C++ community as
-a whole.
-
-<a name="quickstart"></a>
-## Quickstart
-
-If you want to just get started, make sure you at least run through the
-[Abseil Quickstart](https://abseil.io/docs/cpp/quickstart). The Quickstart
-contains information about setting up your development environment, downloading
-the Abseil code, running tests, and getting a simple binary working.
-
-<a name="build"></a>
-## Building Abseil
-
-[Bazel](https://bazel.build) and [CMake](https://cmake.org/) are the official
-build systems for Abseil.
-See the [quickstart](https://abseil.io/docs/cpp/quickstart) for more information
-on building Abseil using the Bazel build system.
-If you require CMake support, please check the [CMake build
-instructions](CMake/README.md) and [CMake
-Quickstart](https://abseil.io/docs/cpp/quickstart-cmake).
-
-<a name="support"></a>
-## Support
-
-Abseil follows Google's [Foundational C++ Support
-Policy](https://opensource.google/documentation/policies/cplusplus-support). See
-[this
-table](https://github.com/google/oss-policies-info/blob/main/foundational-cxx-support-matrix.md)
-for a list of currently supported versions compilers, platforms, and build
-tools.
-
-<a name="codemap"></a>
-## Codemap
-
-Abseil contains the following C++ library components:
-
-* [`base`](absl/base/)
- <br /> The `base` library contains initialization code and other code which
- all other Abseil code depends on. Code within `base` may not depend on any
- other code (other than the C++ standard library).
-* [`algorithm`](absl/algorithm/)
- <br /> The `algorithm` library contains additions to the C++ `<algorithm>`
- library and container-based versions of such algorithms.
-* [`cleanup`](absl/cleanup/)
- <br /> The `cleanup` library contains the control-flow-construct-like type
- `absl::Cleanup` which is used for executing a callback on scope exit.
-* [`container`](absl/container/)
- <br /> The `container` library contains additional STL-style containers,
- including Abseil's unordered "Swiss table" containers.
-* [`debugging`](absl/debugging/)
- <br /> The `debugging` library contains code useful for enabling leak
- checks, and stacktrace and symbolization utilities.
-* [`flags`](absl/flags/)
- <br /> The `flags` library contains code for handling command line flags for
- libraries and binaries built with Abseil.
-* [`hash`](absl/hash/)
- <br /> The `hash` library contains the hashing framework and default hash
- functor implementations for hashable types in Abseil.
-* [`iterator`](absl/iterator/)
- <br /> The `iterator` library contains utilities for augmenting ranges in
- range-based for loops.
-* [`log`](absl/log/)
- <br /> The `log` library contains `LOG` and `CHECK` macros and facilities
- for writing logged messages out to disk, `stderr`, or user-extensible
- destinations.
-* [`memory`](absl/memory/)
- <br /> The `memory` library contains memory management facilities that augment
- C++'s `<memory>` library.
-* [`meta`](absl/meta/)
- <br /> The `meta` library contains compatible versions of type checks
- available within C++14 and C++17 versions of the C++ `<type_traits>` library.
-* [`numeric`](absl/numeric/)
- <br /> The `numeric` library contains 128-bit integer types as well as
- implementations of C++20's bitwise math functions.
-* [`profiling`](absl/profiling/)
- <br /> The `profiling` library contains utility code for profiling C++
- entities. It is currently a private dependency of other Abseil libraries.
-* [`random`](absl/random/)
- <br /> The `random` library contains functions for generating psuedorandom
- values.
-* [`status`](absl/status/)
- <br /> The `status` library contains abstractions for error handling,
- specifically `absl::Status` and `absl::StatusOr<T>`.
-* [`strings`](absl/strings/)
- <br /> The `strings` library contains a variety of strings routines and
- utilities, including a C++14-compatible version of the C++17
- `std::string_view` type.
-* [`synchronization`](absl/synchronization/)
- <br /> The `synchronization` library contains concurrency primitives (Abseil's
- `absl::Mutex` class, an alternative to `std::mutex`) and a variety of
- synchronization abstractions.
-* [`time`](absl/time/)
- <br /> The `time` library contains abstractions for computing with absolute
- points in time, durations of time, and formatting and parsing time within
- time zones.
-* [`types`](absl/types/)
- <br /> The `types` library contains non-container utility types, like a
- C++14-compatible version of the C++17 `std::optional` type.
-* [`utility`](absl/utility/)
- <br /> The `utility` library contains utility and helper code.
-
-<a name="releases"></a>
-## Releases
-
-Abseil recommends users "live-at-head" (update to the latest commit from the
-master branch as often as possible). However, we realize this philosophy doesn't
-work for every project, so we also provide [Long Term Support
-Releases](https://github.com/abseil/abseil-cpp/releases) to which we backport
-fixes for severe bugs. See our [release
-management](https://abseil.io/about/releases) document for more details.
-
-<a name="license"></a>
-## License
-
-The Abseil C++ library is licensed under the terms of the Apache
-license. See [LICENSE](LICENSE) for more information.
-
-<a name="links"></a>
-## Links
-
-For more information about Abseil:
-
-* Consult our [Abseil Introduction](https://abseil.io/about/intro)
-* Read [Why Adopt Abseil](https://abseil.io/about/philosophy) to understand our
- design philosophy.
-* Peruse our
- [Abseil Compatibility Guarantees](https://abseil.io/about/compatibility) to
- understand both what we promise to you, and what we expect of you in return.
diff --git a/third_party/abseil-cpp/UPGRADES.md b/third_party/abseil-cpp/UPGRADES.md
deleted file mode 100644
index 35599d0..0000000
--- a/third_party/abseil-cpp/UPGRADES.md
+++ /dev/null
@@ -1,17 +0,0 @@
-# C++ Upgrade Tools
-
-Abseil may occassionally release API-breaking changes. As noted in our
-[Compatibility Guidelines][compatibility-guide], we will aim to provide a tool
-to do the work of effecting such API-breaking changes, when absolutely
-necessary.
-
-These tools will be listed on the [C++ Upgrade Tools][upgrade-tools] guide on
-https://abseil.io.
-
-For more information, the [C++ Automated Upgrade Guide][api-upgrades-guide]
-outlines this process.
-
-[compatibility-guide]: https://abseil.io/about/compatibility
-[api-upgrades-guide]: https://abseil.io/docs/cpp/tools/api-upgrades
-[upgrade-tools]: https://abseil.io/docs/cpp/tools/upgrades/
-
diff --git a/third_party/abseil-cpp/WORKSPACE b/third_party/abseil-cpp/WORKSPACE
deleted file mode 100644
index 072fa93..0000000
--- a/third_party/abseil-cpp/WORKSPACE
+++ /dev/null
@@ -1,61 +0,0 @@
-#
-# Copyright 2019 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.
-#
-
-workspace(name = "com_google_absl")
-
-load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
-
-# GoogleTest/GoogleMock framework. Used by most unit-tests.
-http_archive(
- name = "com_google_googletest", # 2022-06-16T20:18:32Z
- sha256 = "a1d3123179024258f9c399d45da3e0b09c4aaf8d2c041466ce5b4793a8929f23",
- strip_prefix = "googletest-86add13493e5c881d7e4ba77fb91c1f57752b3a4",
- # Keep this URL in sync with ABSL_GOOGLETEST_COMMIT in ci/cmake_common.sh.
- urls = ["https://github.com/google/googletest/archive/86add13493e5c881d7e4ba77fb91c1f57752b3a4.zip"],
-)
-
-# RE2 (the regular expression library used by GoogleTest)
-# Note this must use a commit from the `abseil` branch of the RE2 project.
-# https://github.com/google/re2/tree/abseil
-http_archive(
- name = "com_googlesource_code_re2",
- sha256 = "0a890c2aa0bb05b2ce906a15efb520d0f5ad4c7d37b8db959c43772802991887",
- strip_prefix = "re2-a427f10b9fb4622dd6d8643032600aa1b50fbd12",
- urls = ["https://github.com/google/re2/archive/a427f10b9fb4622dd6d8643032600aa1b50fbd12.zip"], # 2022-06-09
-)
-
-# Google benchmark.
-http_archive(
- name = "com_github_google_benchmark", # 2021-09-20T09:19:51Z
- sha256 = "62e2f2e6d8a744d67e4bbc212fcfd06647080de4253c97ad5c6749e09faf2cb0",
- strip_prefix = "benchmark-0baacde3618ca617da95375e0af13ce1baadea47",
- urls = ["https://github.com/google/benchmark/archive/0baacde3618ca617da95375e0af13ce1baadea47.zip"],
-)
-
-# Bazel Skylib.
-http_archive(
- name = "bazel_skylib",
- urls = ["https://github.com/bazelbuild/bazel-skylib/releases/download/1.2.1/bazel-skylib-1.2.1.tar.gz"],
- sha256 = "f7be3474d42aae265405a592bb7da8e171919d74c16f082a5457840f06054728",
-)
-
-# Bazel platform rules.
-http_archive(
- name = "platforms",
- sha256 = "a879ea428c6d56ab0ec18224f976515948822451473a80d06c2e50af0bbe5121",
- strip_prefix = "platforms-da5541f26b7de1dc8e04c075c99df5351742a4a2",
- urls = ["https://github.com/bazelbuild/platforms/archive/da5541f26b7de1dc8e04c075c99df5351742a4a2.zip"], # 2022-05-27
-)
diff --git a/third_party/abseil-cpp/absl.gni b/third_party/abseil-cpp/absl.gni
deleted file mode 100644
index 4c6cd37..0000000
--- a/third_party/abseil-cpp/absl.gni
+++ /dev/null
@@ -1,107 +0,0 @@
-# Copyright 2020 The Chromium Authors
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# This file contains the definition of the template absl_source_set which
-# should be the only type of target needed in abseil's BUILD.gn files.
-# This template will correctly set "configs" and "public_configs" in order
-# to correctly compile abseil in Chromium.
-#
-# Usage:
-# Most of the times its usage will be similar to the example below but all
-# the arguments avilable in source_set are also available for absl_source_set.
-#
-# absl_source_set("foo") {
-# sources = [ "foo.cc" ]
-# public = [ "foo.h" ]
-# deps = [ ":bar" ]
-# }
-
-import("//build_overrides/build.gni")
-
-template("absl_source_set") {
- source_set(target_name) {
- forward_variables_from(invoker, "*")
- configs -= [ "//build/config/compiler:chromium_code" ]
- configs += [
- "//build/config/compiler:no_chromium_code",
- "//build/config/compiler:prevent_unsafe_narrowing",
- "//third_party/abseil-cpp:absl_default_cflags_cc",
- "//third_party/abseil-cpp:absl_define_config",
- ]
-
- if (is_component_build) {
- defines = [ "ABSL_BUILD_DLL" ]
- if (!is_win) {
- configs -= [ "//build/config/gcc:symbol_visibility_hidden" ]
- configs += [ "//build/config/gcc:symbol_visibility_default" ]
- }
- }
-
- if (!defined(public_configs)) {
- public_configs = []
- }
- public_configs += [ "//third_party/abseil-cpp:absl_include_config" ]
-
- if (!defined(visibility)) {
- # Within Chromium builds, restrict direct visibility of Abseil sources, so
- # users must depend on //third_party/abseil-cpp:absl. This prevents use of
- # banned targets like absl/types:any. A few targets require exceptions.
- # TODO(crbug.com/1096380): Consider replacing build_with_chromium with
- # is_component_build for a narrower, more accurate condition.
- if (build_with_chromium) {
- visibility = [
- # Abseil itself.
- "//third_party/abseil-cpp/*",
-
- # GTest. It unconditionally #includes any.h if pretty-print support
- # for absl types is enabled.
- "//third_party/googletest/*",
-
- # WebRTC binary to run PSNR and SSIM video quality analysis. It
- # statically links absl and it is used by "browser_tests" when
- # is_component_build=false but it cannot depend on the absl
- # component because it uses absl/flags.
- "//third_party/webrtc/rtc_tools:frame_analyzer",
-
- # WebRTC binaries used by //:chromium_builder_asan. They both
- # statically link absl (because they depend on absl/flags) and are
- # used by Chromium only when is_component_build=false.
- "//third_party/webrtc/rtc_tools:rtp_generator",
- "//third_party/webrtc/rtc_tools:video_replay",
-
- # Not used by Chromium directly.
- "//chromecast/internal/*",
- "//libassistant/*",
- ]
- } else {
- visibility = [ "*" ]
- }
- }
- }
-}
-
-template("absl_test") {
- source_set(target_name) {
- forward_variables_from(invoker, "*")
- testonly = true
- configs -= [ "//build/config/compiler:chromium_code" ]
- configs += [
- "//build/config/compiler:no_chromium_code",
- "//third_party/abseil-cpp:absl_default_cflags_cc",
- "//third_party/abseil-cpp:absl_define_config",
- "//third_party/abseil-cpp:absl_test_config",
- ]
-
- if (!defined(public_configs)) {
- public_configs = []
- }
- public_configs += [ "//third_party/abseil-cpp:absl_include_config" ]
-
- visibility = [ "//third_party/abseil-cpp/:*" ]
- deps += [
- "//third_party/googletest:gmock",
- "//third_party/googletest:gtest",
- ]
- }
-}
diff --git a/third_party/abseil-cpp/absl/BUILD.bazel b/third_party/abseil-cpp/absl/BUILD.bazel
deleted file mode 100644
index 29963cc..0000000
--- a/third_party/abseil-cpp/absl/BUILD.bazel
+++ /dev/null
@@ -1,125 +0,0 @@
-#
-# Copyright 2017 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.
-
-load("@bazel_skylib//lib:selects.bzl", "selects")
-
-package(default_visibility = ["//visibility:public"])
-
-licenses(["notice"])
-
-config_setting(
- name = "clang_compiler",
- flag_values = {
- "@bazel_tools//tools/cpp:compiler": "clang",
- },
- visibility = [":__subpackages__"],
-)
-
-config_setting(
- name = "gcc_compiler",
- flag_values = {
- "@bazel_tools//tools/cpp:compiler": "gcc",
- },
- visibility = [":__subpackages__"],
-)
-
-config_setting(
- name = "msvc_compiler",
- flag_values = {
- "@bazel_tools//tools/cpp:compiler": "msvc-cl",
- },
- visibility = [":__subpackages__"],
-)
-
-config_setting(
- name = "clang-cl_compiler",
- flag_values = {
- "@bazel_tools//tools/cpp:compiler": "clang-cl",
- },
- visibility = [":__subpackages__"],
-)
-
-config_setting(
- name = "osx",
- constraint_values = [
- "@platforms//os:osx",
- ],
-)
-
-config_setting(
- name = "ios",
- constraint_values = [
- "@platforms//os:ios",
- ],
-)
-
-config_setting(
- name = "ppc",
- values = {
- "cpu": "ppc",
- },
- visibility = [":__subpackages__"],
-)
-
-config_setting(
- name = "cpu_wasm",
- values = {
- "cpu": "wasm",
- },
- visibility = [":__subpackages__"],
-)
-
-config_setting(
- name = "cpu_wasm32",
- values = {
- "cpu": "wasm32",
- },
- visibility = [":__subpackages__"],
-)
-
-config_setting(
- name = "platforms_wasm32",
- constraint_values = [
- "@platforms//cpu:wasm32",
- ],
- visibility = [":__subpackages__"],
-)
-
-config_setting(
- name = "platforms_wasm64",
- constraint_values = [
- "@platforms//cpu:wasm64",
- ],
- visibility = [":__subpackages__"],
-)
-
-selects.config_setting_group(
- name = "wasm",
- match_any = [
- ":cpu_wasm",
- ":cpu_wasm32",
- ":platforms_wasm32",
- ":platforms_wasm64",
- ],
- visibility = [":__subpackages__"],
-)
-
-config_setting(
- name = "fuchsia",
- values = {
- "cpu": "fuchsia",
- },
- visibility = [":__subpackages__"],
-)
diff --git a/third_party/abseil-cpp/absl/CMakeLists.txt b/third_party/abseil-cpp/absl/CMakeLists.txt
deleted file mode 100644
index 925be19..0000000
--- a/third_party/abseil-cpp/absl/CMakeLists.txt
+++ /dev/null
@@ -1,40 +0,0 @@
-#
-# Copyright 2017 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.
-#
-
-add_subdirectory(base)
-add_subdirectory(algorithm)
-add_subdirectory(cleanup)
-add_subdirectory(container)
-add_subdirectory(debugging)
-add_subdirectory(flags)
-add_subdirectory(functional)
-add_subdirectory(hash)
-add_subdirectory(log)
-add_subdirectory(memory)
-add_subdirectory(meta)
-add_subdirectory(numeric)
-add_subdirectory(profiling)
-add_subdirectory(random)
-add_subdirectory(status)
-add_subdirectory(strings)
-add_subdirectory(synchronization)
-add_subdirectory(time)
-add_subdirectory(types)
-add_subdirectory(utility)
-
-if (${ABSL_BUILD_DLL})
- absl_make_dll()
-endif()
diff --git a/third_party/abseil-cpp/absl/abseil.podspec.gen.py b/third_party/abseil-cpp/absl/abseil.podspec.gen.py
deleted file mode 100755
index 6375298..0000000
--- a/third_party/abseil-cpp/absl/abseil.podspec.gen.py
+++ /dev/null
@@ -1,229 +0,0 @@
-#!/usr/bin/env python3
-# -*- coding: utf-8 -*-
-"""This script generates abseil.podspec from all BUILD.bazel files.
-
-This is expected to run on abseil git repository with Bazel 1.0 on Linux.
-It recursively analyzes BUILD.bazel files using query command of Bazel to
-dump its build rules in XML format. From these rules, it constructs podspec
-structure.
-"""
-
-import argparse
-import collections
-import os
-import re
-import subprocess
-import xml.etree.ElementTree
-
-# Template of root podspec.
-SPEC_TEMPLATE = """
-# This file has been automatically generated from a script.
-# Please make modifications to `abseil.podspec.gen.py` instead.
-Pod::Spec.new do |s|
- s.name = 'abseil'
- s.version = '${version}'
- s.summary = 'Abseil Common Libraries (C++) from Google'
- s.homepage = 'https://abseil.io'
- s.license = 'Apache License, Version 2.0'
- s.authors = { 'Abseil Team' => 'abseil-io@googlegroups.com' }
- s.source = {
- :git => 'https://github.com/abseil/abseil-cpp.git',
- :tag => '${tag}',
- }
- s.module_name = 'absl'
- s.header_mappings_dir = 'absl'
- s.header_dir = 'absl'
- s.libraries = 'c++'
- s.compiler_flags = '-Wno-everything'
- s.pod_target_xcconfig = {
- 'USER_HEADER_SEARCH_PATHS' => '$(inherited) "$(PODS_TARGET_SRCROOT)"',
- 'USE_HEADERMAP' => 'NO',
- 'ALWAYS_SEARCH_USER_PATHS' => 'NO',
- }
- s.ios.deployment_target = '9.0'
- s.osx.deployment_target = '10.10'
- s.tvos.deployment_target = '9.0'
- s.watchos.deployment_target = '2.0'
-"""
-
-# Rule object representing the rule of Bazel BUILD.
-Rule = collections.namedtuple(
- "Rule", "type name package srcs hdrs textual_hdrs deps visibility testonly")
-
-
-def get_elem_value(elem, name):
- """Returns the value of XML element with the given name."""
- for child in elem:
- if child.attrib.get("name") != name:
- continue
- if child.tag == "string":
- return child.attrib.get("value")
- if child.tag == "boolean":
- return child.attrib.get("value") == "true"
- if child.tag == "list":
- return [nested_child.attrib.get("value") for nested_child in child]
- raise "Cannot recognize tag: " + child.tag
- return None
-
-
-def normalize_paths(paths):
- """Returns the list of normalized path."""
- # e.g. ["//absl/strings:dir/header.h"] -> ["absl/strings/dir/header.h"]
- return [path.lstrip("/").replace(":", "/") for path in paths]
-
-
-def parse_rule(elem, package):
- """Returns a rule from bazel XML rule."""
- return Rule(
- type=elem.attrib["class"],
- name=get_elem_value(elem, "name"),
- package=package,
- srcs=normalize_paths(get_elem_value(elem, "srcs") or []),
- hdrs=normalize_paths(get_elem_value(elem, "hdrs") or []),
- textual_hdrs=normalize_paths(get_elem_value(elem, "textual_hdrs") or []),
- deps=get_elem_value(elem, "deps") or [],
- visibility=get_elem_value(elem, "visibility") or [],
- testonly=get_elem_value(elem, "testonly") or False)
-
-
-def read_build(package):
- """Runs bazel query on given package file and returns all cc rules."""
- result = subprocess.check_output(
- ["bazel", "query", package + ":all", "--output", "xml"])
- root = xml.etree.ElementTree.fromstring(result)
- return [
- parse_rule(elem, package)
- for elem in root
- if elem.tag == "rule" and elem.attrib["class"].startswith("cc_")
- ]
-
-
-def collect_rules(root_path):
- """Collects and returns all rules from root path recursively."""
- rules = []
- for cur, _, _ in os.walk(root_path):
- build_path = os.path.join(cur, "BUILD.bazel")
- if os.path.exists(build_path):
- rules.extend(read_build("//" + cur))
- return rules
-
-
-def relevant_rule(rule):
- """Returns true if a given rule is relevant when generating a podspec."""
- return (
- # cc_library only (ignore cc_test, cc_binary)
- rule.type == "cc_library" and
- # ignore empty rule
- (rule.hdrs + rule.textual_hdrs + rule.srcs) and
- # ignore test-only rule
- not rule.testonly)
-
-
-def get_spec_var(depth):
- """Returns the name of variable for spec with given depth."""
- return "s" if depth == 0 else "s{}".format(depth)
-
-
-def get_spec_name(label):
- """Converts the label of bazel rule to the name of podspec."""
- assert label.startswith("//absl/"), "{} doesn't start with //absl/".format(
- label)
- # e.g. //absl/apple/banana -> abseil/apple/banana
- return "abseil/" + label[7:]
-
-
-def write_podspec(f, rules, args):
- """Writes a podspec from given rules and args."""
- rule_dir = build_rule_directory(rules)["abseil"]
- # Write root part with given arguments
- spec = re.sub(r"\$\{(\w+)\}", lambda x: args[x.group(1)],
- SPEC_TEMPLATE).lstrip()
- f.write(spec)
- # Write all target rules
- write_podspec_map(f, rule_dir, 0)
- f.write("end\n")
-
-
-def build_rule_directory(rules):
- """Builds a tree-style rule directory from given rules."""
- rule_dir = {}
- for rule in rules:
- cur = rule_dir
- for frag in get_spec_name(rule.package).split("/"):
- cur = cur.setdefault(frag, {})
- cur[rule.name] = rule
- return rule_dir
-
-
-def write_podspec_map(f, cur_map, depth):
- """Writes podspec from rule map recursively."""
- for key, value in sorted(cur_map.items()):
- indent = " " * (depth + 1)
- f.write("{indent}{var0}.subspec '{key}' do |{var1}|\n".format(
- indent=indent,
- key=key,
- var0=get_spec_var(depth),
- var1=get_spec_var(depth + 1)))
- if isinstance(value, dict):
- write_podspec_map(f, value, depth + 1)
- else:
- write_podspec_rule(f, value, depth + 1)
- f.write("{indent}end\n".format(indent=indent))
-
-
-def write_podspec_rule(f, rule, depth):
- """Writes podspec from given rule."""
- indent = " " * (depth + 1)
- spec_var = get_spec_var(depth)
- # Puts all files in hdrs, textual_hdrs, and srcs into source_files.
- # Since CocoaPods treats header_files a bit differently from bazel,
- # this won't generate a header_files field so that all source_files
- # are considered as header files.
- srcs = sorted(set(rule.hdrs + rule.textual_hdrs + rule.srcs))
- write_indented_list(
- f, "{indent}{var}.source_files = ".format(indent=indent, var=spec_var),
- srcs)
- # Writes dependencies of this rule.
- for dep in sorted(rule.deps):
- name = get_spec_name(dep.replace(":", "/"))
- f.write("{indent}{var}.dependency '{dep}'\n".format(
- indent=indent, var=spec_var, dep=name))
-
-
-def write_indented_list(f, leading, values):
- """Writes leading values in an indented style."""
- f.write(leading)
- f.write((",\n" + " " * len(leading)).join("'{}'".format(v) for v in values))
- f.write("\n")
-
-
-def generate(args):
- """Generates a podspec file from all BUILD files under absl directory."""
- rules = filter(relevant_rule, collect_rules("absl"))
- with open(args.output, "wt") as f:
- write_podspec(f, rules, vars(args))
-
-
-def main():
- parser = argparse.ArgumentParser(
- description="Generates abseil.podspec from BUILD.bazel")
- parser.add_argument(
- "-v", "--version", help="The version of podspec", required=True)
- parser.add_argument(
- "-t",
- "--tag",
- default=None,
- help="The name of git tag (default: version)")
- parser.add_argument(
- "-o",
- "--output",
- default="abseil.podspec",
- help="The name of output file (default: abseil.podspec)")
- args = parser.parse_args()
- if args.tag is None:
- args.tag = args.version
- generate(args)
-
-
-if __name__ == "__main__":
- main()
diff --git a/third_party/abseil-cpp/absl/algorithm/BUILD.bazel b/third_party/abseil-cpp/absl/algorithm/BUILD.bazel
deleted file mode 100644
index 3a9ab01..0000000
--- a/third_party/abseil-cpp/absl/algorithm/BUILD.bazel
+++ /dev/null
@@ -1,92 +0,0 @@
-#
-# Copyright 2017 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.
-#
-
-load(
- "//absl:copts/configure_copts.bzl",
- "ABSL_DEFAULT_COPTS",
- "ABSL_DEFAULT_LINKOPTS",
- "ABSL_TEST_COPTS",
-)
-
-package(default_visibility = ["//visibility:public"])
-
-licenses(["notice"])
-
-cc_library(
- name = "algorithm",
- hdrs = ["algorithm.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- "//absl/base:config",
- ],
-)
-
-cc_test(
- name = "algorithm_test",
- size = "small",
- srcs = ["algorithm_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":algorithm",
- "//absl/base:config",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_binary(
- name = "algorithm_benchmark",
- testonly = 1,
- srcs = ["equal_benchmark.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- tags = ["benchmark"],
- deps = [
- ":algorithm",
- "//absl/base:core_headers",
- "@com_github_google_benchmark//:benchmark_main",
- ],
-)
-
-cc_library(
- name = "container",
- hdrs = [
- "container.h",
- ],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":algorithm",
- "//absl/base:core_headers",
- "//absl/meta:type_traits",
- ],
-)
-
-cc_test(
- name = "container_test",
- srcs = ["container_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":container",
- "//absl/base",
- "//absl/base:core_headers",
- "//absl/memory",
- "//absl/types:span",
- "@com_google_googletest//:gtest_main",
- ],
-)
diff --git a/third_party/abseil-cpp/absl/algorithm/BUILD.gn b/third_party/abseil-cpp/absl/algorithm/BUILD.gn
deleted file mode 100644
index 7e53c03..0000000
--- a/third_party/abseil-cpp/absl/algorithm/BUILD.gn
+++ /dev/null
@@ -1,38 +0,0 @@
-# Copyright 2018 The Chromium Authors
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-import("//third_party/abseil-cpp/absl.gni")
-
-absl_source_set("algorithm") {
- public = [ "algorithm.h" ]
- deps = [ "//third_party/abseil-cpp/absl/base:config" ]
-}
-
-absl_source_set("container") {
- public = [ "container.h" ]
- deps = [
- ":algorithm",
- "//third_party/abseil-cpp/absl/base:core_headers",
- "//third_party/abseil-cpp/absl/meta:type_traits",
- ]
-}
-
-absl_test("algorithm_test") {
- sources = [ "algorithm_test.cc" ]
- deps = [
- ":algorithm",
- "//third_party/abseil-cpp/absl/base:config",
- ]
-}
-
-absl_test("container_test") {
- sources = [ "container_test.cc" ]
- deps = [
- ":container",
- "//third_party/abseil-cpp/absl/base",
- "//third_party/abseil-cpp/absl/base:core_headers",
- "//third_party/abseil-cpp/absl/memory",
- "//third_party/abseil-cpp/absl/types:span",
- ]
-}
diff --git a/third_party/abseil-cpp/absl/algorithm/CMakeLists.txt b/third_party/abseil-cpp/absl/algorithm/CMakeLists.txt
deleted file mode 100644
index 181b49c..0000000
--- a/third_party/abseil-cpp/absl/algorithm/CMakeLists.txt
+++ /dev/null
@@ -1,70 +0,0 @@
-#
-# Copyright 2017 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.
-#
-
-absl_cc_library(
- NAME
- algorithm
- HDRS
- "algorithm.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::config
- PUBLIC
-)
-
-absl_cc_test(
- NAME
- algorithm_test
- SRCS
- "algorithm_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::algorithm
- absl::config
- GTest::gmock_main
-)
-
-absl_cc_library(
- NAME
- algorithm_container
- HDRS
- "container.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::algorithm
- absl::core_headers
- absl::meta
- PUBLIC
-)
-
-absl_cc_test(
- NAME
- container_test
- SRCS
- "container_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::algorithm_container
- absl::base
- absl::core_headers
- absl::memory
- absl::span
- GTest::gmock_main
-)
diff --git a/third_party/abseil-cpp/absl/algorithm/algorithm.h b/third_party/abseil-cpp/absl/algorithm/algorithm.h
deleted file mode 100644
index e9b4733..0000000
--- a/third_party/abseil-cpp/absl/algorithm/algorithm.h
+++ /dev/null
@@ -1,159 +0,0 @@
-// Copyright 2017 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.
-//
-// -----------------------------------------------------------------------------
-// File: algorithm.h
-// -----------------------------------------------------------------------------
-//
-// This header file contains Google extensions to the standard <algorithm> C++
-// header.
-
-#ifndef ABSL_ALGORITHM_ALGORITHM_H_
-#define ABSL_ALGORITHM_ALGORITHM_H_
-
-#include <algorithm>
-#include <iterator>
-#include <type_traits>
-
-#include "absl/base/config.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-
-namespace algorithm_internal {
-
-// Performs comparisons with operator==, similar to C++14's `std::equal_to<>`.
-struct EqualTo {
- template <typename T, typename U>
- bool operator()(const T& a, const U& b) const {
- return a == b;
- }
-};
-
-template <typename InputIter1, typename InputIter2, typename Pred>
-bool EqualImpl(InputIter1 first1, InputIter1 last1, InputIter2 first2,
- InputIter2 last2, Pred pred, std::input_iterator_tag,
- std::input_iterator_tag) {
- while (true) {
- if (first1 == last1) return first2 == last2;
- if (first2 == last2) return false;
- if (!pred(*first1, *first2)) return false;
- ++first1;
- ++first2;
- }
-}
-
-template <typename InputIter1, typename InputIter2, typename Pred>
-bool EqualImpl(InputIter1 first1, InputIter1 last1, InputIter2 first2,
- InputIter2 last2, Pred&& pred, std::random_access_iterator_tag,
- std::random_access_iterator_tag) {
- return (last1 - first1 == last2 - first2) &&
- std::equal(first1, last1, first2, std::forward<Pred>(pred));
-}
-
-// When we are using our own internal predicate that just applies operator==, we
-// forward to the non-predicate form of std::equal. This enables an optimization
-// in libstdc++ that can result in std::memcmp being used for integer types.
-template <typename InputIter1, typename InputIter2>
-bool EqualImpl(InputIter1 first1, InputIter1 last1, InputIter2 first2,
- InputIter2 last2, algorithm_internal::EqualTo /* unused */,
- std::random_access_iterator_tag,
- std::random_access_iterator_tag) {
- return (last1 - first1 == last2 - first2) &&
- std::equal(first1, last1, first2);
-}
-
-template <typename It>
-It RotateImpl(It first, It middle, It last, std::true_type) {
- return std::rotate(first, middle, last);
-}
-
-template <typename It>
-It RotateImpl(It first, It middle, It last, std::false_type) {
- std::rotate(first, middle, last);
- return std::next(first, std::distance(middle, last));
-}
-
-} // namespace algorithm_internal
-
-// equal()
-//
-// Compares the equality of two ranges specified by pairs of iterators, using
-// the given predicate, returning true iff for each corresponding iterator i1
-// and i2 in the first and second range respectively, pred(*i1, *i2) == true
-//
-// This comparison takes at most min(`last1` - `first1`, `last2` - `first2`)
-// invocations of the predicate. Additionally, if InputIter1 and InputIter2 are
-// both random-access iterators, and `last1` - `first1` != `last2` - `first2`,
-// then the predicate is never invoked and the function returns false.
-//
-// This is a C++11-compatible implementation of C++14 `std::equal`. See
-// https://en.cppreference.com/w/cpp/algorithm/equal for more information.
-template <typename InputIter1, typename InputIter2, typename Pred>
-bool equal(InputIter1 first1, InputIter1 last1, InputIter2 first2,
- InputIter2 last2, Pred&& pred) {
- return algorithm_internal::EqualImpl(
- first1, last1, first2, last2, std::forward<Pred>(pred),
- typename std::iterator_traits<InputIter1>::iterator_category{},
- typename std::iterator_traits<InputIter2>::iterator_category{});
-}
-
-// Overload of equal() that performs comparison of two ranges specified by pairs
-// of iterators using operator==.
-template <typename InputIter1, typename InputIter2>
-bool equal(InputIter1 first1, InputIter1 last1, InputIter2 first2,
- InputIter2 last2) {
- return absl::equal(first1, last1, first2, last2,
- algorithm_internal::EqualTo{});
-}
-
-// linear_search()
-//
-// Performs a linear search for `value` using the iterator `first` up to
-// but not including `last`, returning true if [`first`, `last`) contains an
-// element equal to `value`.
-//
-// A linear search is of O(n) complexity which is guaranteed to make at most
-// n = (`last` - `first`) comparisons. A linear search over short containers
-// may be faster than a binary search, even when the container is sorted.
-template <typename InputIterator, typename EqualityComparable>
-bool linear_search(InputIterator first, InputIterator last,
- const EqualityComparable& value) {
- return std::find(first, last, value) != last;
-}
-
-// rotate()
-//
-// Performs a left rotation on a range of elements (`first`, `last`) such that
-// `middle` is now the first element. `rotate()` returns an iterator pointing to
-// the first element before rotation. This function is exactly the same as
-// `std::rotate`, but fixes a bug in gcc
-// <= 4.9 where `std::rotate` returns `void` instead of an iterator.
-//
-// The complexity of this algorithm is the same as that of `std::rotate`, but if
-// `ForwardIterator` is not a random-access iterator, then `absl::rotate`
-// performs an additional pass over the range to construct the return value.
-template <typename ForwardIterator>
-ForwardIterator rotate(ForwardIterator first, ForwardIterator middle,
- ForwardIterator last) {
- return algorithm_internal::RotateImpl(
- first, middle, last,
- std::is_same<decltype(std::rotate(first, middle, last)),
- ForwardIterator>());
-}
-
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_ALGORITHM_ALGORITHM_H_
diff --git a/third_party/abseil-cpp/absl/algorithm/algorithm_test.cc b/third_party/abseil-cpp/absl/algorithm/algorithm_test.cc
deleted file mode 100644
index d18df02..0000000
--- a/third_party/abseil-cpp/absl/algorithm/algorithm_test.cc
+++ /dev/null
@@ -1,191 +0,0 @@
-// Copyright 2017 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/algorithm/algorithm.h"
-
-#include <algorithm>
-#include <list>
-#include <vector>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/base/config.h"
-
-namespace {
-
-TEST(EqualTest, DefaultComparisonRandomAccess) {
- std::vector<int> v1{1, 2, 3};
- std::vector<int> v2 = v1;
- std::vector<int> v3 = {1, 2};
- std::vector<int> v4 = {1, 2, 4};
-
- EXPECT_TRUE(absl::equal(v1.begin(), v1.end(), v2.begin(), v2.end()));
- EXPECT_FALSE(absl::equal(v1.begin(), v1.end(), v3.begin(), v3.end()));
- EXPECT_FALSE(absl::equal(v1.begin(), v1.end(), v4.begin(), v4.end()));
-}
-
-TEST(EqualTest, DefaultComparison) {
- std::list<int> lst1{1, 2, 3};
- std::list<int> lst2 = lst1;
- std::list<int> lst3{1, 2};
- std::list<int> lst4{1, 2, 4};
-
- EXPECT_TRUE(absl::equal(lst1.begin(), lst1.end(), lst2.begin(), lst2.end()));
- EXPECT_FALSE(absl::equal(lst1.begin(), lst1.end(), lst3.begin(), lst3.end()));
- EXPECT_FALSE(absl::equal(lst1.begin(), lst1.end(), lst4.begin(), lst4.end()));
-}
-
-TEST(EqualTest, EmptyRange) {
- std::vector<int> v1{1, 2, 3};
- std::vector<int> empty1;
- std::vector<int> empty2;
-
- // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105705
-#if ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(12, 0)
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wnonnull"
-#endif
- EXPECT_FALSE(absl::equal(v1.begin(), v1.end(), empty1.begin(), empty1.end()));
-#if ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(12, 0)
-#pragma GCC diagnostic pop
-#endif
- EXPECT_FALSE(absl::equal(empty1.begin(), empty1.end(), v1.begin(), v1.end()));
- EXPECT_TRUE(
- absl::equal(empty1.begin(), empty1.end(), empty2.begin(), empty2.end()));
-}
-
-TEST(EqualTest, MixedIterTypes) {
- std::vector<int> v1{1, 2, 3};
- std::list<int> lst1{v1.begin(), v1.end()};
- std::list<int> lst2{1, 2, 4};
- std::list<int> lst3{1, 2};
-
- EXPECT_TRUE(absl::equal(v1.begin(), v1.end(), lst1.begin(), lst1.end()));
- EXPECT_FALSE(absl::equal(v1.begin(), v1.end(), lst2.begin(), lst2.end()));
- EXPECT_FALSE(absl::equal(v1.begin(), v1.end(), lst3.begin(), lst3.end()));
-}
-
-TEST(EqualTest, MixedValueTypes) {
- std::vector<int> v1{1, 2, 3};
- std::vector<char> v2{1, 2, 3};
- std::vector<char> v3{1, 2};
- std::vector<char> v4{1, 2, 4};
-
- EXPECT_TRUE(absl::equal(v1.begin(), v1.end(), v2.begin(), v2.end()));
- EXPECT_FALSE(absl::equal(v1.begin(), v1.end(), v3.begin(), v3.end()));
- EXPECT_FALSE(absl::equal(v1.begin(), v1.end(), v4.begin(), v4.end()));
-}
-
-TEST(EqualTest, WeirdIterators) {
- std::vector<bool> v1{true, false};
- std::vector<bool> v2 = v1;
- std::vector<bool> v3{true};
- std::vector<bool> v4{true, true, true};
-
- EXPECT_TRUE(absl::equal(v1.begin(), v1.end(), v2.begin(), v2.end()));
- EXPECT_FALSE(absl::equal(v1.begin(), v1.end(), v3.begin(), v3.end()));
- EXPECT_FALSE(absl::equal(v1.begin(), v1.end(), v4.begin(), v4.end()));
-}
-
-TEST(EqualTest, CustomComparison) {
- int n[] = {1, 2, 3, 4};
- std::vector<int*> v1{&n[0], &n[1], &n[2]};
- std::vector<int*> v2 = v1;
- std::vector<int*> v3{&n[0], &n[1], &n[3]};
- std::vector<int*> v4{&n[0], &n[1]};
-
- auto eq = [](int* a, int* b) { return *a == *b; };
-
- EXPECT_TRUE(absl::equal(v1.begin(), v1.end(), v2.begin(), v2.end(), eq));
- EXPECT_FALSE(absl::equal(v1.begin(), v1.end(), v3.begin(), v3.end(), eq));
- EXPECT_FALSE(absl::equal(v1.begin(), v1.end(), v4.begin(), v4.end(), eq));
-}
-
-TEST(EqualTest, MoveOnlyPredicate) {
- std::vector<int> v1{1, 2, 3};
- std::vector<int> v2{4, 5, 6};
-
- // move-only equality predicate
- struct Eq {
- Eq() = default;
- Eq(Eq &&) = default;
- Eq(const Eq &) = delete;
- Eq &operator=(const Eq &) = delete;
- bool operator()(const int a, const int b) const { return a == b; }
- };
-
- EXPECT_TRUE(absl::equal(v1.begin(), v1.end(), v1.begin(), v1.end(), Eq()));
- EXPECT_FALSE(absl::equal(v1.begin(), v1.end(), v2.begin(), v2.end(), Eq()));
-}
-
-struct CountingTrivialPred {
- int* count;
- bool operator()(int, int) const {
- ++*count;
- return true;
- }
-};
-
-TEST(EqualTest, RandomAccessComplexity) {
- std::vector<int> v1{1, 1, 3};
- std::vector<int> v2 = v1;
- std::vector<int> v3{1, 2};
-
- do {
- int count = 0;
- absl::equal(v1.begin(), v1.end(), v2.begin(), v2.end(),
- CountingTrivialPred{&count});
- EXPECT_LE(count, 3);
- } while (std::next_permutation(v2.begin(), v2.end()));
-
- int count = 0;
- absl::equal(v1.begin(), v1.end(), v3.begin(), v3.end(),
- CountingTrivialPred{&count});
- EXPECT_EQ(count, 0);
-}
-
-class LinearSearchTest : public testing::Test {
- protected:
- LinearSearchTest() : container_{1, 2, 3} {}
-
- static bool Is3(int n) { return n == 3; }
- static bool Is4(int n) { return n == 4; }
-
- std::vector<int> container_;
-};
-
-TEST_F(LinearSearchTest, linear_search) {
- EXPECT_TRUE(absl::linear_search(container_.begin(), container_.end(), 3));
- EXPECT_FALSE(absl::linear_search(container_.begin(), container_.end(), 4));
-}
-
-TEST_F(LinearSearchTest, linear_searchConst) {
- const std::vector<int> *const const_container = &container_;
- EXPECT_TRUE(
- absl::linear_search(const_container->begin(), const_container->end(), 3));
- EXPECT_FALSE(
- absl::linear_search(const_container->begin(), const_container->end(), 4));
-}
-
-TEST(RotateTest, Rotate) {
- std::vector<int> v{0, 1, 2, 3, 4};
- EXPECT_EQ(*absl::rotate(v.begin(), v.begin() + 2, v.end()), 0);
- EXPECT_THAT(v, testing::ElementsAreArray({2, 3, 4, 0, 1}));
-
- std::list<int> l{0, 1, 2, 3, 4};
- EXPECT_EQ(*absl::rotate(l.begin(), std::next(l.begin(), 3), l.end()), 0);
- EXPECT_THAT(l, testing::ElementsAreArray({3, 4, 0, 1, 2}));
-}
-
-} // namespace
diff --git a/third_party/abseil-cpp/absl/algorithm/container.h b/third_party/abseil-cpp/absl/algorithm/container.h
deleted file mode 100644
index 26b1952..0000000
--- a/third_party/abseil-cpp/absl/algorithm/container.h
+++ /dev/null
@@ -1,1774 +0,0 @@
-// Copyright 2017 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.
-//
-// -----------------------------------------------------------------------------
-// File: container.h
-// -----------------------------------------------------------------------------
-//
-// This header file provides Container-based versions of algorithmic functions
-// within the C++ standard library. The following standard library sets of
-// functions are covered within this file:
-//
-// * Algorithmic <iterator> functions
-// * Algorithmic <numeric> functions
-// * <algorithm> functions
-//
-// The standard library functions operate on iterator ranges; the functions
-// within this API operate on containers, though many return iterator ranges.
-//
-// All functions within this API are named with a `c_` prefix. Calls such as
-// `absl::c_xx(container, ...) are equivalent to std:: functions such as
-// `std::xx(std::begin(cont), std::end(cont), ...)`. Functions that act on
-// iterators but not conceptually on iterator ranges (e.g. `std::iter_swap`)
-// have no equivalent here.
-//
-// For template parameter and variable naming, `C` indicates the container type
-// to which the function is applied, `Pred` indicates the predicate object type
-// to be used by the function and `T` indicates the applicable element type.
-
-#ifndef ABSL_ALGORITHM_CONTAINER_H_
-#define ABSL_ALGORITHM_CONTAINER_H_
-
-#include <algorithm>
-#include <cassert>
-#include <iterator>
-#include <numeric>
-#include <type_traits>
-#include <unordered_map>
-#include <unordered_set>
-#include <utility>
-#include <vector>
-
-#include "absl/algorithm/algorithm.h"
-#include "absl/base/macros.h"
-#include "absl/meta/type_traits.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_algorithm_internal {
-
-// NOTE: it is important to defer to ADL lookup for building with C++ modules,
-// especially for headers like <valarray> which are not visible from this file
-// but specialize std::begin and std::end.
-using std::begin;
-using std::end;
-
-// The type of the iterator given by begin(c) (possibly std::begin(c)).
-// ContainerIter<const vector<T>> gives vector<T>::const_iterator,
-// while ContainerIter<vector<T>> gives vector<T>::iterator.
-template <typename C>
-using ContainerIter = decltype(begin(std::declval<C&>()));
-
-// An MSVC bug involving template parameter substitution requires us to use
-// decltype() here instead of just std::pair.
-template <typename C1, typename C2>
-using ContainerIterPairType =
- decltype(std::make_pair(ContainerIter<C1>(), ContainerIter<C2>()));
-
-template <typename C>
-using ContainerDifferenceType =
- decltype(std::distance(std::declval<ContainerIter<C>>(),
- std::declval<ContainerIter<C>>()));
-
-template <typename C>
-using ContainerPointerType =
- typename std::iterator_traits<ContainerIter<C>>::pointer;
-
-// container_algorithm_internal::c_begin and
-// container_algorithm_internal::c_end are abbreviations for proper ADL
-// lookup of std::begin and std::end, i.e.
-// using std::begin;
-// using std::end;
-// std::foo(begin(c), end(c));
-// becomes
-// std::foo(container_algorithm_internal::begin(c),
-// container_algorithm_internal::end(c));
-// These are meant for internal use only.
-
-template <typename C>
-ContainerIter<C> c_begin(C& c) { return begin(c); }
-
-template <typename C>
-ContainerIter<C> c_end(C& c) { return end(c); }
-
-template <typename T>
-struct IsUnorderedContainer : std::false_type {};
-
-template <class Key, class T, class Hash, class KeyEqual, class Allocator>
-struct IsUnorderedContainer<
- std::unordered_map<Key, T, Hash, KeyEqual, Allocator>> : std::true_type {};
-
-template <class Key, class Hash, class KeyEqual, class Allocator>
-struct IsUnorderedContainer<std::unordered_set<Key, Hash, KeyEqual, Allocator>>
- : std::true_type {};
-
-// container_algorithm_internal::c_size. It is meant for internal use only.
-
-template <class C>
-auto c_size(C& c) -> decltype(c.size()) {
- return c.size();
-}
-
-template <class T, std::size_t N>
-constexpr std::size_t c_size(T (&)[N]) {
- return N;
-}
-
-} // namespace container_algorithm_internal
-
-// PUBLIC API
-
-//------------------------------------------------------------------------------
-// Abseil algorithm.h functions
-//------------------------------------------------------------------------------
-
-// c_linear_search()
-//
-// Container-based version of absl::linear_search() for performing a linear
-// search within a container.
-template <typename C, typename EqualityComparable>
-bool c_linear_search(const C& c, EqualityComparable&& value) {
- return linear_search(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c),
- std::forward<EqualityComparable>(value));
-}
-
-//------------------------------------------------------------------------------
-// <iterator> algorithms
-//------------------------------------------------------------------------------
-
-// c_distance()
-//
-// Container-based version of the <iterator> `std::distance()` function to
-// return the number of elements within a container.
-template <typename C>
-container_algorithm_internal::ContainerDifferenceType<const C> c_distance(
- const C& c) {
- return std::distance(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c));
-}
-
-//------------------------------------------------------------------------------
-// <algorithm> Non-modifying sequence operations
-//------------------------------------------------------------------------------
-
-// c_all_of()
-//
-// Container-based version of the <algorithm> `std::all_of()` function to
-// test if all elements within a container satisfy a condition.
-template <typename C, typename Pred>
-bool c_all_of(const C& c, Pred&& pred) {
- return std::all_of(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c),
- std::forward<Pred>(pred));
-}
-
-// c_any_of()
-//
-// Container-based version of the <algorithm> `std::any_of()` function to
-// test if any element in a container fulfills a condition.
-template <typename C, typename Pred>
-bool c_any_of(const C& c, Pred&& pred) {
- return std::any_of(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c),
- std::forward<Pred>(pred));
-}
-
-// c_none_of()
-//
-// Container-based version of the <algorithm> `std::none_of()` function to
-// test if no elements in a container fulfill a condition.
-template <typename C, typename Pred>
-bool c_none_of(const C& c, Pred&& pred) {
- return std::none_of(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c),
- std::forward<Pred>(pred));
-}
-
-// c_for_each()
-//
-// Container-based version of the <algorithm> `std::for_each()` function to
-// apply a function to a container's elements.
-template <typename C, typename Function>
-decay_t<Function> c_for_each(C&& c, Function&& f) {
- return std::for_each(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c),
- std::forward<Function>(f));
-}
-
-// c_find()
-//
-// Container-based version of the <algorithm> `std::find()` function to find
-// the first element containing the passed value within a container value.
-template <typename C, typename T>
-container_algorithm_internal::ContainerIter<C> c_find(C& c, T&& value) {
- return std::find(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c),
- std::forward<T>(value));
-}
-
-// c_find_if()
-//
-// Container-based version of the <algorithm> `std::find_if()` function to find
-// the first element in a container matching the given condition.
-template <typename C, typename Pred>
-container_algorithm_internal::ContainerIter<C> c_find_if(C& c, Pred&& pred) {
- return std::find_if(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c),
- std::forward<Pred>(pred));
-}
-
-// c_find_if_not()
-//
-// Container-based version of the <algorithm> `std::find_if_not()` function to
-// find the first element in a container not matching the given condition.
-template <typename C, typename Pred>
-container_algorithm_internal::ContainerIter<C> c_find_if_not(C& c,
- Pred&& pred) {
- return std::find_if_not(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c),
- std::forward<Pred>(pred));
-}
-
-// c_find_end()
-//
-// Container-based version of the <algorithm> `std::find_end()` function to
-// find the last subsequence within a container.
-template <typename Sequence1, typename Sequence2>
-container_algorithm_internal::ContainerIter<Sequence1> c_find_end(
- Sequence1& sequence, Sequence2& subsequence) {
- return std::find_end(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence),
- container_algorithm_internal::c_begin(subsequence),
- container_algorithm_internal::c_end(subsequence));
-}
-
-// Overload of c_find_end() for using a predicate evaluation other than `==` as
-// the function's test condition.
-template <typename Sequence1, typename Sequence2, typename BinaryPredicate>
-container_algorithm_internal::ContainerIter<Sequence1> c_find_end(
- Sequence1& sequence, Sequence2& subsequence, BinaryPredicate&& pred) {
- return std::find_end(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence),
- container_algorithm_internal::c_begin(subsequence),
- container_algorithm_internal::c_end(subsequence),
- std::forward<BinaryPredicate>(pred));
-}
-
-// c_find_first_of()
-//
-// Container-based version of the <algorithm> `std::find_first_of()` function to
-// find the first element within the container that is also within the options
-// container.
-template <typename C1, typename C2>
-container_algorithm_internal::ContainerIter<C1> c_find_first_of(C1& container,
- C2& options) {
- return std::find_first_of(container_algorithm_internal::c_begin(container),
- container_algorithm_internal::c_end(container),
- container_algorithm_internal::c_begin(options),
- container_algorithm_internal::c_end(options));
-}
-
-// Overload of c_find_first_of() for using a predicate evaluation other than
-// `==` as the function's test condition.
-template <typename C1, typename C2, typename BinaryPredicate>
-container_algorithm_internal::ContainerIter<C1> c_find_first_of(
- C1& container, C2& options, BinaryPredicate&& pred) {
- return std::find_first_of(container_algorithm_internal::c_begin(container),
- container_algorithm_internal::c_end(container),
- container_algorithm_internal::c_begin(options),
- container_algorithm_internal::c_end(options),
- std::forward<BinaryPredicate>(pred));
-}
-
-// c_adjacent_find()
-//
-// Container-based version of the <algorithm> `std::adjacent_find()` function to
-// find equal adjacent elements within a container.
-template <typename Sequence>
-container_algorithm_internal::ContainerIter<Sequence> c_adjacent_find(
- Sequence& sequence) {
- return std::adjacent_find(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence));
-}
-
-// Overload of c_adjacent_find() for using a predicate evaluation other than
-// `==` as the function's test condition.
-template <typename Sequence, typename BinaryPredicate>
-container_algorithm_internal::ContainerIter<Sequence> c_adjacent_find(
- Sequence& sequence, BinaryPredicate&& pred) {
- return std::adjacent_find(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence),
- std::forward<BinaryPredicate>(pred));
-}
-
-// c_count()
-//
-// Container-based version of the <algorithm> `std::count()` function to count
-// values that match within a container.
-template <typename C, typename T>
-container_algorithm_internal::ContainerDifferenceType<const C> c_count(
- const C& c, T&& value) {
- return std::count(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c),
- std::forward<T>(value));
-}
-
-// c_count_if()
-//
-// Container-based version of the <algorithm> `std::count_if()` function to
-// count values matching a condition within a container.
-template <typename C, typename Pred>
-container_algorithm_internal::ContainerDifferenceType<const C> c_count_if(
- const C& c, Pred&& pred) {
- return std::count_if(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c),
- std::forward<Pred>(pred));
-}
-
-// c_mismatch()
-//
-// Container-based version of the <algorithm> `std::mismatch()` function to
-// return the first element where two ordered containers differ. Applies `==` to
-// the first N elements of `c1` and `c2`, where N = min(size(c1), size(c2)).
-template <typename C1, typename C2>
-container_algorithm_internal::ContainerIterPairType<C1, C2>
-c_mismatch(C1& c1, C2& c2) {
- auto first1 = container_algorithm_internal::c_begin(c1);
- auto last1 = container_algorithm_internal::c_end(c1);
- auto first2 = container_algorithm_internal::c_begin(c2);
- auto last2 = container_algorithm_internal::c_end(c2);
-
- for (; first1 != last1 && first2 != last2; ++first1, (void)++first2) {
- // Negates equality because Cpp17EqualityComparable doesn't require clients
- // to overload both `operator==` and `operator!=`.
- if (!(*first1 == *first2)) {
- break;
- }
- }
-
- return std::make_pair(first1, first2);
-}
-
-// Overload of c_mismatch() for using a predicate evaluation other than `==` as
-// the function's test condition. Applies `pred`to the first N elements of `c1`
-// and `c2`, where N = min(size(c1), size(c2)).
-template <typename C1, typename C2, typename BinaryPredicate>
-container_algorithm_internal::ContainerIterPairType<C1, C2>
-c_mismatch(C1& c1, C2& c2, BinaryPredicate pred) {
- auto first1 = container_algorithm_internal::c_begin(c1);
- auto last1 = container_algorithm_internal::c_end(c1);
- auto first2 = container_algorithm_internal::c_begin(c2);
- auto last2 = container_algorithm_internal::c_end(c2);
-
- for (; first1 != last1 && first2 != last2; ++first1, (void)++first2) {
- if (!pred(*first1, *first2)) {
- break;
- }
- }
-
- return std::make_pair(first1, first2);
-}
-
-// c_equal()
-//
-// Container-based version of the <algorithm> `std::equal()` function to
-// test whether two containers are equal.
-//
-// NOTE: the semantics of c_equal() are slightly different than those of
-// equal(): while the latter iterates over the second container only up to the
-// size of the first container, c_equal() also checks whether the container
-// sizes are equal. This better matches expectations about c_equal() based on
-// its signature.
-//
-// Example:
-// vector v1 = <1, 2, 3>;
-// vector v2 = <1, 2, 3, 4>;
-// equal(std::begin(v1), std::end(v1), std::begin(v2)) returns true
-// c_equal(v1, v2) returns false
-
-template <typename C1, typename C2>
-bool c_equal(const C1& c1, const C2& c2) {
- return ((container_algorithm_internal::c_size(c1) ==
- container_algorithm_internal::c_size(c2)) &&
- std::equal(container_algorithm_internal::c_begin(c1),
- container_algorithm_internal::c_end(c1),
- container_algorithm_internal::c_begin(c2)));
-}
-
-// Overload of c_equal() for using a predicate evaluation other than `==` as
-// the function's test condition.
-template <typename C1, typename C2, typename BinaryPredicate>
-bool c_equal(const C1& c1, const C2& c2, BinaryPredicate&& pred) {
- return ((container_algorithm_internal::c_size(c1) ==
- container_algorithm_internal::c_size(c2)) &&
- std::equal(container_algorithm_internal::c_begin(c1),
- container_algorithm_internal::c_end(c1),
- container_algorithm_internal::c_begin(c2),
- std::forward<BinaryPredicate>(pred)));
-}
-
-// c_is_permutation()
-//
-// Container-based version of the <algorithm> `std::is_permutation()` function
-// to test whether a container is a permutation of another.
-template <typename C1, typename C2>
-bool c_is_permutation(const C1& c1, const C2& c2) {
- using std::begin;
- using std::end;
- return c1.size() == c2.size() &&
- std::is_permutation(begin(c1), end(c1), begin(c2));
-}
-
-// Overload of c_is_permutation() for using a predicate evaluation other than
-// `==` as the function's test condition.
-template <typename C1, typename C2, typename BinaryPredicate>
-bool c_is_permutation(const C1& c1, const C2& c2, BinaryPredicate&& pred) {
- using std::begin;
- using std::end;
- return c1.size() == c2.size() &&
- std::is_permutation(begin(c1), end(c1), begin(c2),
- std::forward<BinaryPredicate>(pred));
-}
-
-// c_search()
-//
-// Container-based version of the <algorithm> `std::search()` function to search
-// a container for a subsequence.
-template <typename Sequence1, typename Sequence2>
-container_algorithm_internal::ContainerIter<Sequence1> c_search(
- Sequence1& sequence, Sequence2& subsequence) {
- return std::search(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence),
- container_algorithm_internal::c_begin(subsequence),
- container_algorithm_internal::c_end(subsequence));
-}
-
-// Overload of c_search() for using a predicate evaluation other than
-// `==` as the function's test condition.
-template <typename Sequence1, typename Sequence2, typename BinaryPredicate>
-container_algorithm_internal::ContainerIter<Sequence1> c_search(
- Sequence1& sequence, Sequence2& subsequence, BinaryPredicate&& pred) {
- return std::search(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence),
- container_algorithm_internal::c_begin(subsequence),
- container_algorithm_internal::c_end(subsequence),
- std::forward<BinaryPredicate>(pred));
-}
-
-// c_search_n()
-//
-// Container-based version of the <algorithm> `std::search_n()` function to
-// search a container for the first sequence of N elements.
-template <typename Sequence, typename Size, typename T>
-container_algorithm_internal::ContainerIter<Sequence> c_search_n(
- Sequence& sequence, Size count, T&& value) {
- return std::search_n(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence), count,
- std::forward<T>(value));
-}
-
-// Overload of c_search_n() for using a predicate evaluation other than
-// `==` as the function's test condition.
-template <typename Sequence, typename Size, typename T,
- typename BinaryPredicate>
-container_algorithm_internal::ContainerIter<Sequence> c_search_n(
- Sequence& sequence, Size count, T&& value, BinaryPredicate&& pred) {
- return std::search_n(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence), count,
- std::forward<T>(value),
- std::forward<BinaryPredicate>(pred));
-}
-
-//------------------------------------------------------------------------------
-// <algorithm> Modifying sequence operations
-//------------------------------------------------------------------------------
-
-// c_copy()
-//
-// Container-based version of the <algorithm> `std::copy()` function to copy a
-// container's elements into an iterator.
-template <typename InputSequence, typename OutputIterator>
-OutputIterator c_copy(const InputSequence& input, OutputIterator output) {
- return std::copy(container_algorithm_internal::c_begin(input),
- container_algorithm_internal::c_end(input), output);
-}
-
-// c_copy_n()
-//
-// Container-based version of the <algorithm> `std::copy_n()` function to copy a
-// container's first N elements into an iterator.
-template <typename C, typename Size, typename OutputIterator>
-OutputIterator c_copy_n(const C& input, Size n, OutputIterator output) {
- return std::copy_n(container_algorithm_internal::c_begin(input), n, output);
-}
-
-// c_copy_if()
-//
-// Container-based version of the <algorithm> `std::copy_if()` function to copy
-// a container's elements satisfying some condition into an iterator.
-template <typename InputSequence, typename OutputIterator, typename Pred>
-OutputIterator c_copy_if(const InputSequence& input, OutputIterator output,
- Pred&& pred) {
- return std::copy_if(container_algorithm_internal::c_begin(input),
- container_algorithm_internal::c_end(input), output,
- std::forward<Pred>(pred));
-}
-
-// c_copy_backward()
-//
-// Container-based version of the <algorithm> `std::copy_backward()` function to
-// copy a container's elements in reverse order into an iterator.
-template <typename C, typename BidirectionalIterator>
-BidirectionalIterator c_copy_backward(const C& src,
- BidirectionalIterator dest) {
- return std::copy_backward(container_algorithm_internal::c_begin(src),
- container_algorithm_internal::c_end(src), dest);
-}
-
-// c_move()
-//
-// Container-based version of the <algorithm> `std::move()` function to move
-// a container's elements into an iterator.
-template <typename C, typename OutputIterator>
-OutputIterator c_move(C&& src, OutputIterator dest) {
- return std::move(container_algorithm_internal::c_begin(src),
- container_algorithm_internal::c_end(src), dest);
-}
-
-// c_move_backward()
-//
-// Container-based version of the <algorithm> `std::move_backward()` function to
-// move a container's elements into an iterator in reverse order.
-template <typename C, typename BidirectionalIterator>
-BidirectionalIterator c_move_backward(C&& src, BidirectionalIterator dest) {
- return std::move_backward(container_algorithm_internal::c_begin(src),
- container_algorithm_internal::c_end(src), dest);
-}
-
-// c_swap_ranges()
-//
-// Container-based version of the <algorithm> `std::swap_ranges()` function to
-// swap a container's elements with another container's elements. Swaps the
-// first N elements of `c1` and `c2`, where N = min(size(c1), size(c2)).
-template <typename C1, typename C2>
-container_algorithm_internal::ContainerIter<C2> c_swap_ranges(C1& c1, C2& c2) {
- auto first1 = container_algorithm_internal::c_begin(c1);
- auto last1 = container_algorithm_internal::c_end(c1);
- auto first2 = container_algorithm_internal::c_begin(c2);
- auto last2 = container_algorithm_internal::c_end(c2);
-
- using std::swap;
- for (; first1 != last1 && first2 != last2; ++first1, (void)++first2) {
- swap(*first1, *first2);
- }
- return first2;
-}
-
-// c_transform()
-//
-// Container-based version of the <algorithm> `std::transform()` function to
-// transform a container's elements using the unary operation, storing the
-// result in an iterator pointing to the last transformed element in the output
-// range.
-template <typename InputSequence, typename OutputIterator, typename UnaryOp>
-OutputIterator c_transform(const InputSequence& input, OutputIterator output,
- UnaryOp&& unary_op) {
- return std::transform(container_algorithm_internal::c_begin(input),
- container_algorithm_internal::c_end(input), output,
- std::forward<UnaryOp>(unary_op));
-}
-
-// Overload of c_transform() for performing a transformation using a binary
-// predicate. Applies `binary_op` to the first N elements of `c1` and `c2`,
-// where N = min(size(c1), size(c2)).
-template <typename InputSequence1, typename InputSequence2,
- typename OutputIterator, typename BinaryOp>
-OutputIterator c_transform(const InputSequence1& input1,
- const InputSequence2& input2, OutputIterator output,
- BinaryOp&& binary_op) {
- auto first1 = container_algorithm_internal::c_begin(input1);
- auto last1 = container_algorithm_internal::c_end(input1);
- auto first2 = container_algorithm_internal::c_begin(input2);
- auto last2 = container_algorithm_internal::c_end(input2);
- for (; first1 != last1 && first2 != last2;
- ++first1, (void)++first2, ++output) {
- *output = binary_op(*first1, *first2);
- }
-
- return output;
-}
-
-// c_replace()
-//
-// Container-based version of the <algorithm> `std::replace()` function to
-// replace a container's elements of some value with a new value. The container
-// is modified in place.
-template <typename Sequence, typename T>
-void c_replace(Sequence& sequence, const T& old_value, const T& new_value) {
- std::replace(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence), old_value,
- new_value);
-}
-
-// c_replace_if()
-//
-// Container-based version of the <algorithm> `std::replace_if()` function to
-// replace a container's elements of some value with a new value based on some
-// condition. The container is modified in place.
-template <typename C, typename Pred, typename T>
-void c_replace_if(C& c, Pred&& pred, T&& new_value) {
- std::replace_if(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c),
- std::forward<Pred>(pred), std::forward<T>(new_value));
-}
-
-// c_replace_copy()
-//
-// Container-based version of the <algorithm> `std::replace_copy()` function to
-// replace a container's elements of some value with a new value and return the
-// results within an iterator.
-template <typename C, typename OutputIterator, typename T>
-OutputIterator c_replace_copy(const C& c, OutputIterator result, T&& old_value,
- T&& new_value) {
- return std::replace_copy(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c), result,
- std::forward<T>(old_value),
- std::forward<T>(new_value));
-}
-
-// c_replace_copy_if()
-//
-// Container-based version of the <algorithm> `std::replace_copy_if()` function
-// to replace a container's elements of some value with a new value based on
-// some condition, and return the results within an iterator.
-template <typename C, typename OutputIterator, typename Pred, typename T>
-OutputIterator c_replace_copy_if(const C& c, OutputIterator result, Pred&& pred,
- T&& new_value) {
- return std::replace_copy_if(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c), result,
- std::forward<Pred>(pred),
- std::forward<T>(new_value));
-}
-
-// c_fill()
-//
-// Container-based version of the <algorithm> `std::fill()` function to fill a
-// container with some value.
-template <typename C, typename T>
-void c_fill(C& c, T&& value) {
- std::fill(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c), std::forward<T>(value));
-}
-
-// c_fill_n()
-//
-// Container-based version of the <algorithm> `std::fill_n()` function to fill
-// the first N elements in a container with some value.
-template <typename C, typename Size, typename T>
-void c_fill_n(C& c, Size n, T&& value) {
- std::fill_n(container_algorithm_internal::c_begin(c), n,
- std::forward<T>(value));
-}
-
-// c_generate()
-//
-// Container-based version of the <algorithm> `std::generate()` function to
-// assign a container's elements to the values provided by the given generator.
-template <typename C, typename Generator>
-void c_generate(C& c, Generator&& gen) {
- std::generate(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c),
- std::forward<Generator>(gen));
-}
-
-// c_generate_n()
-//
-// Container-based version of the <algorithm> `std::generate_n()` function to
-// assign a container's first N elements to the values provided by the given
-// generator.
-template <typename C, typename Size, typename Generator>
-container_algorithm_internal::ContainerIter<C> c_generate_n(C& c, Size n,
- Generator&& gen) {
- return std::generate_n(container_algorithm_internal::c_begin(c), n,
- std::forward<Generator>(gen));
-}
-
-// Note: `c_xx()` <algorithm> container versions for `remove()`, `remove_if()`,
-// and `unique()` are omitted, because it's not clear whether or not such
-// functions should call erase on their supplied sequences afterwards. Either
-// behavior would be surprising for a different set of users.
-
-// c_remove_copy()
-//
-// Container-based version of the <algorithm> `std::remove_copy()` function to
-// copy a container's elements while removing any elements matching the given
-// `value`.
-template <typename C, typename OutputIterator, typename T>
-OutputIterator c_remove_copy(const C& c, OutputIterator result, T&& value) {
- return std::remove_copy(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c), result,
- std::forward<T>(value));
-}
-
-// c_remove_copy_if()
-//
-// Container-based version of the <algorithm> `std::remove_copy_if()` function
-// to copy a container's elements while removing any elements matching the given
-// condition.
-template <typename C, typename OutputIterator, typename Pred>
-OutputIterator c_remove_copy_if(const C& c, OutputIterator result,
- Pred&& pred) {
- return std::remove_copy_if(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c), result,
- std::forward<Pred>(pred));
-}
-
-// c_unique_copy()
-//
-// Container-based version of the <algorithm> `std::unique_copy()` function to
-// copy a container's elements while removing any elements containing duplicate
-// values.
-template <typename C, typename OutputIterator>
-OutputIterator c_unique_copy(const C& c, OutputIterator result) {
- return std::unique_copy(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c), result);
-}
-
-// Overload of c_unique_copy() for using a predicate evaluation other than
-// `==` for comparing uniqueness of the element values.
-template <typename C, typename OutputIterator, typename BinaryPredicate>
-OutputIterator c_unique_copy(const C& c, OutputIterator result,
- BinaryPredicate&& pred) {
- return std::unique_copy(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c), result,
- std::forward<BinaryPredicate>(pred));
-}
-
-// c_reverse()
-//
-// Container-based version of the <algorithm> `std::reverse()` function to
-// reverse a container's elements.
-template <typename Sequence>
-void c_reverse(Sequence& sequence) {
- std::reverse(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence));
-}
-
-// c_reverse_copy()
-//
-// Container-based version of the <algorithm> `std::reverse()` function to
-// reverse a container's elements and write them to an iterator range.
-template <typename C, typename OutputIterator>
-OutputIterator c_reverse_copy(const C& sequence, OutputIterator result) {
- return std::reverse_copy(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence),
- result);
-}
-
-// c_rotate()
-//
-// Container-based version of the <algorithm> `std::rotate()` function to
-// shift a container's elements leftward such that the `middle` element becomes
-// the first element in the container.
-template <typename C,
- typename Iterator = container_algorithm_internal::ContainerIter<C>>
-Iterator c_rotate(C& sequence, Iterator middle) {
- return absl::rotate(container_algorithm_internal::c_begin(sequence), middle,
- container_algorithm_internal::c_end(sequence));
-}
-
-// c_rotate_copy()
-//
-// Container-based version of the <algorithm> `std::rotate_copy()` function to
-// shift a container's elements leftward such that the `middle` element becomes
-// the first element in a new iterator range.
-template <typename C, typename OutputIterator>
-OutputIterator c_rotate_copy(
- const C& sequence,
- container_algorithm_internal::ContainerIter<const C> middle,
- OutputIterator result) {
- return std::rotate_copy(container_algorithm_internal::c_begin(sequence),
- middle, container_algorithm_internal::c_end(sequence),
- result);
-}
-
-// c_shuffle()
-//
-// Container-based version of the <algorithm> `std::shuffle()` function to
-// randomly shuffle elements within the container using a `gen()` uniform random
-// number generator.
-template <typename RandomAccessContainer, typename UniformRandomBitGenerator>
-void c_shuffle(RandomAccessContainer& c, UniformRandomBitGenerator&& gen) {
- std::shuffle(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c),
- std::forward<UniformRandomBitGenerator>(gen));
-}
-
-//------------------------------------------------------------------------------
-// <algorithm> Partition functions
-//------------------------------------------------------------------------------
-
-// c_is_partitioned()
-//
-// Container-based version of the <algorithm> `std::is_partitioned()` function
-// to test whether all elements in the container for which `pred` returns `true`
-// precede those for which `pred` is `false`.
-template <typename C, typename Pred>
-bool c_is_partitioned(const C& c, Pred&& pred) {
- return std::is_partitioned(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c),
- std::forward<Pred>(pred));
-}
-
-// c_partition()
-//
-// Container-based version of the <algorithm> `std::partition()` function
-// to rearrange all elements in a container in such a way that all elements for
-// which `pred` returns `true` precede all those for which it returns `false`,
-// returning an iterator to the first element of the second group.
-template <typename C, typename Pred>
-container_algorithm_internal::ContainerIter<C> c_partition(C& c, Pred&& pred) {
- return std::partition(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c),
- std::forward<Pred>(pred));
-}
-
-// c_stable_partition()
-//
-// Container-based version of the <algorithm> `std::stable_partition()` function
-// to rearrange all elements in a container in such a way that all elements for
-// which `pred` returns `true` precede all those for which it returns `false`,
-// preserving the relative ordering between the two groups. The function returns
-// an iterator to the first element of the second group.
-template <typename C, typename Pred>
-container_algorithm_internal::ContainerIter<C> c_stable_partition(C& c,
- Pred&& pred) {
- return std::stable_partition(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c),
- std::forward<Pred>(pred));
-}
-
-// c_partition_copy()
-//
-// Container-based version of the <algorithm> `std::partition_copy()` function
-// to partition a container's elements and return them into two iterators: one
-// for which `pred` returns `true`, and one for which `pred` returns `false.`
-
-template <typename C, typename OutputIterator1, typename OutputIterator2,
- typename Pred>
-std::pair<OutputIterator1, OutputIterator2> c_partition_copy(
- const C& c, OutputIterator1 out_true, OutputIterator2 out_false,
- Pred&& pred) {
- return std::partition_copy(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c), out_true,
- out_false, std::forward<Pred>(pred));
-}
-
-// c_partition_point()
-//
-// Container-based version of the <algorithm> `std::partition_point()` function
-// to return the first element of an already partitioned container for which
-// the given `pred` is not `true`.
-template <typename C, typename Pred>
-container_algorithm_internal::ContainerIter<C> c_partition_point(C& c,
- Pred&& pred) {
- return std::partition_point(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c),
- std::forward<Pred>(pred));
-}
-
-//------------------------------------------------------------------------------
-// <algorithm> Sorting functions
-//------------------------------------------------------------------------------
-
-// c_sort()
-//
-// Container-based version of the <algorithm> `std::sort()` function
-// to sort elements in ascending order of their values.
-template <typename C>
-void c_sort(C& c) {
- std::sort(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c));
-}
-
-// Overload of c_sort() for performing a `comp` comparison other than the
-// default `operator<`.
-template <typename C, typename LessThan>
-void c_sort(C& c, LessThan&& comp) {
- std::sort(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c),
- std::forward<LessThan>(comp));
-}
-
-// c_stable_sort()
-//
-// Container-based version of the <algorithm> `std::stable_sort()` function
-// to sort elements in ascending order of their values, preserving the order
-// of equivalents.
-template <typename C>
-void c_stable_sort(C& c) {
- std::stable_sort(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c));
-}
-
-// Overload of c_stable_sort() for performing a `comp` comparison other than the
-// default `operator<`.
-template <typename C, typename LessThan>
-void c_stable_sort(C& c, LessThan&& comp) {
- std::stable_sort(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c),
- std::forward<LessThan>(comp));
-}
-
-// c_is_sorted()
-//
-// Container-based version of the <algorithm> `std::is_sorted()` function
-// to evaluate whether the given container is sorted in ascending order.
-template <typename C>
-bool c_is_sorted(const C& c) {
- return std::is_sorted(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c));
-}
-
-// c_is_sorted() overload for performing a `comp` comparison other than the
-// default `operator<`.
-template <typename C, typename LessThan>
-bool c_is_sorted(const C& c, LessThan&& comp) {
- return std::is_sorted(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c),
- std::forward<LessThan>(comp));
-}
-
-// c_partial_sort()
-//
-// Container-based version of the <algorithm> `std::partial_sort()` function
-// to rearrange elements within a container such that elements before `middle`
-// are sorted in ascending order.
-template <typename RandomAccessContainer>
-void c_partial_sort(
- RandomAccessContainer& sequence,
- container_algorithm_internal::ContainerIter<RandomAccessContainer> middle) {
- std::partial_sort(container_algorithm_internal::c_begin(sequence), middle,
- container_algorithm_internal::c_end(sequence));
-}
-
-// Overload of c_partial_sort() for performing a `comp` comparison other than
-// the default `operator<`.
-template <typename RandomAccessContainer, typename LessThan>
-void c_partial_sort(
- RandomAccessContainer& sequence,
- container_algorithm_internal::ContainerIter<RandomAccessContainer> middle,
- LessThan&& comp) {
- std::partial_sort(container_algorithm_internal::c_begin(sequence), middle,
- container_algorithm_internal::c_end(sequence),
- std::forward<LessThan>(comp));
-}
-
-// c_partial_sort_copy()
-//
-// Container-based version of the <algorithm> `std::partial_sort_copy()`
-// function to sort the elements in the given range `result` within the larger
-// `sequence` in ascending order (and using `result` as the output parameter).
-// At most min(result.last - result.first, sequence.last - sequence.first)
-// elements from the sequence will be stored in the result.
-template <typename C, typename RandomAccessContainer>
-container_algorithm_internal::ContainerIter<RandomAccessContainer>
-c_partial_sort_copy(const C& sequence, RandomAccessContainer& result) {
- return std::partial_sort_copy(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence),
- container_algorithm_internal::c_begin(result),
- container_algorithm_internal::c_end(result));
-}
-
-// Overload of c_partial_sort_copy() for performing a `comp` comparison other
-// than the default `operator<`.
-template <typename C, typename RandomAccessContainer, typename LessThan>
-container_algorithm_internal::ContainerIter<RandomAccessContainer>
-c_partial_sort_copy(const C& sequence, RandomAccessContainer& result,
- LessThan&& comp) {
- return std::partial_sort_copy(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence),
- container_algorithm_internal::c_begin(result),
- container_algorithm_internal::c_end(result),
- std::forward<LessThan>(comp));
-}
-
-// c_is_sorted_until()
-//
-// Container-based version of the <algorithm> `std::is_sorted_until()` function
-// to return the first element within a container that is not sorted in
-// ascending order as an iterator.
-template <typename C>
-container_algorithm_internal::ContainerIter<C> c_is_sorted_until(C& c) {
- return std::is_sorted_until(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c));
-}
-
-// Overload of c_is_sorted_until() for performing a `comp` comparison other than
-// the default `operator<`.
-template <typename C, typename LessThan>
-container_algorithm_internal::ContainerIter<C> c_is_sorted_until(
- C& c, LessThan&& comp) {
- return std::is_sorted_until(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c),
- std::forward<LessThan>(comp));
-}
-
-// c_nth_element()
-//
-// Container-based version of the <algorithm> `std::nth_element()` function
-// to rearrange the elements within a container such that the `nth` element
-// would be in that position in an ordered sequence; other elements may be in
-// any order, except that all preceding `nth` will be less than that element,
-// and all following `nth` will be greater than that element.
-template <typename RandomAccessContainer>
-void c_nth_element(
- RandomAccessContainer& sequence,
- container_algorithm_internal::ContainerIter<RandomAccessContainer> nth) {
- std::nth_element(container_algorithm_internal::c_begin(sequence), nth,
- container_algorithm_internal::c_end(sequence));
-}
-
-// Overload of c_nth_element() for performing a `comp` comparison other than
-// the default `operator<`.
-template <typename RandomAccessContainer, typename LessThan>
-void c_nth_element(
- RandomAccessContainer& sequence,
- container_algorithm_internal::ContainerIter<RandomAccessContainer> nth,
- LessThan&& comp) {
- std::nth_element(container_algorithm_internal::c_begin(sequence), nth,
- container_algorithm_internal::c_end(sequence),
- std::forward<LessThan>(comp));
-}
-
-//------------------------------------------------------------------------------
-// <algorithm> Binary Search
-//------------------------------------------------------------------------------
-
-// c_lower_bound()
-//
-// Container-based version of the <algorithm> `std::lower_bound()` function
-// to return an iterator pointing to the first element in a sorted container
-// which does not compare less than `value`.
-template <typename Sequence, typename T>
-container_algorithm_internal::ContainerIter<Sequence> c_lower_bound(
- Sequence& sequence, T&& value) {
- return std::lower_bound(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence),
- std::forward<T>(value));
-}
-
-// Overload of c_lower_bound() for performing a `comp` comparison other than
-// the default `operator<`.
-template <typename Sequence, typename T, typename LessThan>
-container_algorithm_internal::ContainerIter<Sequence> c_lower_bound(
- Sequence& sequence, T&& value, LessThan&& comp) {
- return std::lower_bound(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence),
- std::forward<T>(value), std::forward<LessThan>(comp));
-}
-
-// c_upper_bound()
-//
-// Container-based version of the <algorithm> `std::upper_bound()` function
-// to return an iterator pointing to the first element in a sorted container
-// which is greater than `value`.
-template <typename Sequence, typename T>
-container_algorithm_internal::ContainerIter<Sequence> c_upper_bound(
- Sequence& sequence, T&& value) {
- return std::upper_bound(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence),
- std::forward<T>(value));
-}
-
-// Overload of c_upper_bound() for performing a `comp` comparison other than
-// the default `operator<`.
-template <typename Sequence, typename T, typename LessThan>
-container_algorithm_internal::ContainerIter<Sequence> c_upper_bound(
- Sequence& sequence, T&& value, LessThan&& comp) {
- return std::upper_bound(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence),
- std::forward<T>(value), std::forward<LessThan>(comp));
-}
-
-// c_equal_range()
-//
-// Container-based version of the <algorithm> `std::equal_range()` function
-// to return an iterator pair pointing to the first and last elements in a
-// sorted container which compare equal to `value`.
-template <typename Sequence, typename T>
-container_algorithm_internal::ContainerIterPairType<Sequence, Sequence>
-c_equal_range(Sequence& sequence, T&& value) {
- return std::equal_range(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence),
- std::forward<T>(value));
-}
-
-// Overload of c_equal_range() for performing a `comp` comparison other than
-// the default `operator<`.
-template <typename Sequence, typename T, typename LessThan>
-container_algorithm_internal::ContainerIterPairType<Sequence, Sequence>
-c_equal_range(Sequence& sequence, T&& value, LessThan&& comp) {
- return std::equal_range(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence),
- std::forward<T>(value), std::forward<LessThan>(comp));
-}
-
-// c_binary_search()
-//
-// Container-based version of the <algorithm> `std::binary_search()` function
-// to test if any element in the sorted container contains a value equivalent to
-// 'value'.
-template <typename Sequence, typename T>
-bool c_binary_search(Sequence&& sequence, T&& value) {
- return std::binary_search(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence),
- std::forward<T>(value));
-}
-
-// Overload of c_binary_search() for performing a `comp` comparison other than
-// the default `operator<`.
-template <typename Sequence, typename T, typename LessThan>
-bool c_binary_search(Sequence&& sequence, T&& value, LessThan&& comp) {
- return std::binary_search(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence),
- std::forward<T>(value),
- std::forward<LessThan>(comp));
-}
-
-//------------------------------------------------------------------------------
-// <algorithm> Merge functions
-//------------------------------------------------------------------------------
-
-// c_merge()
-//
-// Container-based version of the <algorithm> `std::merge()` function
-// to merge two sorted containers into a single sorted iterator.
-template <typename C1, typename C2, typename OutputIterator>
-OutputIterator c_merge(const C1& c1, const C2& c2, OutputIterator result) {
- return std::merge(container_algorithm_internal::c_begin(c1),
- container_algorithm_internal::c_end(c1),
- container_algorithm_internal::c_begin(c2),
- container_algorithm_internal::c_end(c2), result);
-}
-
-// Overload of c_merge() for performing a `comp` comparison other than
-// the default `operator<`.
-template <typename C1, typename C2, typename OutputIterator, typename LessThan>
-OutputIterator c_merge(const C1& c1, const C2& c2, OutputIterator result,
- LessThan&& comp) {
- return std::merge(container_algorithm_internal::c_begin(c1),
- container_algorithm_internal::c_end(c1),
- container_algorithm_internal::c_begin(c2),
- container_algorithm_internal::c_end(c2), result,
- std::forward<LessThan>(comp));
-}
-
-// c_inplace_merge()
-//
-// Container-based version of the <algorithm> `std::inplace_merge()` function
-// to merge a supplied iterator `middle` into a container.
-template <typename C>
-void c_inplace_merge(C& c,
- container_algorithm_internal::ContainerIter<C> middle) {
- std::inplace_merge(container_algorithm_internal::c_begin(c), middle,
- container_algorithm_internal::c_end(c));
-}
-
-// Overload of c_inplace_merge() for performing a merge using a `comp` other
-// than `operator<`.
-template <typename C, typename LessThan>
-void c_inplace_merge(C& c,
- container_algorithm_internal::ContainerIter<C> middle,
- LessThan&& comp) {
- std::inplace_merge(container_algorithm_internal::c_begin(c), middle,
- container_algorithm_internal::c_end(c),
- std::forward<LessThan>(comp));
-}
-
-// c_includes()
-//
-// Container-based version of the <algorithm> `std::includes()` function
-// to test whether a sorted container `c1` entirely contains another sorted
-// container `c2`.
-template <typename C1, typename C2>
-bool c_includes(const C1& c1, const C2& c2) {
- return std::includes(container_algorithm_internal::c_begin(c1),
- container_algorithm_internal::c_end(c1),
- container_algorithm_internal::c_begin(c2),
- container_algorithm_internal::c_end(c2));
-}
-
-// Overload of c_includes() for performing a merge using a `comp` other than
-// `operator<`.
-template <typename C1, typename C2, typename LessThan>
-bool c_includes(const C1& c1, const C2& c2, LessThan&& comp) {
- return std::includes(container_algorithm_internal::c_begin(c1),
- container_algorithm_internal::c_end(c1),
- container_algorithm_internal::c_begin(c2),
- container_algorithm_internal::c_end(c2),
- std::forward<LessThan>(comp));
-}
-
-// c_set_union()
-//
-// Container-based version of the <algorithm> `std::set_union()` function
-// to return an iterator containing the union of two containers; duplicate
-// values are not copied into the output.
-template <typename C1, typename C2, typename OutputIterator,
- typename = typename std::enable_if<
- !container_algorithm_internal::IsUnorderedContainer<C1>::value,
- void>::type,
- typename = typename std::enable_if<
- !container_algorithm_internal::IsUnorderedContainer<C2>::value,
- void>::type>
-OutputIterator c_set_union(const C1& c1, const C2& c2, OutputIterator output) {
- return std::set_union(container_algorithm_internal::c_begin(c1),
- container_algorithm_internal::c_end(c1),
- container_algorithm_internal::c_begin(c2),
- container_algorithm_internal::c_end(c2), output);
-}
-
-// Overload of c_set_union() for performing a merge using a `comp` other than
-// `operator<`.
-template <typename C1, typename C2, typename OutputIterator, typename LessThan,
- typename = typename std::enable_if<
- !container_algorithm_internal::IsUnorderedContainer<C1>::value,
- void>::type,
- typename = typename std::enable_if<
- !container_algorithm_internal::IsUnorderedContainer<C2>::value,
- void>::type>
-OutputIterator c_set_union(const C1& c1, const C2& c2, OutputIterator output,
- LessThan&& comp) {
- return std::set_union(container_algorithm_internal::c_begin(c1),
- container_algorithm_internal::c_end(c1),
- container_algorithm_internal::c_begin(c2),
- container_algorithm_internal::c_end(c2), output,
- std::forward<LessThan>(comp));
-}
-
-// c_set_intersection()
-//
-// Container-based version of the <algorithm> `std::set_intersection()` function
-// to return an iterator containing the intersection of two sorted containers.
-template <typename C1, typename C2, typename OutputIterator,
- typename = typename std::enable_if<
- !container_algorithm_internal::IsUnorderedContainer<C1>::value,
- void>::type,
- typename = typename std::enable_if<
- !container_algorithm_internal::IsUnorderedContainer<C2>::value,
- void>::type>
-OutputIterator c_set_intersection(const C1& c1, const C2& c2,
- OutputIterator output) {
- // In debug builds, ensure that both containers are sorted with respect to the
- // default comparator. std::set_intersection requires the containers be sorted
- // using operator<.
- assert(absl::c_is_sorted(c1));
- assert(absl::c_is_sorted(c2));
- return std::set_intersection(container_algorithm_internal::c_begin(c1),
- container_algorithm_internal::c_end(c1),
- container_algorithm_internal::c_begin(c2),
- container_algorithm_internal::c_end(c2), output);
-}
-
-// Overload of c_set_intersection() for performing a merge using a `comp` other
-// than `operator<`.
-template <typename C1, typename C2, typename OutputIterator, typename LessThan,
- typename = typename std::enable_if<
- !container_algorithm_internal::IsUnorderedContainer<C1>::value,
- void>::type,
- typename = typename std::enable_if<
- !container_algorithm_internal::IsUnorderedContainer<C2>::value,
- void>::type>
-OutputIterator c_set_intersection(const C1& c1, const C2& c2,
- OutputIterator output, LessThan&& comp) {
- // In debug builds, ensure that both containers are sorted with respect to the
- // default comparator. std::set_intersection requires the containers be sorted
- // using the same comparator.
- assert(absl::c_is_sorted(c1, comp));
- assert(absl::c_is_sorted(c2, comp));
- return std::set_intersection(container_algorithm_internal::c_begin(c1),
- container_algorithm_internal::c_end(c1),
- container_algorithm_internal::c_begin(c2),
- container_algorithm_internal::c_end(c2), output,
- std::forward<LessThan>(comp));
-}
-
-// c_set_difference()
-//
-// Container-based version of the <algorithm> `std::set_difference()` function
-// to return an iterator containing elements present in the first container but
-// not in the second.
-template <typename C1, typename C2, typename OutputIterator,
- typename = typename std::enable_if<
- !container_algorithm_internal::IsUnorderedContainer<C1>::value,
- void>::type,
- typename = typename std::enable_if<
- !container_algorithm_internal::IsUnorderedContainer<C2>::value,
- void>::type>
-OutputIterator c_set_difference(const C1& c1, const C2& c2,
- OutputIterator output) {
- return std::set_difference(container_algorithm_internal::c_begin(c1),
- container_algorithm_internal::c_end(c1),
- container_algorithm_internal::c_begin(c2),
- container_algorithm_internal::c_end(c2), output);
-}
-
-// Overload of c_set_difference() for performing a merge using a `comp` other
-// than `operator<`.
-template <typename C1, typename C2, typename OutputIterator, typename LessThan,
- typename = typename std::enable_if<
- !container_algorithm_internal::IsUnorderedContainer<C1>::value,
- void>::type,
- typename = typename std::enable_if<
- !container_algorithm_internal::IsUnorderedContainer<C2>::value,
- void>::type>
-OutputIterator c_set_difference(const C1& c1, const C2& c2,
- OutputIterator output, LessThan&& comp) {
- return std::set_difference(container_algorithm_internal::c_begin(c1),
- container_algorithm_internal::c_end(c1),
- container_algorithm_internal::c_begin(c2),
- container_algorithm_internal::c_end(c2), output,
- std::forward<LessThan>(comp));
-}
-
-// c_set_symmetric_difference()
-//
-// Container-based version of the <algorithm> `std::set_symmetric_difference()`
-// function to return an iterator containing elements present in either one
-// container or the other, but not both.
-template <typename C1, typename C2, typename OutputIterator,
- typename = typename std::enable_if<
- !container_algorithm_internal::IsUnorderedContainer<C1>::value,
- void>::type,
- typename = typename std::enable_if<
- !container_algorithm_internal::IsUnorderedContainer<C2>::value,
- void>::type>
-OutputIterator c_set_symmetric_difference(const C1& c1, const C2& c2,
- OutputIterator output) {
- return std::set_symmetric_difference(
- container_algorithm_internal::c_begin(c1),
- container_algorithm_internal::c_end(c1),
- container_algorithm_internal::c_begin(c2),
- container_algorithm_internal::c_end(c2), output);
-}
-
-// Overload of c_set_symmetric_difference() for performing a merge using a
-// `comp` other than `operator<`.
-template <typename C1, typename C2, typename OutputIterator, typename LessThan,
- typename = typename std::enable_if<
- !container_algorithm_internal::IsUnorderedContainer<C1>::value,
- void>::type,
- typename = typename std::enable_if<
- !container_algorithm_internal::IsUnorderedContainer<C2>::value,
- void>::type>
-OutputIterator c_set_symmetric_difference(const C1& c1, const C2& c2,
- OutputIterator output,
- LessThan&& comp) {
- return std::set_symmetric_difference(
- container_algorithm_internal::c_begin(c1),
- container_algorithm_internal::c_end(c1),
- container_algorithm_internal::c_begin(c2),
- container_algorithm_internal::c_end(c2), output,
- std::forward<LessThan>(comp));
-}
-
-//------------------------------------------------------------------------------
-// <algorithm> Heap functions
-//------------------------------------------------------------------------------
-
-// c_push_heap()
-//
-// Container-based version of the <algorithm> `std::push_heap()` function
-// to push a value onto a container heap.
-template <typename RandomAccessContainer>
-void c_push_heap(RandomAccessContainer& sequence) {
- std::push_heap(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence));
-}
-
-// Overload of c_push_heap() for performing a push operation on a heap using a
-// `comp` other than `operator<`.
-template <typename RandomAccessContainer, typename LessThan>
-void c_push_heap(RandomAccessContainer& sequence, LessThan&& comp) {
- std::push_heap(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence),
- std::forward<LessThan>(comp));
-}
-
-// c_pop_heap()
-//
-// Container-based version of the <algorithm> `std::pop_heap()` function
-// to pop a value from a heap container.
-template <typename RandomAccessContainer>
-void c_pop_heap(RandomAccessContainer& sequence) {
- std::pop_heap(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence));
-}
-
-// Overload of c_pop_heap() for performing a pop operation on a heap using a
-// `comp` other than `operator<`.
-template <typename RandomAccessContainer, typename LessThan>
-void c_pop_heap(RandomAccessContainer& sequence, LessThan&& comp) {
- std::pop_heap(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence),
- std::forward<LessThan>(comp));
-}
-
-// c_make_heap()
-//
-// Container-based version of the <algorithm> `std::make_heap()` function
-// to make a container a heap.
-template <typename RandomAccessContainer>
-void c_make_heap(RandomAccessContainer& sequence) {
- std::make_heap(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence));
-}
-
-// Overload of c_make_heap() for performing heap comparisons using a
-// `comp` other than `operator<`
-template <typename RandomAccessContainer, typename LessThan>
-void c_make_heap(RandomAccessContainer& sequence, LessThan&& comp) {
- std::make_heap(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence),
- std::forward<LessThan>(comp));
-}
-
-// c_sort_heap()
-//
-// Container-based version of the <algorithm> `std::sort_heap()` function
-// to sort a heap into ascending order (after which it is no longer a heap).
-template <typename RandomAccessContainer>
-void c_sort_heap(RandomAccessContainer& sequence) {
- std::sort_heap(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence));
-}
-
-// Overload of c_sort_heap() for performing heap comparisons using a
-// `comp` other than `operator<`
-template <typename RandomAccessContainer, typename LessThan>
-void c_sort_heap(RandomAccessContainer& sequence, LessThan&& comp) {
- std::sort_heap(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence),
- std::forward<LessThan>(comp));
-}
-
-// c_is_heap()
-//
-// Container-based version of the <algorithm> `std::is_heap()` function
-// to check whether the given container is a heap.
-template <typename RandomAccessContainer>
-bool c_is_heap(const RandomAccessContainer& sequence) {
- return std::is_heap(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence));
-}
-
-// Overload of c_is_heap() for performing heap comparisons using a
-// `comp` other than `operator<`
-template <typename RandomAccessContainer, typename LessThan>
-bool c_is_heap(const RandomAccessContainer& sequence, LessThan&& comp) {
- return std::is_heap(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence),
- std::forward<LessThan>(comp));
-}
-
-// c_is_heap_until()
-//
-// Container-based version of the <algorithm> `std::is_heap_until()` function
-// to find the first element in a given container which is not in heap order.
-template <typename RandomAccessContainer>
-container_algorithm_internal::ContainerIter<RandomAccessContainer>
-c_is_heap_until(RandomAccessContainer& sequence) {
- return std::is_heap_until(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence));
-}
-
-// Overload of c_is_heap_until() for performing heap comparisons using a
-// `comp` other than `operator<`
-template <typename RandomAccessContainer, typename LessThan>
-container_algorithm_internal::ContainerIter<RandomAccessContainer>
-c_is_heap_until(RandomAccessContainer& sequence, LessThan&& comp) {
- return std::is_heap_until(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence),
- std::forward<LessThan>(comp));
-}
-
-//------------------------------------------------------------------------------
-// <algorithm> Min/max
-//------------------------------------------------------------------------------
-
-// c_min_element()
-//
-// Container-based version of the <algorithm> `std::min_element()` function
-// to return an iterator pointing to the element with the smallest value, using
-// `operator<` to make the comparisons.
-template <typename Sequence>
-container_algorithm_internal::ContainerIter<Sequence> c_min_element(
- Sequence& sequence) {
- return std::min_element(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence));
-}
-
-// Overload of c_min_element() for performing a `comp` comparison other than
-// `operator<`.
-template <typename Sequence, typename LessThan>
-container_algorithm_internal::ContainerIter<Sequence> c_min_element(
- Sequence& sequence, LessThan&& comp) {
- return std::min_element(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence),
- std::forward<LessThan>(comp));
-}
-
-// c_max_element()
-//
-// Container-based version of the <algorithm> `std::max_element()` function
-// to return an iterator pointing to the element with the largest value, using
-// `operator<` to make the comparisons.
-template <typename Sequence>
-container_algorithm_internal::ContainerIter<Sequence> c_max_element(
- Sequence& sequence) {
- return std::max_element(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence));
-}
-
-// Overload of c_max_element() for performing a `comp` comparison other than
-// `operator<`.
-template <typename Sequence, typename LessThan>
-container_algorithm_internal::ContainerIter<Sequence> c_max_element(
- Sequence& sequence, LessThan&& comp) {
- return std::max_element(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence),
- std::forward<LessThan>(comp));
-}
-
-// c_minmax_element()
-//
-// Container-based version of the <algorithm> `std::minmax_element()` function
-// to return a pair of iterators pointing to the elements containing the
-// smallest and largest values, respectively, using `operator<` to make the
-// comparisons.
-template <typename C>
-container_algorithm_internal::ContainerIterPairType<C, C>
-c_minmax_element(C& c) {
- return std::minmax_element(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c));
-}
-
-// Overload of c_minmax_element() for performing `comp` comparisons other than
-// `operator<`.
-template <typename C, typename LessThan>
-container_algorithm_internal::ContainerIterPairType<C, C>
-c_minmax_element(C& c, LessThan&& comp) {
- return std::minmax_element(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c),
- std::forward<LessThan>(comp));
-}
-
-//------------------------------------------------------------------------------
-// <algorithm> Lexicographical Comparisons
-//------------------------------------------------------------------------------
-
-// c_lexicographical_compare()
-//
-// Container-based version of the <algorithm> `std::lexicographical_compare()`
-// function to lexicographically compare (e.g. sort words alphabetically) two
-// container sequences. The comparison is performed using `operator<`. Note
-// that capital letters ("A-Z") have ASCII values less than lowercase letters
-// ("a-z").
-template <typename Sequence1, typename Sequence2>
-bool c_lexicographical_compare(Sequence1&& sequence1, Sequence2&& sequence2) {
- return std::lexicographical_compare(
- container_algorithm_internal::c_begin(sequence1),
- container_algorithm_internal::c_end(sequence1),
- container_algorithm_internal::c_begin(sequence2),
- container_algorithm_internal::c_end(sequence2));
-}
-
-// Overload of c_lexicographical_compare() for performing a lexicographical
-// comparison using a `comp` operator instead of `operator<`.
-template <typename Sequence1, typename Sequence2, typename LessThan>
-bool c_lexicographical_compare(Sequence1&& sequence1, Sequence2&& sequence2,
- LessThan&& comp) {
- return std::lexicographical_compare(
- container_algorithm_internal::c_begin(sequence1),
- container_algorithm_internal::c_end(sequence1),
- container_algorithm_internal::c_begin(sequence2),
- container_algorithm_internal::c_end(sequence2),
- std::forward<LessThan>(comp));
-}
-
-// c_next_permutation()
-//
-// Container-based version of the <algorithm> `std::next_permutation()` function
-// to rearrange a container's elements into the next lexicographically greater
-// permutation.
-template <typename C>
-bool c_next_permutation(C& c) {
- return std::next_permutation(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c));
-}
-
-// Overload of c_next_permutation() for performing a lexicographical
-// comparison using a `comp` operator instead of `operator<`.
-template <typename C, typename LessThan>
-bool c_next_permutation(C& c, LessThan&& comp) {
- return std::next_permutation(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c),
- std::forward<LessThan>(comp));
-}
-
-// c_prev_permutation()
-//
-// Container-based version of the <algorithm> `std::prev_permutation()` function
-// to rearrange a container's elements into the next lexicographically lesser
-// permutation.
-template <typename C>
-bool c_prev_permutation(C& c) {
- return std::prev_permutation(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c));
-}
-
-// Overload of c_prev_permutation() for performing a lexicographical
-// comparison using a `comp` operator instead of `operator<`.
-template <typename C, typename LessThan>
-bool c_prev_permutation(C& c, LessThan&& comp) {
- return std::prev_permutation(container_algorithm_internal::c_begin(c),
- container_algorithm_internal::c_end(c),
- std::forward<LessThan>(comp));
-}
-
-//------------------------------------------------------------------------------
-// <numeric> algorithms
-//------------------------------------------------------------------------------
-
-// c_iota()
-//
-// Container-based version of the <algorithm> `std::iota()` function
-// to compute successive values of `value`, as if incremented with `++value`
-// after each element is written. and write them to the container.
-template <typename Sequence, typename T>
-void c_iota(Sequence& sequence, T&& value) {
- std::iota(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence),
- std::forward<T>(value));
-}
-// c_accumulate()
-//
-// Container-based version of the <algorithm> `std::accumulate()` function
-// to accumulate the element values of a container to `init` and return that
-// accumulation by value.
-//
-// Note: Due to a language technicality this function has return type
-// absl::decay_t<T>. As a user of this function you can casually read
-// this as "returns T by value" and assume it does the right thing.
-template <typename Sequence, typename T>
-decay_t<T> c_accumulate(const Sequence& sequence, T&& init) {
- return std::accumulate(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence),
- std::forward<T>(init));
-}
-
-// Overload of c_accumulate() for using a binary operations other than
-// addition for computing the accumulation.
-template <typename Sequence, typename T, typename BinaryOp>
-decay_t<T> c_accumulate(const Sequence& sequence, T&& init,
- BinaryOp&& binary_op) {
- return std::accumulate(container_algorithm_internal::c_begin(sequence),
- container_algorithm_internal::c_end(sequence),
- std::forward<T>(init),
- std::forward<BinaryOp>(binary_op));
-}
-
-// c_inner_product()
-//
-// Container-based version of the <algorithm> `std::inner_product()` function
-// to compute the cumulative inner product of container element pairs.
-//
-// Note: Due to a language technicality this function has return type
-// absl::decay_t<T>. As a user of this function you can casually read
-// this as "returns T by value" and assume it does the right thing.
-template <typename Sequence1, typename Sequence2, typename T>
-decay_t<T> c_inner_product(const Sequence1& factors1, const Sequence2& factors2,
- T&& sum) {
- return std::inner_product(container_algorithm_internal::c_begin(factors1),
- container_algorithm_internal::c_end(factors1),
- container_algorithm_internal::c_begin(factors2),
- std::forward<T>(sum));
-}
-
-// Overload of c_inner_product() for using binary operations other than
-// `operator+` (for computing the accumulation) and `operator*` (for computing
-// the product between the two container's element pair).
-template <typename Sequence1, typename Sequence2, typename T,
- typename BinaryOp1, typename BinaryOp2>
-decay_t<T> c_inner_product(const Sequence1& factors1, const Sequence2& factors2,
- T&& sum, BinaryOp1&& op1, BinaryOp2&& op2) {
- return std::inner_product(container_algorithm_internal::c_begin(factors1),
- container_algorithm_internal::c_end(factors1),
- container_algorithm_internal::c_begin(factors2),
- std::forward<T>(sum), std::forward<BinaryOp1>(op1),
- std::forward<BinaryOp2>(op2));
-}
-
-// c_adjacent_difference()
-//
-// Container-based version of the <algorithm> `std::adjacent_difference()`
-// function to compute the difference between each element and the one preceding
-// it and write it to an iterator.
-template <typename InputSequence, typename OutputIt>
-OutputIt c_adjacent_difference(const InputSequence& input,
- OutputIt output_first) {
- return std::adjacent_difference(container_algorithm_internal::c_begin(input),
- container_algorithm_internal::c_end(input),
- output_first);
-}
-
-// Overload of c_adjacent_difference() for using a binary operation other than
-// subtraction to compute the adjacent difference.
-template <typename InputSequence, typename OutputIt, typename BinaryOp>
-OutputIt c_adjacent_difference(const InputSequence& input,
- OutputIt output_first, BinaryOp&& op) {
- return std::adjacent_difference(container_algorithm_internal::c_begin(input),
- container_algorithm_internal::c_end(input),
- output_first, std::forward<BinaryOp>(op));
-}
-
-// c_partial_sum()
-//
-// Container-based version of the <algorithm> `std::partial_sum()` function
-// to compute the partial sum of the elements in a sequence and write them
-// to an iterator. The partial sum is the sum of all element values so far in
-// the sequence.
-template <typename InputSequence, typename OutputIt>
-OutputIt c_partial_sum(const InputSequence& input, OutputIt output_first) {
- return std::partial_sum(container_algorithm_internal::c_begin(input),
- container_algorithm_internal::c_end(input),
- output_first);
-}
-
-// Overload of c_partial_sum() for using a binary operation other than addition
-// to compute the "partial sum".
-template <typename InputSequence, typename OutputIt, typename BinaryOp>
-OutputIt c_partial_sum(const InputSequence& input, OutputIt output_first,
- BinaryOp&& op) {
- return std::partial_sum(container_algorithm_internal::c_begin(input),
- container_algorithm_internal::c_end(input),
- output_first, std::forward<BinaryOp>(op));
-}
-
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_ALGORITHM_CONTAINER_H_
diff --git a/third_party/abseil-cpp/absl/algorithm/container_test.cc b/third_party/abseil-cpp/absl/algorithm/container_test.cc
deleted file mode 100644
index 0fbc777..0000000
--- a/third_party/abseil-cpp/absl/algorithm/container_test.cc
+++ /dev/null
@@ -1,1127 +0,0 @@
-// Copyright 2017 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/algorithm/container.h"
-
-#include <functional>
-#include <initializer_list>
-#include <iterator>
-#include <list>
-#include <memory>
-#include <ostream>
-#include <random>
-#include <set>
-#include <unordered_set>
-#include <utility>
-#include <valarray>
-#include <vector>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/base/casts.h"
-#include "absl/base/macros.h"
-#include "absl/memory/memory.h"
-#include "absl/types/span.h"
-
-namespace {
-
-using ::testing::Each;
-using ::testing::ElementsAre;
-using ::testing::Gt;
-using ::testing::IsNull;
-using ::testing::Lt;
-using ::testing::Pointee;
-using ::testing::Truly;
-using ::testing::UnorderedElementsAre;
-
-// Most of these tests just check that the code compiles, not that it
-// does the right thing. That's fine since the functions just forward
-// to the STL implementation.
-class NonMutatingTest : public testing::Test {
- protected:
- std::unordered_set<int> container_ = {1, 2, 3};
- std::list<int> sequence_ = {1, 2, 3};
- std::vector<int> vector_ = {1, 2, 3};
- int array_[3] = {1, 2, 3};
-};
-
-struct AccumulateCalls {
- void operator()(int value) { calls.push_back(value); }
- std::vector<int> calls;
-};
-
-bool Predicate(int value) { return value < 3; }
-bool BinPredicate(int v1, int v2) { return v1 < v2; }
-bool Equals(int v1, int v2) { return v1 == v2; }
-bool IsOdd(int x) { return x % 2 != 0; }
-
-TEST_F(NonMutatingTest, Distance) {
- EXPECT_EQ(container_.size(),
- static_cast<size_t>(absl::c_distance(container_)));
- EXPECT_EQ(sequence_.size(), static_cast<size_t>(absl::c_distance(sequence_)));
- EXPECT_EQ(vector_.size(), static_cast<size_t>(absl::c_distance(vector_)));
- EXPECT_EQ(ABSL_ARRAYSIZE(array_),
- static_cast<size_t>(absl::c_distance(array_)));
-
- // Works with a temporary argument.
- EXPECT_EQ(vector_.size(),
- static_cast<size_t>(absl::c_distance(std::vector<int>(vector_))));
-}
-
-TEST_F(NonMutatingTest, Distance_OverloadedBeginEnd) {
- // Works with classes which have custom ADL-selected overloads of std::begin
- // and std::end.
- std::initializer_list<int> a = {1, 2, 3};
- std::valarray<int> b = {1, 2, 3};
- EXPECT_EQ(3, absl::c_distance(a));
- EXPECT_EQ(3, absl::c_distance(b));
-
- // It is assumed that other c_* functions use the same mechanism for
- // ADL-selecting begin/end overloads.
-}
-
-TEST_F(NonMutatingTest, ForEach) {
- AccumulateCalls c = absl::c_for_each(container_, AccumulateCalls());
- // Don't rely on the unordered_set's order.
- std::sort(c.calls.begin(), c.calls.end());
- EXPECT_EQ(vector_, c.calls);
-
- // Works with temporary container, too.
- AccumulateCalls c2 =
- absl::c_for_each(std::unordered_set<int>(container_), AccumulateCalls());
- std::sort(c2.calls.begin(), c2.calls.end());
- EXPECT_EQ(vector_, c2.calls);
-}
-
-TEST_F(NonMutatingTest, FindReturnsCorrectType) {
- auto it = absl::c_find(container_, 3);
- EXPECT_EQ(3, *it);
- absl::c_find(absl::implicit_cast<const std::list<int>&>(sequence_), 3);
-}
-
-TEST_F(NonMutatingTest, FindIf) { absl::c_find_if(container_, Predicate); }
-
-TEST_F(NonMutatingTest, FindIfNot) {
- absl::c_find_if_not(container_, Predicate);
-}
-
-TEST_F(NonMutatingTest, FindEnd) {
- absl::c_find_end(sequence_, vector_);
- absl::c_find_end(vector_, sequence_);
-}
-
-TEST_F(NonMutatingTest, FindEndWithPredicate) {
- absl::c_find_end(sequence_, vector_, BinPredicate);
- absl::c_find_end(vector_, sequence_, BinPredicate);
-}
-
-TEST_F(NonMutatingTest, FindFirstOf) {
- absl::c_find_first_of(container_, sequence_);
- absl::c_find_first_of(sequence_, container_);
-}
-
-TEST_F(NonMutatingTest, FindFirstOfWithPredicate) {
- absl::c_find_first_of(container_, sequence_, BinPredicate);
- absl::c_find_first_of(sequence_, container_, BinPredicate);
-}
-
-TEST_F(NonMutatingTest, AdjacentFind) { absl::c_adjacent_find(sequence_); }
-
-TEST_F(NonMutatingTest, AdjacentFindWithPredicate) {
- absl::c_adjacent_find(sequence_, BinPredicate);
-}
-
-TEST_F(NonMutatingTest, Count) { EXPECT_EQ(1, absl::c_count(container_, 3)); }
-
-TEST_F(NonMutatingTest, CountIf) {
- EXPECT_EQ(2, absl::c_count_if(container_, Predicate));
- const std::unordered_set<int>& const_container = container_;
- EXPECT_EQ(2, absl::c_count_if(const_container, Predicate));
-}
-
-TEST_F(NonMutatingTest, Mismatch) {
- // Testing necessary as absl::c_mismatch executes logic.
- {
- auto result = absl::c_mismatch(vector_, sequence_);
- EXPECT_EQ(result.first, vector_.end());
- EXPECT_EQ(result.second, sequence_.end());
- }
- {
- auto result = absl::c_mismatch(sequence_, vector_);
- EXPECT_EQ(result.first, sequence_.end());
- EXPECT_EQ(result.second, vector_.end());
- }
-
- sequence_.back() = 5;
- {
- auto result = absl::c_mismatch(vector_, sequence_);
- EXPECT_EQ(result.first, std::prev(vector_.end()));
- EXPECT_EQ(result.second, std::prev(sequence_.end()));
- }
- {
- auto result = absl::c_mismatch(sequence_, vector_);
- EXPECT_EQ(result.first, std::prev(sequence_.end()));
- EXPECT_EQ(result.second, std::prev(vector_.end()));
- }
-
- sequence_.pop_back();
- {
- auto result = absl::c_mismatch(vector_, sequence_);
- EXPECT_EQ(result.first, std::prev(vector_.end()));
- EXPECT_EQ(result.second, sequence_.end());
- }
- {
- auto result = absl::c_mismatch(sequence_, vector_);
- EXPECT_EQ(result.first, sequence_.end());
- EXPECT_EQ(result.second, std::prev(vector_.end()));
- }
- {
- struct NoNotEquals {
- constexpr bool operator==(NoNotEquals) const { return true; }
- constexpr bool operator!=(NoNotEquals) const = delete;
- };
- std::vector<NoNotEquals> first;
- std::list<NoNotEquals> second;
-
- // Check this still compiles.
- absl::c_mismatch(first, second);
- }
-}
-
-TEST_F(NonMutatingTest, MismatchWithPredicate) {
- // Testing necessary as absl::c_mismatch executes logic.
- {
- auto result = absl::c_mismatch(vector_, sequence_, BinPredicate);
- EXPECT_EQ(result.first, vector_.begin());
- EXPECT_EQ(result.second, sequence_.begin());
- }
- {
- auto result = absl::c_mismatch(sequence_, vector_, BinPredicate);
- EXPECT_EQ(result.first, sequence_.begin());
- EXPECT_EQ(result.second, vector_.begin());
- }
-
- sequence_.front() = 0;
- {
- auto result = absl::c_mismatch(vector_, sequence_, BinPredicate);
- EXPECT_EQ(result.first, vector_.begin());
- EXPECT_EQ(result.second, sequence_.begin());
- }
- {
- auto result = absl::c_mismatch(sequence_, vector_, BinPredicate);
- EXPECT_EQ(result.first, std::next(sequence_.begin()));
- EXPECT_EQ(result.second, std::next(vector_.begin()));
- }
-
- sequence_.clear();
- {
- auto result = absl::c_mismatch(vector_, sequence_, BinPredicate);
- EXPECT_EQ(result.first, vector_.begin());
- EXPECT_EQ(result.second, sequence_.end());
- }
- {
- auto result = absl::c_mismatch(sequence_, vector_, BinPredicate);
- EXPECT_EQ(result.first, sequence_.end());
- EXPECT_EQ(result.second, vector_.begin());
- }
-}
-
-TEST_F(NonMutatingTest, Equal) {
- EXPECT_TRUE(absl::c_equal(vector_, sequence_));
- EXPECT_TRUE(absl::c_equal(sequence_, vector_));
- EXPECT_TRUE(absl::c_equal(sequence_, array_));
- EXPECT_TRUE(absl::c_equal(array_, vector_));
-
- // Test that behavior appropriately differs from that of equal().
- std::vector<int> vector_plus = {1, 2, 3};
- vector_plus.push_back(4);
- EXPECT_FALSE(absl::c_equal(vector_plus, sequence_));
- EXPECT_FALSE(absl::c_equal(sequence_, vector_plus));
- EXPECT_FALSE(absl::c_equal(array_, vector_plus));
-}
-
-TEST_F(NonMutatingTest, EqualWithPredicate) {
- EXPECT_TRUE(absl::c_equal(vector_, sequence_, Equals));
- EXPECT_TRUE(absl::c_equal(sequence_, vector_, Equals));
- EXPECT_TRUE(absl::c_equal(array_, sequence_, Equals));
- EXPECT_TRUE(absl::c_equal(vector_, array_, Equals));
-
- // Test that behavior appropriately differs from that of equal().
- std::vector<int> vector_plus = {1, 2, 3};
- vector_plus.push_back(4);
- EXPECT_FALSE(absl::c_equal(vector_plus, sequence_, Equals));
- EXPECT_FALSE(absl::c_equal(sequence_, vector_plus, Equals));
- EXPECT_FALSE(absl::c_equal(vector_plus, array_, Equals));
-}
-
-TEST_F(NonMutatingTest, IsPermutation) {
- auto vector_permut_ = vector_;
- std::next_permutation(vector_permut_.begin(), vector_permut_.end());
- EXPECT_TRUE(absl::c_is_permutation(vector_permut_, sequence_));
- EXPECT_TRUE(absl::c_is_permutation(sequence_, vector_permut_));
-
- // Test that behavior appropriately differs from that of is_permutation().
- std::vector<int> vector_plus = {1, 2, 3};
- vector_plus.push_back(4);
- EXPECT_FALSE(absl::c_is_permutation(vector_plus, sequence_));
- EXPECT_FALSE(absl::c_is_permutation(sequence_, vector_plus));
-}
-
-TEST_F(NonMutatingTest, IsPermutationWithPredicate) {
- auto vector_permut_ = vector_;
- std::next_permutation(vector_permut_.begin(), vector_permut_.end());
- EXPECT_TRUE(absl::c_is_permutation(vector_permut_, sequence_, Equals));
- EXPECT_TRUE(absl::c_is_permutation(sequence_, vector_permut_, Equals));
-
- // Test that behavior appropriately differs from that of is_permutation().
- std::vector<int> vector_plus = {1, 2, 3};
- vector_plus.push_back(4);
- EXPECT_FALSE(absl::c_is_permutation(vector_plus, sequence_, Equals));
- EXPECT_FALSE(absl::c_is_permutation(sequence_, vector_plus, Equals));
-}
-
-TEST_F(NonMutatingTest, Search) {
- absl::c_search(sequence_, vector_);
- absl::c_search(vector_, sequence_);
- absl::c_search(array_, sequence_);
-}
-
-TEST_F(NonMutatingTest, SearchWithPredicate) {
- absl::c_search(sequence_, vector_, BinPredicate);
- absl::c_search(vector_, sequence_, BinPredicate);
-}
-
-TEST_F(NonMutatingTest, SearchN) { absl::c_search_n(sequence_, 3, 1); }
-
-TEST_F(NonMutatingTest, SearchNWithPredicate) {
- absl::c_search_n(sequence_, 3, 1, BinPredicate);
-}
-
-TEST_F(NonMutatingTest, LowerBound) {
- std::list<int>::iterator i = absl::c_lower_bound(sequence_, 3);
- ASSERT_TRUE(i != sequence_.end());
- EXPECT_EQ(2, std::distance(sequence_.begin(), i));
- EXPECT_EQ(3, *i);
-}
-
-TEST_F(NonMutatingTest, LowerBoundWithPredicate) {
- std::vector<int> v(vector_);
- std::sort(v.begin(), v.end(), std::greater<int>());
- std::vector<int>::iterator i = absl::c_lower_bound(v, 3, std::greater<int>());
- EXPECT_TRUE(i == v.begin());
- EXPECT_EQ(3, *i);
-}
-
-TEST_F(NonMutatingTest, UpperBound) {
- std::list<int>::iterator i = absl::c_upper_bound(sequence_, 1);
- ASSERT_TRUE(i != sequence_.end());
- EXPECT_EQ(1, std::distance(sequence_.begin(), i));
- EXPECT_EQ(2, *i);
-}
-
-TEST_F(NonMutatingTest, UpperBoundWithPredicate) {
- std::vector<int> v(vector_);
- std::sort(v.begin(), v.end(), std::greater<int>());
- std::vector<int>::iterator i = absl::c_upper_bound(v, 1, std::greater<int>());
- EXPECT_EQ(3, i - v.begin());
- EXPECT_TRUE(i == v.end());
-}
-
-TEST_F(NonMutatingTest, EqualRange) {
- std::pair<std::list<int>::iterator, std::list<int>::iterator> p =
- absl::c_equal_range(sequence_, 2);
- EXPECT_EQ(1, std::distance(sequence_.begin(), p.first));
- EXPECT_EQ(2, std::distance(sequence_.begin(), p.second));
-}
-
-TEST_F(NonMutatingTest, EqualRangeArray) {
- auto p = absl::c_equal_range(array_, 2);
- EXPECT_EQ(1, std::distance(std::begin(array_), p.first));
- EXPECT_EQ(2, std::distance(std::begin(array_), p.second));
-}
-
-TEST_F(NonMutatingTest, EqualRangeWithPredicate) {
- std::vector<int> v(vector_);
- std::sort(v.begin(), v.end(), std::greater<int>());
- std::pair<std::vector<int>::iterator, std::vector<int>::iterator> p =
- absl::c_equal_range(v, 2, std::greater<int>());
- EXPECT_EQ(1, std::distance(v.begin(), p.first));
- EXPECT_EQ(2, std::distance(v.begin(), p.second));
-}
-
-TEST_F(NonMutatingTest, BinarySearch) {
- EXPECT_TRUE(absl::c_binary_search(vector_, 2));
- EXPECT_TRUE(absl::c_binary_search(std::vector<int>(vector_), 2));
-}
-
-TEST_F(NonMutatingTest, BinarySearchWithPredicate) {
- std::vector<int> v(vector_);
- std::sort(v.begin(), v.end(), std::greater<int>());
- EXPECT_TRUE(absl::c_binary_search(v, 2, std::greater<int>()));
- EXPECT_TRUE(
- absl::c_binary_search(std::vector<int>(v), 2, std::greater<int>()));
-}
-
-TEST_F(NonMutatingTest, MinElement) {
- std::list<int>::iterator i = absl::c_min_element(sequence_);
- ASSERT_TRUE(i != sequence_.end());
- EXPECT_EQ(*i, 1);
-}
-
-TEST_F(NonMutatingTest, MinElementWithPredicate) {
- std::list<int>::iterator i =
- absl::c_min_element(sequence_, std::greater<int>());
- ASSERT_TRUE(i != sequence_.end());
- EXPECT_EQ(*i, 3);
-}
-
-TEST_F(NonMutatingTest, MaxElement) {
- std::list<int>::iterator i = absl::c_max_element(sequence_);
- ASSERT_TRUE(i != sequence_.end());
- EXPECT_EQ(*i, 3);
-}
-
-TEST_F(NonMutatingTest, MaxElementWithPredicate) {
- std::list<int>::iterator i =
- absl::c_max_element(sequence_, std::greater<int>());
- ASSERT_TRUE(i != sequence_.end());
- EXPECT_EQ(*i, 1);
-}
-
-TEST_F(NonMutatingTest, LexicographicalCompare) {
- EXPECT_FALSE(absl::c_lexicographical_compare(sequence_, sequence_));
-
- std::vector<int> v;
- v.push_back(1);
- v.push_back(2);
- v.push_back(4);
-
- EXPECT_TRUE(absl::c_lexicographical_compare(sequence_, v));
- EXPECT_TRUE(absl::c_lexicographical_compare(std::list<int>(sequence_), v));
-}
-
-TEST_F(NonMutatingTest, LexicographicalCopmareWithPredicate) {
- EXPECT_FALSE(absl::c_lexicographical_compare(sequence_, sequence_,
- std::greater<int>()));
-
- std::vector<int> v;
- v.push_back(1);
- v.push_back(2);
- v.push_back(4);
-
- EXPECT_TRUE(
- absl::c_lexicographical_compare(v, sequence_, std::greater<int>()));
- EXPECT_TRUE(absl::c_lexicographical_compare(
- std::vector<int>(v), std::list<int>(sequence_), std::greater<int>()));
-}
-
-TEST_F(NonMutatingTest, Includes) {
- std::set<int> s(vector_.begin(), vector_.end());
- s.insert(4);
- EXPECT_TRUE(absl::c_includes(s, vector_));
-}
-
-TEST_F(NonMutatingTest, IncludesWithPredicate) {
- std::vector<int> v = {3, 2, 1};
- std::set<int, std::greater<int>> s(v.begin(), v.end());
- s.insert(4);
- EXPECT_TRUE(absl::c_includes(s, v, std::greater<int>()));
-}
-
-class NumericMutatingTest : public testing::Test {
- protected:
- std::list<int> list_ = {1, 2, 3};
- std::vector<int> output_;
-};
-
-TEST_F(NumericMutatingTest, Iota) {
- absl::c_iota(list_, 5);
- std::list<int> expected{5, 6, 7};
- EXPECT_EQ(list_, expected);
-}
-
-TEST_F(NonMutatingTest, Accumulate) {
- EXPECT_EQ(absl::c_accumulate(sequence_, 4), 1 + 2 + 3 + 4);
-}
-
-TEST_F(NonMutatingTest, AccumulateWithBinaryOp) {
- EXPECT_EQ(absl::c_accumulate(sequence_, 4, std::multiplies<int>()),
- 1 * 2 * 3 * 4);
-}
-
-TEST_F(NonMutatingTest, AccumulateLvalueInit) {
- int lvalue = 4;
- EXPECT_EQ(absl::c_accumulate(sequence_, lvalue), 1 + 2 + 3 + 4);
-}
-
-TEST_F(NonMutatingTest, AccumulateWithBinaryOpLvalueInit) {
- int lvalue = 4;
- EXPECT_EQ(absl::c_accumulate(sequence_, lvalue, std::multiplies<int>()),
- 1 * 2 * 3 * 4);
-}
-
-TEST_F(NonMutatingTest, InnerProduct) {
- EXPECT_EQ(absl::c_inner_product(sequence_, vector_, 1000),
- 1000 + 1 * 1 + 2 * 2 + 3 * 3);
-}
-
-TEST_F(NonMutatingTest, InnerProductWithBinaryOps) {
- EXPECT_EQ(absl::c_inner_product(sequence_, vector_, 10,
- std::multiplies<int>(), std::plus<int>()),
- 10 * (1 + 1) * (2 + 2) * (3 + 3));
-}
-
-TEST_F(NonMutatingTest, InnerProductLvalueInit) {
- int lvalue = 1000;
- EXPECT_EQ(absl::c_inner_product(sequence_, vector_, lvalue),
- 1000 + 1 * 1 + 2 * 2 + 3 * 3);
-}
-
-TEST_F(NonMutatingTest, InnerProductWithBinaryOpsLvalueInit) {
- int lvalue = 10;
- EXPECT_EQ(absl::c_inner_product(sequence_, vector_, lvalue,
- std::multiplies<int>(), std::plus<int>()),
- 10 * (1 + 1) * (2 + 2) * (3 + 3));
-}
-
-TEST_F(NumericMutatingTest, AdjacentDifference) {
- auto last = absl::c_adjacent_difference(list_, std::back_inserter(output_));
- *last = 1000;
- std::vector<int> expected{1, 2 - 1, 3 - 2, 1000};
- EXPECT_EQ(output_, expected);
-}
-
-TEST_F(NumericMutatingTest, AdjacentDifferenceWithBinaryOp) {
- auto last = absl::c_adjacent_difference(list_, std::back_inserter(output_),
- std::multiplies<int>());
- *last = 1000;
- std::vector<int> expected{1, 2 * 1, 3 * 2, 1000};
- EXPECT_EQ(output_, expected);
-}
-
-TEST_F(NumericMutatingTest, PartialSum) {
- auto last = absl::c_partial_sum(list_, std::back_inserter(output_));
- *last = 1000;
- std::vector<int> expected{1, 1 + 2, 1 + 2 + 3, 1000};
- EXPECT_EQ(output_, expected);
-}
-
-TEST_F(NumericMutatingTest, PartialSumWithBinaryOp) {
- auto last = absl::c_partial_sum(list_, std::back_inserter(output_),
- std::multiplies<int>());
- *last = 1000;
- std::vector<int> expected{1, 1 * 2, 1 * 2 * 3, 1000};
- EXPECT_EQ(output_, expected);
-}
-
-TEST_F(NonMutatingTest, LinearSearch) {
- EXPECT_TRUE(absl::c_linear_search(container_, 3));
- EXPECT_FALSE(absl::c_linear_search(container_, 4));
-}
-
-TEST_F(NonMutatingTest, AllOf) {
- const std::vector<int>& v = vector_;
- EXPECT_FALSE(absl::c_all_of(v, [](int x) { return x > 1; }));
- EXPECT_TRUE(absl::c_all_of(v, [](int x) { return x > 0; }));
-}
-
-TEST_F(NonMutatingTest, AnyOf) {
- const std::vector<int>& v = vector_;
- EXPECT_TRUE(absl::c_any_of(v, [](int x) { return x > 2; }));
- EXPECT_FALSE(absl::c_any_of(v, [](int x) { return x > 5; }));
-}
-
-TEST_F(NonMutatingTest, NoneOf) {
- const std::vector<int>& v = vector_;
- EXPECT_FALSE(absl::c_none_of(v, [](int x) { return x > 2; }));
- EXPECT_TRUE(absl::c_none_of(v, [](int x) { return x > 5; }));
-}
-
-TEST_F(NonMutatingTest, MinMaxElementLess) {
- std::pair<std::vector<int>::const_iterator, std::vector<int>::const_iterator>
- p = absl::c_minmax_element(vector_, std::less<int>());
- EXPECT_TRUE(p.first == vector_.begin());
- EXPECT_TRUE(p.second == vector_.begin() + 2);
-}
-
-TEST_F(NonMutatingTest, MinMaxElementGreater) {
- std::pair<std::vector<int>::const_iterator, std::vector<int>::const_iterator>
- p = absl::c_minmax_element(vector_, std::greater<int>());
- EXPECT_TRUE(p.first == vector_.begin() + 2);
- EXPECT_TRUE(p.second == vector_.begin());
-}
-
-TEST_F(NonMutatingTest, MinMaxElementNoPredicate) {
- std::pair<std::vector<int>::const_iterator, std::vector<int>::const_iterator>
- p = absl::c_minmax_element(vector_);
- EXPECT_TRUE(p.first == vector_.begin());
- EXPECT_TRUE(p.second == vector_.begin() + 2);
-}
-
-class SortingTest : public testing::Test {
- protected:
- std::list<int> sorted_ = {1, 2, 3, 4};
- std::list<int> unsorted_ = {2, 4, 1, 3};
- std::list<int> reversed_ = {4, 3, 2, 1};
-};
-
-TEST_F(SortingTest, IsSorted) {
- EXPECT_TRUE(absl::c_is_sorted(sorted_));
- EXPECT_FALSE(absl::c_is_sorted(unsorted_));
- EXPECT_FALSE(absl::c_is_sorted(reversed_));
-}
-
-TEST_F(SortingTest, IsSortedWithPredicate) {
- EXPECT_FALSE(absl::c_is_sorted(sorted_, std::greater<int>()));
- EXPECT_FALSE(absl::c_is_sorted(unsorted_, std::greater<int>()));
- EXPECT_TRUE(absl::c_is_sorted(reversed_, std::greater<int>()));
-}
-
-TEST_F(SortingTest, IsSortedUntil) {
- EXPECT_EQ(1, *absl::c_is_sorted_until(unsorted_));
- EXPECT_EQ(4, *absl::c_is_sorted_until(unsorted_, std::greater<int>()));
-}
-
-TEST_F(SortingTest, NthElement) {
- std::vector<int> unsorted = {2, 4, 1, 3};
- absl::c_nth_element(unsorted, unsorted.begin() + 2);
- EXPECT_THAT(unsorted, ElementsAre(Lt(3), Lt(3), 3, Gt(3)));
- absl::c_nth_element(unsorted, unsorted.begin() + 2, std::greater<int>());
- EXPECT_THAT(unsorted, ElementsAre(Gt(2), Gt(2), 2, Lt(2)));
-}
-
-TEST(MutatingTest, IsPartitioned) {
- EXPECT_TRUE(
- absl::c_is_partitioned(std::vector<int>{1, 3, 5, 2, 4, 6}, IsOdd));
- EXPECT_FALSE(
- absl::c_is_partitioned(std::vector<int>{1, 2, 3, 4, 5, 6}, IsOdd));
- EXPECT_FALSE(
- absl::c_is_partitioned(std::vector<int>{2, 4, 6, 1, 3, 5}, IsOdd));
-}
-
-TEST(MutatingTest, Partition) {
- std::vector<int> actual = {1, 2, 3, 4, 5};
- absl::c_partition(actual, IsOdd);
- EXPECT_THAT(actual, Truly([](const std::vector<int>& c) {
- return absl::c_is_partitioned(c, IsOdd);
- }));
-}
-
-TEST(MutatingTest, StablePartition) {
- std::vector<int> actual = {1, 2, 3, 4, 5};
- absl::c_stable_partition(actual, IsOdd);
- EXPECT_THAT(actual, ElementsAre(1, 3, 5, 2, 4));
-}
-
-TEST(MutatingTest, PartitionCopy) {
- const std::vector<int> initial = {1, 2, 3, 4, 5};
- std::vector<int> odds, evens;
- auto ends = absl::c_partition_copy(initial, back_inserter(odds),
- back_inserter(evens), IsOdd);
- *ends.first = 7;
- *ends.second = 6;
- EXPECT_THAT(odds, ElementsAre(1, 3, 5, 7));
- EXPECT_THAT(evens, ElementsAre(2, 4, 6));
-}
-
-TEST(MutatingTest, PartitionPoint) {
- const std::vector<int> initial = {1, 3, 5, 2, 4};
- auto middle = absl::c_partition_point(initial, IsOdd);
- EXPECT_EQ(2, *middle);
-}
-
-TEST(MutatingTest, CopyMiddle) {
- const std::vector<int> initial = {4, -1, -2, -3, 5};
- const std::list<int> input = {1, 2, 3};
- const std::vector<int> expected = {4, 1, 2, 3, 5};
-
- std::list<int> test_list(initial.begin(), initial.end());
- absl::c_copy(input, ++test_list.begin());
- EXPECT_EQ(std::list<int>(expected.begin(), expected.end()), test_list);
-
- std::vector<int> test_vector = initial;
- absl::c_copy(input, test_vector.begin() + 1);
- EXPECT_EQ(expected, test_vector);
-}
-
-TEST(MutatingTest, CopyFrontInserter) {
- const std::list<int> initial = {4, 5};
- const std::list<int> input = {1, 2, 3};
- const std::list<int> expected = {3, 2, 1, 4, 5};
-
- std::list<int> test_list = initial;
- absl::c_copy(input, std::front_inserter(test_list));
- EXPECT_EQ(expected, test_list);
-}
-
-TEST(MutatingTest, CopyBackInserter) {
- const std::vector<int> initial = {4, 5};
- const std::list<int> input = {1, 2, 3};
- const std::vector<int> expected = {4, 5, 1, 2, 3};
-
- std::list<int> test_list(initial.begin(), initial.end());
- absl::c_copy(input, std::back_inserter(test_list));
- EXPECT_EQ(std::list<int>(expected.begin(), expected.end()), test_list);
-
- std::vector<int> test_vector = initial;
- absl::c_copy(input, std::back_inserter(test_vector));
- EXPECT_EQ(expected, test_vector);
-}
-
-TEST(MutatingTest, CopyN) {
- const std::vector<int> initial = {1, 2, 3, 4, 5};
- const std::vector<int> expected = {1, 2};
- std::vector<int> actual;
- absl::c_copy_n(initial, 2, back_inserter(actual));
- EXPECT_EQ(expected, actual);
-}
-
-TEST(MutatingTest, CopyIf) {
- const std::list<int> input = {1, 2, 3};
- std::vector<int> output;
- absl::c_copy_if(input, std::back_inserter(output),
- [](int i) { return i != 2; });
- EXPECT_THAT(output, ElementsAre(1, 3));
-}
-
-TEST(MutatingTest, CopyBackward) {
- std::vector<int> actual = {1, 2, 3, 4, 5};
- std::vector<int> expected = {1, 2, 1, 2, 3};
- absl::c_copy_backward(absl::MakeSpan(actual.data(), 3), actual.end());
- EXPECT_EQ(expected, actual);
-}
-
-TEST(MutatingTest, Move) {
- std::vector<std::unique_ptr<int>> src;
- src.emplace_back(absl::make_unique<int>(1));
- src.emplace_back(absl::make_unique<int>(2));
- src.emplace_back(absl::make_unique<int>(3));
- src.emplace_back(absl::make_unique<int>(4));
- src.emplace_back(absl::make_unique<int>(5));
-
- std::vector<std::unique_ptr<int>> dest = {};
- absl::c_move(src, std::back_inserter(dest));
- EXPECT_THAT(src, Each(IsNull()));
- EXPECT_THAT(dest, ElementsAre(Pointee(1), Pointee(2), Pointee(3), Pointee(4),
- Pointee(5)));
-}
-
-TEST(MutatingTest, MoveBackward) {
- std::vector<std::unique_ptr<int>> actual;
- actual.emplace_back(absl::make_unique<int>(1));
- actual.emplace_back(absl::make_unique<int>(2));
- actual.emplace_back(absl::make_unique<int>(3));
- actual.emplace_back(absl::make_unique<int>(4));
- actual.emplace_back(absl::make_unique<int>(5));
- auto subrange = absl::MakeSpan(actual.data(), 3);
- absl::c_move_backward(subrange, actual.end());
- EXPECT_THAT(actual, ElementsAre(IsNull(), IsNull(), Pointee(1), Pointee(2),
- Pointee(3)));
-}
-
-TEST(MutatingTest, MoveWithRvalue) {
- auto MakeRValueSrc = [] {
- std::vector<std::unique_ptr<int>> src;
- src.emplace_back(absl::make_unique<int>(1));
- src.emplace_back(absl::make_unique<int>(2));
- src.emplace_back(absl::make_unique<int>(3));
- return src;
- };
-
- std::vector<std::unique_ptr<int>> dest = MakeRValueSrc();
- absl::c_move(MakeRValueSrc(), std::back_inserter(dest));
- EXPECT_THAT(dest, ElementsAre(Pointee(1), Pointee(2), Pointee(3), Pointee(1),
- Pointee(2), Pointee(3)));
-}
-
-TEST(MutatingTest, SwapRanges) {
- std::vector<int> odds = {2, 4, 6};
- std::vector<int> evens = {1, 3, 5};
- absl::c_swap_ranges(odds, evens);
- EXPECT_THAT(odds, ElementsAre(1, 3, 5));
- EXPECT_THAT(evens, ElementsAre(2, 4, 6));
-
- odds.pop_back();
- absl::c_swap_ranges(odds, evens);
- EXPECT_THAT(odds, ElementsAre(2, 4));
- EXPECT_THAT(evens, ElementsAre(1, 3, 6));
-
- absl::c_swap_ranges(evens, odds);
- EXPECT_THAT(odds, ElementsAre(1, 3));
- EXPECT_THAT(evens, ElementsAre(2, 4, 6));
-}
-
-TEST_F(NonMutatingTest, Transform) {
- std::vector<int> x{0, 2, 4}, y, z;
- auto end = absl::c_transform(x, back_inserter(y), std::negate<int>());
- EXPECT_EQ(std::vector<int>({0, -2, -4}), y);
- *end = 7;
- EXPECT_EQ(std::vector<int>({0, -2, -4, 7}), y);
-
- y = {1, 3, 0};
- end = absl::c_transform(x, y, back_inserter(z), std::plus<int>());
- EXPECT_EQ(std::vector<int>({1, 5, 4}), z);
- *end = 7;
- EXPECT_EQ(std::vector<int>({1, 5, 4, 7}), z);
-
- z.clear();
- y.pop_back();
- end = absl::c_transform(x, y, std::back_inserter(z), std::plus<int>());
- EXPECT_EQ(std::vector<int>({1, 5}), z);
- *end = 7;
- EXPECT_EQ(std::vector<int>({1, 5, 7}), z);
-
- z.clear();
- std::swap(x, y);
- end = absl::c_transform(x, y, std::back_inserter(z), std::plus<int>());
- EXPECT_EQ(std::vector<int>({1, 5}), z);
- *end = 7;
- EXPECT_EQ(std::vector<int>({1, 5, 7}), z);
-}
-
-TEST(MutatingTest, Replace) {
- const std::vector<int> initial = {1, 2, 3, 1, 4, 5};
- const std::vector<int> expected = {4, 2, 3, 4, 4, 5};
-
- std::vector<int> test_vector = initial;
- absl::c_replace(test_vector, 1, 4);
- EXPECT_EQ(expected, test_vector);
-
- std::list<int> test_list(initial.begin(), initial.end());
- absl::c_replace(test_list, 1, 4);
- EXPECT_EQ(std::list<int>(expected.begin(), expected.end()), test_list);
-}
-
-TEST(MutatingTest, ReplaceIf) {
- std::vector<int> actual = {1, 2, 3, 4, 5};
- const std::vector<int> expected = {0, 2, 0, 4, 0};
-
- absl::c_replace_if(actual, IsOdd, 0);
- EXPECT_EQ(expected, actual);
-}
-
-TEST(MutatingTest, ReplaceCopy) {
- const std::vector<int> initial = {1, 2, 3, 1, 4, 5};
- const std::vector<int> expected = {4, 2, 3, 4, 4, 5};
-
- std::vector<int> actual;
- absl::c_replace_copy(initial, back_inserter(actual), 1, 4);
- EXPECT_EQ(expected, actual);
-}
-
-TEST(MutatingTest, Sort) {
- std::vector<int> test_vector = {2, 3, 1, 4};
- absl::c_sort(test_vector);
- EXPECT_THAT(test_vector, ElementsAre(1, 2, 3, 4));
-}
-
-TEST(MutatingTest, SortWithPredicate) {
- std::vector<int> test_vector = {2, 3, 1, 4};
- absl::c_sort(test_vector, std::greater<int>());
- EXPECT_THAT(test_vector, ElementsAre(4, 3, 2, 1));
-}
-
-// For absl::c_stable_sort tests. Needs an operator< that does not cover all
-// fields so that the test can check the sort preserves order of equal elements.
-struct Element {
- int key;
- int value;
- friend bool operator<(const Element& e1, const Element& e2) {
- return e1.key < e2.key;
- }
- // Make gmock print useful diagnostics.
- friend std::ostream& operator<<(std::ostream& o, const Element& e) {
- return o << "{" << e.key << ", " << e.value << "}";
- }
-};
-
-MATCHER_P2(IsElement, key, value, "") {
- return arg.key == key && arg.value == value;
-}
-
-TEST(MutatingTest, StableSort) {
- std::vector<Element> test_vector = {{1, 1}, {2, 1}, {2, 0}, {1, 0}, {2, 2}};
- absl::c_stable_sort(test_vector);
- EXPECT_THAT(test_vector,
- ElementsAre(IsElement(1, 1), IsElement(1, 0), IsElement(2, 1),
- IsElement(2, 0), IsElement(2, 2)));
-}
-
-TEST(MutatingTest, StableSortWithPredicate) {
- std::vector<Element> test_vector = {{1, 1}, {2, 1}, {2, 0}, {1, 0}, {2, 2}};
- absl::c_stable_sort(test_vector, [](const Element& e1, const Element& e2) {
- return e2 < e1;
- });
- EXPECT_THAT(test_vector,
- ElementsAre(IsElement(2, 1), IsElement(2, 0), IsElement(2, 2),
- IsElement(1, 1), IsElement(1, 0)));
-}
-
-TEST(MutatingTest, ReplaceCopyIf) {
- const std::vector<int> initial = {1, 2, 3, 4, 5};
- const std::vector<int> expected = {0, 2, 0, 4, 0};
-
- std::vector<int> actual;
- absl::c_replace_copy_if(initial, back_inserter(actual), IsOdd, 0);
- EXPECT_EQ(expected, actual);
-}
-
-TEST(MutatingTest, Fill) {
- std::vector<int> actual(5);
- absl::c_fill(actual, 1);
- EXPECT_THAT(actual, ElementsAre(1, 1, 1, 1, 1));
-}
-
-TEST(MutatingTest, FillN) {
- std::vector<int> actual(5, 0);
- absl::c_fill_n(actual, 2, 1);
- EXPECT_THAT(actual, ElementsAre(1, 1, 0, 0, 0));
-}
-
-TEST(MutatingTest, Generate) {
- std::vector<int> actual(5);
- int x = 0;
- absl::c_generate(actual, [&x]() { return ++x; });
- EXPECT_THAT(actual, ElementsAre(1, 2, 3, 4, 5));
-}
-
-TEST(MutatingTest, GenerateN) {
- std::vector<int> actual(5, 0);
- int x = 0;
- absl::c_generate_n(actual, 3, [&x]() { return ++x; });
- EXPECT_THAT(actual, ElementsAre(1, 2, 3, 0, 0));
-}
-
-TEST(MutatingTest, RemoveCopy) {
- std::vector<int> actual;
- absl::c_remove_copy(std::vector<int>{1, 2, 3}, back_inserter(actual), 2);
- EXPECT_THAT(actual, ElementsAre(1, 3));
-}
-
-TEST(MutatingTest, RemoveCopyIf) {
- std::vector<int> actual;
- absl::c_remove_copy_if(std::vector<int>{1, 2, 3}, back_inserter(actual),
- IsOdd);
- EXPECT_THAT(actual, ElementsAre(2));
-}
-
-TEST(MutatingTest, UniqueCopy) {
- std::vector<int> actual;
- absl::c_unique_copy(std::vector<int>{1, 2, 2, 2, 3, 3, 2},
- back_inserter(actual));
- EXPECT_THAT(actual, ElementsAre(1, 2, 3, 2));
-}
-
-TEST(MutatingTest, UniqueCopyWithPredicate) {
- std::vector<int> actual;
- absl::c_unique_copy(std::vector<int>{1, 2, 3, -1, -2, -3, 1},
- back_inserter(actual),
- [](int x, int y) { return (x < 0) == (y < 0); });
- EXPECT_THAT(actual, ElementsAre(1, -1, 1));
-}
-
-TEST(MutatingTest, Reverse) {
- std::vector<int> test_vector = {1, 2, 3, 4};
- absl::c_reverse(test_vector);
- EXPECT_THAT(test_vector, ElementsAre(4, 3, 2, 1));
-
- std::list<int> test_list = {1, 2, 3, 4};
- absl::c_reverse(test_list);
- EXPECT_THAT(test_list, ElementsAre(4, 3, 2, 1));
-}
-
-TEST(MutatingTest, ReverseCopy) {
- std::vector<int> actual;
- absl::c_reverse_copy(std::vector<int>{1, 2, 3, 4}, back_inserter(actual));
- EXPECT_THAT(actual, ElementsAre(4, 3, 2, 1));
-}
-
-TEST(MutatingTest, Rotate) {
- std::vector<int> actual = {1, 2, 3, 4};
- auto it = absl::c_rotate(actual, actual.begin() + 2);
- EXPECT_THAT(actual, testing::ElementsAreArray({3, 4, 1, 2}));
- EXPECT_EQ(*it, 1);
-}
-
-TEST(MutatingTest, RotateCopy) {
- std::vector<int> initial = {1, 2, 3, 4};
- std::vector<int> actual;
- auto end =
- absl::c_rotate_copy(initial, initial.begin() + 2, back_inserter(actual));
- *end = 5;
- EXPECT_THAT(actual, ElementsAre(3, 4, 1, 2, 5));
-}
-
-TEST(MutatingTest, Shuffle) {
- std::vector<int> actual = {1, 2, 3, 4, 5};
- absl::c_shuffle(actual, std::random_device());
- EXPECT_THAT(actual, UnorderedElementsAre(1, 2, 3, 4, 5));
-}
-
-TEST(MutatingTest, PartialSort) {
- std::vector<int> sequence{5, 3, 42, 0};
- absl::c_partial_sort(sequence, sequence.begin() + 2);
- EXPECT_THAT(absl::MakeSpan(sequence.data(), 2), ElementsAre(0, 3));
- absl::c_partial_sort(sequence, sequence.begin() + 2, std::greater<int>());
- EXPECT_THAT(absl::MakeSpan(sequence.data(), 2), ElementsAre(42, 5));
-}
-
-TEST(MutatingTest, PartialSortCopy) {
- const std::vector<int> initial = {5, 3, 42, 0};
- std::vector<int> actual(2);
- absl::c_partial_sort_copy(initial, actual);
- EXPECT_THAT(actual, ElementsAre(0, 3));
- absl::c_partial_sort_copy(initial, actual, std::greater<int>());
- EXPECT_THAT(actual, ElementsAre(42, 5));
-}
-
-TEST(MutatingTest, Merge) {
- std::vector<int> actual;
- absl::c_merge(std::vector<int>{1, 3, 5}, std::vector<int>{2, 4},
- back_inserter(actual));
- EXPECT_THAT(actual, ElementsAre(1, 2, 3, 4, 5));
-}
-
-TEST(MutatingTest, MergeWithComparator) {
- std::vector<int> actual;
- absl::c_merge(std::vector<int>{5, 3, 1}, std::vector<int>{4, 2},
- back_inserter(actual), std::greater<int>());
- EXPECT_THAT(actual, ElementsAre(5, 4, 3, 2, 1));
-}
-
-TEST(MutatingTest, InplaceMerge) {
- std::vector<int> actual = {1, 3, 5, 2, 4};
- absl::c_inplace_merge(actual, actual.begin() + 3);
- EXPECT_THAT(actual, ElementsAre(1, 2, 3, 4, 5));
-}
-
-TEST(MutatingTest, InplaceMergeWithComparator) {
- std::vector<int> actual = {5, 3, 1, 4, 2};
- absl::c_inplace_merge(actual, actual.begin() + 3, std::greater<int>());
- EXPECT_THAT(actual, ElementsAre(5, 4, 3, 2, 1));
-}
-
-class SetOperationsTest : public testing::Test {
- protected:
- std::vector<int> a_ = {1, 2, 3};
- std::vector<int> b_ = {1, 3, 5};
-
- std::vector<int> a_reversed_ = {3, 2, 1};
- std::vector<int> b_reversed_ = {5, 3, 1};
-};
-
-TEST_F(SetOperationsTest, SetUnion) {
- std::vector<int> actual;
- absl::c_set_union(a_, b_, back_inserter(actual));
- EXPECT_THAT(actual, ElementsAre(1, 2, 3, 5));
-}
-
-TEST_F(SetOperationsTest, SetUnionWithComparator) {
- std::vector<int> actual;
- absl::c_set_union(a_reversed_, b_reversed_, back_inserter(actual),
- std::greater<int>());
- EXPECT_THAT(actual, ElementsAre(5, 3, 2, 1));
-}
-
-TEST_F(SetOperationsTest, SetIntersection) {
- std::vector<int> actual;
- absl::c_set_intersection(a_, b_, back_inserter(actual));
- EXPECT_THAT(actual, ElementsAre(1, 3));
-}
-
-TEST_F(SetOperationsTest, SetIntersectionWithComparator) {
- std::vector<int> actual;
- absl::c_set_intersection(a_reversed_, b_reversed_, back_inserter(actual),
- std::greater<int>());
- EXPECT_THAT(actual, ElementsAre(3, 1));
-}
-
-TEST_F(SetOperationsTest, SetDifference) {
- std::vector<int> actual;
- absl::c_set_difference(a_, b_, back_inserter(actual));
- EXPECT_THAT(actual, ElementsAre(2));
-}
-
-TEST_F(SetOperationsTest, SetDifferenceWithComparator) {
- std::vector<int> actual;
- absl::c_set_difference(a_reversed_, b_reversed_, back_inserter(actual),
- std::greater<int>());
- EXPECT_THAT(actual, ElementsAre(2));
-}
-
-TEST_F(SetOperationsTest, SetSymmetricDifference) {
- std::vector<int> actual;
- absl::c_set_symmetric_difference(a_, b_, back_inserter(actual));
- EXPECT_THAT(actual, ElementsAre(2, 5));
-}
-
-TEST_F(SetOperationsTest, SetSymmetricDifferenceWithComparator) {
- std::vector<int> actual;
- absl::c_set_symmetric_difference(a_reversed_, b_reversed_,
- back_inserter(actual), std::greater<int>());
- EXPECT_THAT(actual, ElementsAre(5, 2));
-}
-
-TEST(HeapOperationsTest, WithoutComparator) {
- std::vector<int> heap = {1, 2, 3};
- EXPECT_FALSE(absl::c_is_heap(heap));
- absl::c_make_heap(heap);
- EXPECT_TRUE(absl::c_is_heap(heap));
- heap.push_back(4);
- EXPECT_EQ(3, absl::c_is_heap_until(heap) - heap.begin());
- absl::c_push_heap(heap);
- EXPECT_EQ(4, heap[0]);
- absl::c_pop_heap(heap);
- EXPECT_EQ(4, heap[3]);
- absl::c_make_heap(heap);
- absl::c_sort_heap(heap);
- EXPECT_THAT(heap, ElementsAre(1, 2, 3, 4));
- EXPECT_FALSE(absl::c_is_heap(heap));
-}
-
-TEST(HeapOperationsTest, WithComparator) {
- using greater = std::greater<int>;
- std::vector<int> heap = {3, 2, 1};
- EXPECT_FALSE(absl::c_is_heap(heap, greater()));
- absl::c_make_heap(heap, greater());
- EXPECT_TRUE(absl::c_is_heap(heap, greater()));
- heap.push_back(0);
- EXPECT_EQ(3, absl::c_is_heap_until(heap, greater()) - heap.begin());
- absl::c_push_heap(heap, greater());
- EXPECT_EQ(0, heap[0]);
- absl::c_pop_heap(heap, greater());
- EXPECT_EQ(0, heap[3]);
- absl::c_make_heap(heap, greater());
- absl::c_sort_heap(heap, greater());
- EXPECT_THAT(heap, ElementsAre(3, 2, 1, 0));
- EXPECT_FALSE(absl::c_is_heap(heap, greater()));
-}
-
-TEST(MutatingTest, PermutationOperations) {
- std::vector<int> initial = {1, 2, 3, 4};
- std::vector<int> permuted = initial;
-
- absl::c_next_permutation(permuted);
- EXPECT_TRUE(absl::c_is_permutation(initial, permuted));
- EXPECT_TRUE(absl::c_is_permutation(initial, permuted, std::equal_to<int>()));
-
- std::vector<int> permuted2 = initial;
- absl::c_prev_permutation(permuted2, std::greater<int>());
- EXPECT_EQ(permuted, permuted2);
-
- absl::c_prev_permutation(permuted);
- EXPECT_EQ(initial, permuted);
-}
-
-} // namespace
diff --git a/third_party/abseil-cpp/absl/algorithm/equal_benchmark.cc b/third_party/abseil-cpp/absl/algorithm/equal_benchmark.cc
deleted file mode 100644
index 948cd65..0000000
--- a/third_party/abseil-cpp/absl/algorithm/equal_benchmark.cc
+++ /dev/null
@@ -1,126 +0,0 @@
-// Copyright 2017 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 <cstdint>
-#include <cstring>
-
-#include "absl/algorithm/algorithm.h"
-#include "benchmark/benchmark.h"
-
-namespace {
-
-// The range of sequence sizes to benchmark.
-constexpr int kMinBenchmarkSize = 1024;
-constexpr int kMaxBenchmarkSize = 8 * 1024 * 1024;
-
-// A user-defined type for use in equality benchmarks. Note that we expect
-// std::memcmp to win for this type: libstdc++'s std::equal only defers to
-// memcmp for integral types. This is because it is not straightforward to
-// guarantee that std::memcmp would produce a result "as-if" compared by
-// operator== for other types (example gotchas: NaN floats, structs with
-// padding).
-struct EightBits {
- explicit EightBits(int /* unused */) : data(0) {}
- bool operator==(const EightBits& rhs) const { return data == rhs.data; }
- uint8_t data;
-};
-
-template <typename T>
-void BM_absl_equal_benchmark(benchmark::State& state) {
- std::vector<T> xs(state.range(0), T(0));
- std::vector<T> ys = xs;
- while (state.KeepRunning()) {
- const bool same = absl::equal(xs.begin(), xs.end(), ys.begin(), ys.end());
- benchmark::DoNotOptimize(same);
- }
-}
-
-template <typename T>
-void BM_std_equal_benchmark(benchmark::State& state) {
- std::vector<T> xs(state.range(0), T(0));
- std::vector<T> ys = xs;
- while (state.KeepRunning()) {
- const bool same = std::equal(xs.begin(), xs.end(), ys.begin());
- benchmark::DoNotOptimize(same);
- }
-}
-
-template <typename T>
-void BM_memcmp_benchmark(benchmark::State& state) {
- std::vector<T> xs(state.range(0), T(0));
- std::vector<T> ys = xs;
- while (state.KeepRunning()) {
- const bool same =
- std::memcmp(xs.data(), ys.data(), xs.size() * sizeof(T)) == 0;
- benchmark::DoNotOptimize(same);
- }
-}
-
-// The expectation is that the compiler should be able to elide the equality
-// comparison altogether for sufficiently simple types.
-template <typename T>
-void BM_absl_equal_self_benchmark(benchmark::State& state) {
- std::vector<T> xs(state.range(0), T(0));
- while (state.KeepRunning()) {
- const bool same = absl::equal(xs.begin(), xs.end(), xs.begin(), xs.end());
- benchmark::DoNotOptimize(same);
- }
-}
-
-BENCHMARK_TEMPLATE(BM_absl_equal_benchmark, uint8_t)
- ->Range(kMinBenchmarkSize, kMaxBenchmarkSize);
-BENCHMARK_TEMPLATE(BM_std_equal_benchmark, uint8_t)
- ->Range(kMinBenchmarkSize, kMaxBenchmarkSize);
-BENCHMARK_TEMPLATE(BM_memcmp_benchmark, uint8_t)
- ->Range(kMinBenchmarkSize, kMaxBenchmarkSize);
-BENCHMARK_TEMPLATE(BM_absl_equal_self_benchmark, uint8_t)
- ->Range(kMinBenchmarkSize, kMaxBenchmarkSize);
-
-BENCHMARK_TEMPLATE(BM_absl_equal_benchmark, uint16_t)
- ->Range(kMinBenchmarkSize, kMaxBenchmarkSize);
-BENCHMARK_TEMPLATE(BM_std_equal_benchmark, uint16_t)
- ->Range(kMinBenchmarkSize, kMaxBenchmarkSize);
-BENCHMARK_TEMPLATE(BM_memcmp_benchmark, uint16_t)
- ->Range(kMinBenchmarkSize, kMaxBenchmarkSize);
-BENCHMARK_TEMPLATE(BM_absl_equal_self_benchmark, uint16_t)
- ->Range(kMinBenchmarkSize, kMaxBenchmarkSize);
-
-BENCHMARK_TEMPLATE(BM_absl_equal_benchmark, uint32_t)
- ->Range(kMinBenchmarkSize, kMaxBenchmarkSize);
-BENCHMARK_TEMPLATE(BM_std_equal_benchmark, uint32_t)
- ->Range(kMinBenchmarkSize, kMaxBenchmarkSize);
-BENCHMARK_TEMPLATE(BM_memcmp_benchmark, uint32_t)
- ->Range(kMinBenchmarkSize, kMaxBenchmarkSize);
-BENCHMARK_TEMPLATE(BM_absl_equal_self_benchmark, uint32_t)
- ->Range(kMinBenchmarkSize, kMaxBenchmarkSize);
-
-BENCHMARK_TEMPLATE(BM_absl_equal_benchmark, uint64_t)
- ->Range(kMinBenchmarkSize, kMaxBenchmarkSize);
-BENCHMARK_TEMPLATE(BM_std_equal_benchmark, uint64_t)
- ->Range(kMinBenchmarkSize, kMaxBenchmarkSize);
-BENCHMARK_TEMPLATE(BM_memcmp_benchmark, uint64_t)
- ->Range(kMinBenchmarkSize, kMaxBenchmarkSize);
-BENCHMARK_TEMPLATE(BM_absl_equal_self_benchmark, uint64_t)
- ->Range(kMinBenchmarkSize, kMaxBenchmarkSize);
-
-BENCHMARK_TEMPLATE(BM_absl_equal_benchmark, EightBits)
- ->Range(kMinBenchmarkSize, kMaxBenchmarkSize);
-BENCHMARK_TEMPLATE(BM_std_equal_benchmark, EightBits)
- ->Range(kMinBenchmarkSize, kMaxBenchmarkSize);
-BENCHMARK_TEMPLATE(BM_memcmp_benchmark, EightBits)
- ->Range(kMinBenchmarkSize, kMaxBenchmarkSize);
-BENCHMARK_TEMPLATE(BM_absl_equal_self_benchmark, EightBits)
- ->Range(kMinBenchmarkSize, kMaxBenchmarkSize);
-
-} // namespace
diff --git a/third_party/abseil-cpp/absl/base/BUILD.bazel b/third_party/abseil-cpp/absl/base/BUILD.bazel
deleted file mode 100644
index c01765f..0000000
--- a/third_party/abseil-cpp/absl/base/BUILD.bazel
+++ /dev/null
@@ -1,777 +0,0 @@
-#
-# Copyright 2017 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.
-#
-
-load(
- "//absl:copts/configure_copts.bzl",
- "ABSL_DEFAULT_COPTS",
- "ABSL_DEFAULT_LINKOPTS",
- "ABSL_TEST_COPTS",
-)
-
-package(default_visibility = ["//visibility:public"])
-
-licenses(["notice"])
-
-cc_library(
- name = "atomic_hook",
- hdrs = ["internal/atomic_hook.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- visibility = [
- "//absl:__subpackages__",
- ],
- deps = [
- ":config",
- ":core_headers",
- ],
-)
-
-cc_library(
- name = "errno_saver",
- hdrs = ["internal/errno_saver.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- visibility = [
- "//absl:__subpackages__",
- ],
- deps = [":config"],
-)
-
-cc_library(
- name = "log_severity",
- srcs = ["log_severity.cc"],
- hdrs = ["log_severity.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":config",
- ":core_headers",
- ],
-)
-
-cc_library(
- name = "raw_logging_internal",
- srcs = ["internal/raw_logging.cc"],
- hdrs = ["internal/raw_logging.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- visibility = [
- "//absl:__subpackages__",
- ],
- deps = [
- ":atomic_hook",
- ":config",
- ":core_headers",
- ":errno_saver",
- ":log_severity",
- ],
-)
-
-cc_library(
- name = "spinlock_wait",
- srcs = [
- "internal/spinlock_akaros.inc",
- "internal/spinlock_linux.inc",
- "internal/spinlock_posix.inc",
- "internal/spinlock_wait.cc",
- "internal/spinlock_win32.inc",
- ],
- hdrs = ["internal/spinlock_wait.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- visibility = [
- "//absl/base:__pkg__",
- ],
- deps = [
- ":base_internal",
- ":core_headers",
- ":errno_saver",
- ],
-)
-
-cc_library(
- name = "config",
- hdrs = [
- "config.h",
- "options.h",
- "policy_checks.h",
- ],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
-)
-
-cc_library(
- name = "cycleclock_internal",
- hdrs = [
- "internal/cycleclock_config.h",
- "internal/unscaledcycleclock_config.h",
- ],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- visibility = [
- "//absl:__subpackages__",
- ],
- deps = [
- ":base_internal",
- ":config",
- ],
-)
-
-cc_library(
- name = "dynamic_annotations",
- hdrs = [
- "dynamic_annotations.h",
- ],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":config",
- ":core_headers",
- ],
-)
-
-cc_library(
- name = "core_headers",
- hdrs = [
- "attributes.h",
- "const_init.h",
- "macros.h",
- "optimization.h",
- "port.h",
- "thread_annotations.h",
- ],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":config",
- ],
-)
-
-cc_library(
- name = "malloc_internal",
- srcs = [
- "internal/low_level_alloc.cc",
- ],
- hdrs = [
- "internal/direct_mmap.h",
- "internal/low_level_alloc.h",
- ],
- copts = ABSL_DEFAULT_COPTS + select({
- "//conditions:default": [],
- }),
- linkopts = select({
- "//absl:msvc_compiler": [],
- "//absl:clang-cl_compiler": [],
- "//absl:wasm": [],
- "//conditions:default": ["-pthread"],
- }) + ABSL_DEFAULT_LINKOPTS,
- visibility = [
- "//visibility:public",
- ],
- deps = [
- ":base",
- ":base_internal",
- ":config",
- ":core_headers",
- ":dynamic_annotations",
- ":raw_logging_internal",
- ],
-)
-
-cc_library(
- name = "base_internal",
- hdrs = [
- "internal/hide_ptr.h",
- "internal/identity.h",
- "internal/inline_variable.h",
- "internal/invoke.h",
- "internal/scheduling_mode.h",
- ],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- visibility = [
- "//absl:__subpackages__",
- ],
- deps = [
- ":config",
- "//absl/meta:type_traits",
- ],
-)
-
-cc_library(
- name = "base",
- srcs = [
- "internal/cycleclock.cc",
- "internal/spinlock.cc",
- "internal/sysinfo.cc",
- "internal/thread_identity.cc",
- "internal/unscaledcycleclock.cc",
- ],
- hdrs = [
- "call_once.h",
- "casts.h",
- "internal/cycleclock.h",
- "internal/low_level_scheduling.h",
- "internal/per_thread_tls.h",
- "internal/spinlock.h",
- "internal/sysinfo.h",
- "internal/thread_identity.h",
- "internal/tsan_mutex_interface.h",
- "internal/unscaledcycleclock.h",
- ],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = select({
- "//absl:msvc_compiler": [
- "-DEFAULTLIB:advapi32.lib",
- ],
- "//absl:clang-cl_compiler": [
- "-DEFAULTLIB:advapi32.lib",
- ],
- "//absl:wasm": [],
- "//conditions:default": ["-pthread"],
- }) + ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":atomic_hook",
- ":base_internal",
- ":config",
- ":core_headers",
- ":cycleclock_internal",
- ":dynamic_annotations",
- ":log_severity",
- ":raw_logging_internal",
- ":spinlock_wait",
- "//absl/meta:type_traits",
- ],
-)
-
-cc_library(
- name = "atomic_hook_test_helper",
- testonly = 1,
- srcs = ["internal/atomic_hook_test_helper.cc"],
- hdrs = ["internal/atomic_hook_test_helper.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":atomic_hook",
- ":core_headers",
- ],
-)
-
-cc_test(
- name = "atomic_hook_test",
- size = "small",
- srcs = ["internal/atomic_hook_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":atomic_hook",
- ":atomic_hook_test_helper",
- ":core_headers",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_test(
- name = "bit_cast_test",
- size = "small",
- srcs = [
- "bit_cast_test.cc",
- ],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":base",
- ":core_headers",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_library(
- name = "throw_delegate",
- srcs = ["internal/throw_delegate.cc"],
- hdrs = ["internal/throw_delegate.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- visibility = [
- "//absl:__subpackages__",
- ],
- deps = [
- ":config",
- ":raw_logging_internal",
- ],
-)
-
-cc_test(
- name = "throw_delegate_test",
- srcs = ["throw_delegate_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":config",
- ":throw_delegate",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_test(
- name = "errno_saver_test",
- size = "small",
- srcs = ["internal/errno_saver_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":errno_saver",
- ":strerror",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_library(
- name = "exception_testing",
- testonly = 1,
- hdrs = ["internal/exception_testing.h"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- visibility = [
- "//absl:__subpackages__",
- ],
- deps = [
- ":config",
- "@com_google_googletest//:gtest",
- ],
-)
-
-cc_library(
- name = "pretty_function",
- hdrs = ["internal/pretty_function.h"],
- linkopts = ABSL_DEFAULT_LINKOPTS,
- visibility = ["//absl:__subpackages__"],
-)
-
-cc_library(
- name = "exception_safety_testing",
- testonly = 1,
- srcs = ["internal/exception_safety_testing.cc"],
- hdrs = ["internal/exception_safety_testing.h"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":config",
- ":pretty_function",
- "//absl/memory",
- "//absl/meta:type_traits",
- "//absl/strings",
- "//absl/utility",
- "@com_google_googletest//:gtest",
- ],
-)
-
-cc_test(
- name = "exception_safety_testing_test",
- srcs = ["exception_safety_testing_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":exception_safety_testing",
- "//absl/memory",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_test(
- name = "inline_variable_test",
- size = "small",
- srcs = [
- "inline_variable_test.cc",
- "inline_variable_test_a.cc",
- "inline_variable_test_b.cc",
- "internal/inline_variable_testing.h",
- ],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":base_internal",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_test(
- name = "invoke_test",
- size = "small",
- srcs = ["invoke_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":base_internal",
- "//absl/memory",
- "//absl/strings",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-# Common test library made available for use in non-absl code that overrides
-# AbslInternalSpinLockDelay and AbslInternalSpinLockWake.
-cc_library(
- name = "spinlock_test_common",
- testonly = 1,
- srcs = ["spinlock_test_common.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":base",
- ":base_internal",
- ":config",
- ":core_headers",
- "//absl/synchronization",
- "@com_google_googletest//:gtest",
- ],
- alwayslink = 1,
-)
-
-cc_test(
- name = "spinlock_test",
- size = "medium",
- srcs = ["spinlock_test_common.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- tags = [
- "no_test_wasm",
- ],
- deps = [
- ":base",
- ":base_internal",
- ":config",
- ":core_headers",
- "//absl/synchronization",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_library(
- name = "spinlock_benchmark_common",
- testonly = 1,
- srcs = ["internal/spinlock_benchmark.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- visibility = [
- "//absl/base:__pkg__",
- ],
- deps = [
- ":base",
- ":base_internal",
- ":raw_logging_internal",
- "//absl/synchronization",
- "@com_github_google_benchmark//:benchmark_main",
- ],
- alwayslink = 1,
-)
-
-cc_binary(
- name = "spinlock_benchmark",
- testonly = 1,
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- tags = ["benchmark"],
- visibility = ["//visibility:private"],
- deps = [
- ":spinlock_benchmark_common",
- ],
-)
-
-cc_library(
- name = "endian",
- hdrs = [
- "internal/endian.h",
- "internal/unaligned_access.h",
- ],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":base",
- ":config",
- ":core_headers",
- ],
-)
-
-cc_test(
- name = "endian_test",
- srcs = ["internal/endian_test.cc"],
- copts = ABSL_TEST_COPTS,
- deps = [
- ":config",
- ":endian",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_test(
- name = "config_test",
- srcs = ["config_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":config",
- "//absl/synchronization:thread_pool",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_test(
- name = "call_once_test",
- srcs = ["call_once_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":base",
- ":core_headers",
- "//absl/synchronization",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_test(
- name = "raw_logging_test",
- srcs = ["raw_logging_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":raw_logging_internal",
- "//absl/strings",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_test(
- name = "sysinfo_test",
- size = "small",
- srcs = ["internal/sysinfo_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":base",
- "//absl/synchronization",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_test(
- name = "low_level_alloc_test",
- size = "medium",
- srcs = ["internal/low_level_alloc_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- tags = [
- "no_test_ios_x86_64",
- "no_test_wasm",
- ],
- deps = [
- ":malloc_internal",
- "//absl/container:node_hash_map",
- ],
-)
-
-cc_test(
- name = "thread_identity_test",
- size = "small",
- srcs = ["internal/thread_identity_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- tags = [
- "no_test_wasm",
- ],
- deps = [
- ":base",
- ":core_headers",
- "//absl/synchronization",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_test(
- name = "thread_identity_benchmark",
- srcs = ["internal/thread_identity_benchmark.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- tags = ["benchmark"],
- visibility = ["//visibility:private"],
- deps = [
- ":base",
- "//absl/synchronization",
- "@com_github_google_benchmark//:benchmark_main",
- ],
-)
-
-cc_library(
- name = "scoped_set_env",
- testonly = 1,
- srcs = ["internal/scoped_set_env.cc"],
- hdrs = ["internal/scoped_set_env.h"],
- linkopts = ABSL_DEFAULT_LINKOPTS,
- visibility = [
- "//absl:__subpackages__",
- ],
- deps = [
- ":config",
- ":raw_logging_internal",
- ],
-)
-
-cc_test(
- name = "scoped_set_env_test",
- size = "small",
- srcs = ["internal/scoped_set_env_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":scoped_set_env",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_test(
- name = "log_severity_test",
- size = "small",
- srcs = ["log_severity_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":log_severity",
- "//absl/flags:flag_internal",
- "//absl/flags:marshalling",
- "//absl/strings",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_library(
- name = "strerror",
- srcs = ["internal/strerror.cc"],
- hdrs = ["internal/strerror.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- visibility = [
- "//absl:__subpackages__",
- ],
- deps = [
- ":config",
- ":core_headers",
- ":errno_saver",
- ],
-)
-
-cc_test(
- name = "strerror_test",
- size = "small",
- srcs = ["internal/strerror_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":strerror",
- "//absl/strings",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_binary(
- name = "strerror_benchmark",
- testonly = 1,
- srcs = ["internal/strerror_benchmark.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- tags = ["benchmark"],
- visibility = ["//visibility:private"],
- deps = [
- ":strerror",
- "@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",
- ],
-)
-
-cc_library(
- name = "prefetch",
- hdrs = ["internal/prefetch.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- visibility = [
- "//absl:__subpackages__",
- ],
- deps = [
- ":config",
- ],
-)
-
-cc_test(
- name = "prefetch_test",
- size = "small",
- srcs = ["internal/prefetch_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":prefetch",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_test(
- name = "unique_small_name_test",
- size = "small",
- srcs = ["internal/unique_small_name_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- linkstatic = 1,
- deps = [
- ":core_headers",
- "//absl/strings",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_test(
- name = "optimization_test",
- size = "small",
- srcs = ["optimization_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":core_headers",
- "//absl/types:optional",
- "@com_google_googletest//:gtest_main",
- ],
-)
diff --git a/third_party/abseil-cpp/absl/base/BUILD.gn b/third_party/abseil-cpp/absl/base/BUILD.gn
deleted file mode 100644
index d6cca68..0000000
--- a/third_party/abseil-cpp/absl/base/BUILD.gn
+++ /dev/null
@@ -1,291 +0,0 @@
-# Copyright 2018 The Chromium Authors
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-import("//third_party/abseil-cpp/absl.gni")
-
-absl_source_set("atomic_hook") {
- public = [ "internal/atomic_hook.h" ]
- public_deps = [
- ":config",
- ":core_headers",
- ]
- visibility = [ "//third_party/abseil-cpp/absl/*" ]
-}
-
-absl_source_set("errno_saver") {
- public = [ "internal/errno_saver.h" ]
- public_deps = [ ":config" ]
- visibility = [ "//third_party/abseil-cpp/absl/*" ]
-}
-
-absl_source_set("log_severity") {
- sources = [ "log_severity.cc" ]
- public = [ "log_severity.h" ]
- public_deps = [
- ":config",
- ":core_headers",
- ]
-}
-
-absl_source_set("raw_logging_internal") {
- sources = [ "internal/raw_logging.cc" ]
- public = [ "internal/raw_logging.h" ]
- public_deps = [
- ":atomic_hook",
- ":config",
- ":core_headers",
- ":errno_saver",
- ":log_severity",
- ]
- visibility = [ "//third_party/abseil-cpp/absl/*" ]
-}
-
-absl_source_set("spinlock_wait") {
- sources = [
- "internal/spinlock_akaros.inc",
- "internal/spinlock_linux.inc",
- "internal/spinlock_posix.inc",
- "internal/spinlock_wait.cc",
- "internal/spinlock_win32.inc",
- ]
- public = [ "internal/spinlock_wait.h" ]
- deps = [
- ":base_internal",
- ":core_headers",
- ":errno_saver",
- ]
- visibility = [ "//third_party/abseil-cpp/absl/base:*" ]
-}
-
-absl_source_set("config") {
- public = [
- "config.h",
- "options.h",
- "policy_checks.h",
- ]
-}
-
-absl_source_set("cycleclock_internal") {
- public = [
- "internal/cycleclock_config.h",
- "internal/unscaledcycleclock_config.h",
- ]
- visibility = [ "//third_party/abseil-cpp/absl/*" ]
- deps = [
- ":base_internal",
- ":config",
- ]
-}
-
-absl_source_set("dynamic_annotations") {
- public = [ "dynamic_annotations.h" ]
-
- # Abseil's dynamic annotations are only visible inside Abseil because
- # their usage is deprecated in Chromium (see README.chromium for more info).
- visibility = [ "//third_party/abseil-cpp/absl/*" ]
- deps = [
- ":config",
- ":core_headers",
- ]
-}
-
-absl_source_set("core_headers") {
- public = [
- "attributes.h",
- "const_init.h",
- "macros.h",
- "optimization.h",
- "port.h",
- "thread_annotations.h",
- ]
- public_deps = [ ":config" ]
-}
-
-absl_source_set("malloc_internal") {
- sources = [ "internal/low_level_alloc.cc" ]
- public = [
- "internal/direct_mmap.h",
- "internal/low_level_alloc.h",
- ]
- public_deps = [
- ":base",
- ":base_internal",
- ":config",
- ":core_headers",
- ":dynamic_annotations",
- ":raw_logging_internal",
- ]
-}
-
-absl_source_set("base_internal") {
- public = [
- "internal/hide_ptr.h",
- "internal/identity.h",
- "internal/inline_variable.h",
- "internal/invoke.h",
- "internal/scheduling_mode.h",
- ]
- public_deps = [
- ":config",
- "//third_party/abseil-cpp/absl/meta:type_traits",
- ]
- visibility = [ "//third_party/abseil-cpp/absl/*" ]
-}
-
-absl_source_set("base") {
- sources = [
- "internal/cycleclock.cc",
- "internal/spinlock.cc",
- "internal/sysinfo.cc",
- "internal/thread_identity.cc",
- "internal/unscaledcycleclock.cc",
- ]
- public = [
- "call_once.h",
- "casts.h",
- "internal/cycleclock.h",
- "internal/low_level_scheduling.h",
- "internal/per_thread_tls.h",
- "internal/spinlock.h",
- "internal/sysinfo.h",
- "internal/thread_identity.h",
- "internal/tsan_mutex_interface.h",
- "internal/unscaledcycleclock.h",
- ]
-
- # TODO(mbonadei): The bazel file has:
- # "-DEFAULTLIB:advapi32.lib"
- # understand if this is needed here as well.
- public_deps = [
- ":atomic_hook",
- ":base_internal",
- ":config",
- ":core_headers",
- ":cycleclock_internal",
- ":dynamic_annotations",
- ":log_severity",
- ":raw_logging_internal",
- ":spinlock_wait",
- "//third_party/abseil-cpp/absl/meta:type_traits",
- ]
-}
-
-absl_source_set("throw_delegate") {
- sources = [ "internal/throw_delegate.cc" ]
- public = [ "internal/throw_delegate.h" ]
- public_deps = [
- ":config",
- ":raw_logging_internal",
- ]
- visibility = [ "//third_party/abseil-cpp/absl/*" ]
-}
-
-absl_source_set("exception_testing") {
- testonly = true
- public = [ "internal/exception_testing.h" ]
- public_deps = [ ":config" ]
- visibility = [ "//third_party/abseil-cpp/absl/*" ]
-}
-
-absl_source_set("pretty_function") {
- public = [ "internal/pretty_function.h" ]
- visibility = [ "//third_party/abseil-cpp/absl/*" ]
-}
-
-# TODO(mbonadei): This target throws by design. We should probably
-# just remove it.
-# source_set("exception_safety_testing") {
-# testonly = true
-# configs -= [ "//build/config/compiler:chromium_code" ]
-# configs += [
-# "//build/config/compiler:no_chromium_code",
-# "//third_party/abseil-cpp:absl_test_cflags_cc",
-# ]
-# public_configs = [ "//third_party/abseil-cpp:absl_include_config" ]
-# sources = [
-# "internal/exception_safety_testing.cc",
-# ]
-# public = [
-# "internal/exception_safety_testing.h",
-# ]
-# deps = [
-# ":config",
-# ":pretty_function",
-# "//third_party/abseil-cpp/absl/memory",
-# "//third_party/abseil-cpp/absl/meta:type_traits",
-# "//third_party/abseil-cpp/absl/strings",
-# "//third_party/abseil-cpp/absl/utility",
-# "//third_party/googletest:gtest",
-# ]
-# }
-
-absl_source_set("spinlock_test_common") {
- testonly = true
- sources = [ "spinlock_test_common.cc" ]
- deps = [
- ":base",
- ":base_internal",
- ":config",
- ":core_headers",
- "//third_party/abseil-cpp/absl/synchronization",
- "//third_party/googletest:gtest",
- ]
-}
-
-absl_source_set("endian") {
- public = [
- "internal/endian.h",
- "internal/unaligned_access.h",
- ]
- public_deps = [
- ":base",
- ":config",
- ":core_headers",
- ]
-}
-
-absl_source_set("scoped_set_env") {
- testonly = true
- public = [ "internal/scoped_set_env.h" ]
- sources = [ "internal/scoped_set_env.cc" ]
- public_deps = [ ":config" ]
- deps = [ ":raw_logging_internal" ]
- visibility = [ "//third_party/abseil-cpp/absl/*" ]
-}
-
-absl_source_set("strerror") {
- sources = [ "internal/strerror.cc" ]
- public = [ "internal/strerror.h" ]
- public_deps = [ ":config" ]
- deps = [
- ":core_headers",
- ":errno_saver",
- ]
- visibility = [ "//third_party/abseil-cpp/absl/*" ]
-}
-
-absl_source_set("fast_type_id") {
- public = [ "internal/fast_type_id.h" ]
- public_deps = [ ":config" ]
- visibility = [ "//third_party/abseil-cpp/absl/*" ]
-}
-
-absl_source_set("prefetch") {
- public = [ "internal/prefetch.h" ]
- deps = [ ":config" ]
- visibility = [ "//third_party/abseil-cpp/absl/*" ]
-}
-
-absl_test("prefetch_test") {
- sources = [ "internal/prefetch_test.cc" ]
- deps = [ ":prefetch" ]
-}
-
-absl_test("config_test") {
- sources = [ "config_test.cc" ]
- deps = [
- ":config",
- "//third_party/abseil-cpp/absl/synchronization:thread_pool",
- ]
-}
diff --git a/third_party/abseil-cpp/absl/base/CMakeLists.txt b/third_party/abseil-cpp/absl/base/CMakeLists.txt
deleted file mode 100644
index febc5512..0000000
--- a/third_party/abseil-cpp/absl/base/CMakeLists.txt
+++ /dev/null
@@ -1,682 +0,0 @@
-#
-# Copyright 2017 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.
-#
-
-find_library(LIBRT rt)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- atomic_hook
- HDRS
- "internal/atomic_hook.h"
- DEPS
- absl::config
- absl::core_headers
- COPTS
- ${ABSL_DEFAULT_COPTS}
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- errno_saver
- HDRS
- "internal/errno_saver.h"
- DEPS
- absl::config
- COPTS
- ${ABSL_DEFAULT_COPTS}
-)
-
-absl_cc_library(
- NAME
- log_severity
- HDRS
- "log_severity.h"
- SRCS
- "log_severity.cc"
- DEPS
- absl::core_headers
- COPTS
- ${ABSL_DEFAULT_COPTS}
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- raw_logging_internal
- HDRS
- "internal/raw_logging.h"
- SRCS
- "internal/raw_logging.cc"
- DEPS
- absl::atomic_hook
- absl::config
- absl::core_headers
- absl::errno_saver
- absl::log_severity
- COPTS
- ${ABSL_DEFAULT_COPTS}
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- spinlock_wait
- HDRS
- "internal/spinlock_wait.h"
- SRCS
- "internal/spinlock_akaros.inc"
- "internal/spinlock_linux.inc"
- "internal/spinlock_posix.inc"
- "internal/spinlock_wait.cc"
- "internal/spinlock_win32.inc"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::base_internal
- absl::core_headers
- absl::errno_saver
-)
-
-absl_cc_library(
- NAME
- config
- HDRS
- "config.h"
- "options.h"
- "policy_checks.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- PUBLIC
-)
-
-absl_cc_library(
- NAME
- dynamic_annotations
- HDRS
- "dynamic_annotations.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::config
- PUBLIC
-)
-
-absl_cc_library(
- NAME
- core_headers
- HDRS
- "attributes.h"
- "const_init.h"
- "macros.h"
- "optimization.h"
- "port.h"
- "thread_annotations.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::config
- PUBLIC
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- malloc_internal
- HDRS
- "internal/direct_mmap.h"
- "internal/low_level_alloc.h"
- SRCS
- "internal/low_level_alloc.cc"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::base
- absl::base_internal
- absl::config
- absl::core_headers
- absl::dynamic_annotations
- absl::raw_logging_internal
- Threads::Threads
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- base_internal
- HDRS
- "internal/hide_ptr.h"
- "internal/identity.h"
- "internal/inline_variable.h"
- "internal/invoke.h"
- "internal/scheduling_mode.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::config
- absl::type_traits
-)
-
-absl_cc_library(
- NAME
- base
- HDRS
- "call_once.h"
- "casts.h"
- "internal/cycleclock.h"
- "internal/cycleclock_config.h"
- "internal/low_level_scheduling.h"
- "internal/per_thread_tls.h"
- "internal/spinlock.h"
- "internal/sysinfo.h"
- "internal/thread_identity.h"
- "internal/tsan_mutex_interface.h"
- "internal/unscaledcycleclock.h"
- "internal/unscaledcycleclock_config.h"
- SRCS
- "internal/cycleclock.cc"
- "internal/spinlock.cc"
- "internal/sysinfo.cc"
- "internal/thread_identity.cc"
- "internal/unscaledcycleclock.cc"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- LINKOPTS
- ${ABSL_DEFAULT_LINKOPTS}
- $<$<BOOL:${LIBRT}>:-lrt>
- $<$<BOOL:${MINGW}>:-ladvapi32>
- DEPS
- absl::atomic_hook
- absl::base_internal
- absl::config
- absl::core_headers
- absl::dynamic_annotations
- absl::log_severity
- absl::raw_logging_internal
- absl::spinlock_wait
- absl::type_traits
- Threads::Threads
- PUBLIC
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- throw_delegate
- HDRS
- "internal/throw_delegate.h"
- SRCS
- "internal/throw_delegate.cc"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::config
- absl::raw_logging_internal
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- exception_testing
- HDRS
- "internal/exception_testing.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::config
- GTest::gtest
- TESTONLY
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- pretty_function
- HDRS
- "internal/pretty_function.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- exception_safety_testing
- HDRS
- "internal/exception_safety_testing.h"
- SRCS
- "internal/exception_safety_testing.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::config
- absl::pretty_function
- absl::memory
- absl::meta
- absl::strings
- absl::utility
- GTest::gtest
- TESTONLY
-)
-
-absl_cc_test(
- NAME
- absl_exception_safety_testing_test
- SRCS
- "exception_safety_testing_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::exception_safety_testing
- absl::memory
- GTest::gtest_main
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- atomic_hook_test_helper
- SRCS
- "internal/atomic_hook_test_helper.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::atomic_hook
- absl::core_headers
- TESTONLY
-)
-
-absl_cc_test(
- NAME
- atomic_hook_test
- SRCS
- "internal/atomic_hook_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::atomic_hook_test_helper
- absl::atomic_hook
- absl::core_headers
- GTest::gmock
- GTest::gtest_main
-)
-
-absl_cc_test(
- NAME
- bit_cast_test
- SRCS
- "bit_cast_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::base
- absl::core_headers
- GTest::gtest_main
-)
-
-absl_cc_test(
- NAME
- errno_saver_test
- SRCS
- "internal/errno_saver_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::errno_saver
- absl::strerror
- GTest::gmock
- GTest::gtest_main
-)
-
-absl_cc_test(
- NAME
- throw_delegate_test
- SRCS
- "throw_delegate_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::base
- absl::config
- absl::throw_delegate
- GTest::gtest_main
-)
-
-absl_cc_test(
- NAME
- inline_variable_test
- SRCS
- "internal/inline_variable_testing.h"
- "inline_variable_test.cc"
- "inline_variable_test_a.cc"
- "inline_variable_test_b.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::base_internal
- GTest::gtest_main
-)
-
-absl_cc_test(
- NAME
- invoke_test
- SRCS
- "invoke_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::base_internal
- absl::memory
- absl::strings
- GTest::gmock
- GTest::gtest_main
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- spinlock_test_common
- SRCS
- "spinlock_test_common.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::base
- absl::config
- absl::base_internal
- absl::core_headers
- absl::synchronization
- GTest::gtest
- TESTONLY
-)
-
-# On bazel BUILD this target use "alwayslink = 1" which is not implemented here
-absl_cc_test(
- NAME
- spinlock_test
- SRCS
- "spinlock_test_common.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::base
- absl::base_internal
- absl::config
- absl::core_headers
- absl::synchronization
- GTest::gtest_main
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- endian
- HDRS
- "internal/endian.h"
- "internal/unaligned_access.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::base
- absl::config
- absl::core_headers
- PUBLIC
-)
-
-absl_cc_test(
- NAME
- endian_test
- SRCS
- "internal/endian_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::base
- absl::config
- absl::endian
- GTest::gtest_main
-)
-
-absl_cc_test(
- NAME
- config_test
- SRCS
- "config_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::config
- absl::synchronization
- GTest::gtest_main
-)
-
-absl_cc_test(
- NAME
- call_once_test
- SRCS
- "call_once_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::base
- absl::core_headers
- absl::synchronization
- GTest::gtest_main
-)
-
-absl_cc_test(
- NAME
- raw_logging_test
- SRCS
- "raw_logging_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::raw_logging_internal
- absl::strings
- GTest::gtest_main
-)
-
-absl_cc_test(
- NAME
- sysinfo_test
- SRCS
- "internal/sysinfo_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::base
- absl::synchronization
- GTest::gtest_main
-)
-
-absl_cc_test(
- NAME
- low_level_alloc_test
- SRCS
- "internal/low_level_alloc_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::malloc_internal
- absl::node_hash_map
- Threads::Threads
-)
-
-absl_cc_test(
- NAME
- thread_identity_test
- SRCS
- "internal/thread_identity_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::base
- absl::core_headers
- absl::synchronization
- Threads::Threads
- GTest::gtest_main
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- scoped_set_env
- SRCS
- "internal/scoped_set_env.cc"
- HDRS
- "internal/scoped_set_env.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::config
- absl::raw_logging_internal
-)
-
-absl_cc_test(
- NAME
- scoped_set_env_test
- SRCS
- "internal/scoped_set_env_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::scoped_set_env
- GTest::gtest_main
-)
-
-absl_cc_test(
- NAME
- cmake_thread_test
- SRCS
- "internal/cmake_thread_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::base
-)
-
-absl_cc_test(
- NAME
- log_severity_test
- SRCS
- "log_severity_test.cc"
- DEPS
- absl::flags_internal
- absl::flags_marshalling
- absl::log_severity
- absl::strings
- GTest::gmock
- GTest::gtest_main
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- strerror
- SRCS
- "internal/strerror.cc"
- HDRS
- "internal/strerror.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- LINKOPTS
- ${ABSL_DEFAULT_LINKOPTS}
- DEPS
- absl::config
- absl::core_headers
- absl::errno_saver
-)
-
-absl_cc_test(
- NAME
- strerror_test
- SRCS
- "internal/strerror_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::strerror
- absl::strings
- GTest::gmock
- GTest::gtest_main
-)
-
-# Internal-only target, do not depend on directly.
-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::gtest_main
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- prefetch
- HDRS
- "internal/prefetch.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- LINKOPTS
- ${ABSL_DEFAULT_LINKOPTS}
- DEPS
- absl::config
-)
-
-absl_cc_test(
- NAME
- prefetch_test
- SRCS
- "internal/prefetch_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::prefetch
- GTest::gtest_main
-)
-
-absl_cc_test(
- NAME
- optimization_test
- SRCS
- "optimization_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::core_headers
- absl::optional
- GTest::gtest_main
-)
diff --git a/third_party/abseil-cpp/absl/base/attributes.h b/third_party/abseil-cpp/absl/base/attributes.h
deleted file mode 100644
index e11a064..0000000
--- a/third_party/abseil-cpp/absl/base/attributes.h
+++ /dev/null
@@ -1,799 +0,0 @@
-// Copyright 2017 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.
-//
-// This header file defines macros for declaring attributes for functions,
-// types, and variables.
-//
-// These macros are used within Abseil and allow the compiler to optimize, where
-// applicable, certain function calls.
-//
-// Most macros here are exposing GCC or Clang features, and are stubbed out for
-// other compilers.
-//
-// GCC attributes documentation:
-// https://gcc.gnu.org/onlinedocs/gcc-4.7.0/gcc/Function-Attributes.html
-// https://gcc.gnu.org/onlinedocs/gcc-4.7.0/gcc/Variable-Attributes.html
-// https://gcc.gnu.org/onlinedocs/gcc-4.7.0/gcc/Type-Attributes.html
-//
-// Most attributes in this file are already supported by GCC 4.7. However, some
-// of them are not supported in older version of Clang. Thus, we check
-// `__has_attribute()` first. If the check fails, we check if we are on GCC and
-// assume the attribute exists on GCC (which is verified on GCC 4.7).
-
-#ifndef ABSL_BASE_ATTRIBUTES_H_
-#define ABSL_BASE_ATTRIBUTES_H_
-
-#include "absl/base/config.h"
-
-// ABSL_HAVE_ATTRIBUTE
-//
-// A function-like feature checking macro that is a wrapper around
-// `__has_attribute`, which is defined by GCC 5+ and Clang and evaluates to a
-// nonzero constant integer if the attribute is supported or 0 if not.
-//
-// It evaluates to zero if `__has_attribute` is not defined by the compiler.
-//
-// GCC: https://gcc.gnu.org/gcc-5/changes.html
-// Clang: https://clang.llvm.org/docs/LanguageExtensions.html
-#ifdef __has_attribute
-#define ABSL_HAVE_ATTRIBUTE(x) __has_attribute(x)
-#else
-#define ABSL_HAVE_ATTRIBUTE(x) 0
-#endif
-
-// ABSL_HAVE_CPP_ATTRIBUTE
-//
-// A function-like feature checking macro that accepts C++11 style attributes.
-// It's a wrapper around `__has_cpp_attribute`, defined by ISO C++ SD-6
-// (https://en.cppreference.com/w/cpp/experimental/feature_test). If we don't
-// find `__has_cpp_attribute`, will evaluate to 0.
-#if defined(__cplusplus) && defined(__has_cpp_attribute)
-// NOTE: requiring __cplusplus above should not be necessary, but
-// works around https://bugs.llvm.org/show_bug.cgi?id=23435.
-#define ABSL_HAVE_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)
-#else
-#define ABSL_HAVE_CPP_ATTRIBUTE(x) 0
-#endif
-
-// -----------------------------------------------------------------------------
-// Function Attributes
-// -----------------------------------------------------------------------------
-//
-// GCC: https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
-// Clang: https://clang.llvm.org/docs/AttributeReference.html
-
-// ABSL_PRINTF_ATTRIBUTE
-// ABSL_SCANF_ATTRIBUTE
-//
-// Tells the compiler to perform `printf` format string checking if the
-// compiler supports it; see the 'format' attribute in
-// <https://gcc.gnu.org/onlinedocs/gcc-4.7.0/gcc/Function-Attributes.html>.
-//
-// Note: As the GCC manual states, "[s]ince non-static C++ methods
-// have an implicit 'this' argument, the arguments of such methods
-// should be counted from two, not one."
-#if ABSL_HAVE_ATTRIBUTE(format) || (defined(__GNUC__) && !defined(__clang__))
-#define ABSL_PRINTF_ATTRIBUTE(string_index, first_to_check) \
- __attribute__((__format__(__printf__, string_index, first_to_check)))
-#define ABSL_SCANF_ATTRIBUTE(string_index, first_to_check) \
- __attribute__((__format__(__scanf__, string_index, first_to_check)))
-#else
-#define ABSL_PRINTF_ATTRIBUTE(string_index, first_to_check)
-#define ABSL_SCANF_ATTRIBUTE(string_index, first_to_check)
-#endif
-
-// ABSL_ATTRIBUTE_ALWAYS_INLINE
-// ABSL_ATTRIBUTE_NOINLINE
-//
-// Forces functions to either inline or not inline. Introduced in gcc 3.1.
-#if ABSL_HAVE_ATTRIBUTE(always_inline) || \
- (defined(__GNUC__) && !defined(__clang__))
-#define ABSL_ATTRIBUTE_ALWAYS_INLINE __attribute__((always_inline))
-#define ABSL_HAVE_ATTRIBUTE_ALWAYS_INLINE 1
-#else
-#define ABSL_ATTRIBUTE_ALWAYS_INLINE
-#endif
-
-#if ABSL_HAVE_ATTRIBUTE(noinline) || (defined(__GNUC__) && !defined(__clang__))
-#define ABSL_ATTRIBUTE_NOINLINE __attribute__((noinline))
-#define ABSL_HAVE_ATTRIBUTE_NOINLINE 1
-#else
-#define ABSL_ATTRIBUTE_NOINLINE
-#endif
-
-// ABSL_ATTRIBUTE_NO_TAIL_CALL
-//
-// Prevents the compiler from optimizing away stack frames for functions which
-// end in a call to another function.
-#if ABSL_HAVE_ATTRIBUTE(disable_tail_calls)
-#define ABSL_HAVE_ATTRIBUTE_NO_TAIL_CALL 1
-#define ABSL_ATTRIBUTE_NO_TAIL_CALL __attribute__((disable_tail_calls))
-#elif defined(__GNUC__) && !defined(__clang__) && !defined(__e2k__)
-#define ABSL_HAVE_ATTRIBUTE_NO_TAIL_CALL 1
-#define ABSL_ATTRIBUTE_NO_TAIL_CALL \
- __attribute__((optimize("no-optimize-sibling-calls")))
-#else
-#define ABSL_ATTRIBUTE_NO_TAIL_CALL
-#define ABSL_HAVE_ATTRIBUTE_NO_TAIL_CALL 0
-#endif
-
-// ABSL_ATTRIBUTE_WEAK
-//
-// Tags a function as weak for the purposes of compilation and linking.
-// Weak attributes did not work properly in LLVM's Windows backend before
-// 9.0.0, so disable them there. See https://bugs.llvm.org/show_bug.cgi?id=37598
-// for further information.
-// The MinGW compiler doesn't complain about the weak attribute until the link
-// step, presumably because Windows doesn't use ELF binaries.
-#if (ABSL_HAVE_ATTRIBUTE(weak) || \
- (defined(__GNUC__) && !defined(__clang__))) && \
- (!defined(_WIN32) || (defined(__clang__) && __clang_major__ >= 9)) && \
- !defined(__MINGW32__)
-#undef ABSL_ATTRIBUTE_WEAK
-#define ABSL_ATTRIBUTE_WEAK __attribute__((weak))
-#define ABSL_HAVE_ATTRIBUTE_WEAK 1
-#else
-#define ABSL_ATTRIBUTE_WEAK
-#define ABSL_HAVE_ATTRIBUTE_WEAK 0
-#endif
-
-// ABSL_ATTRIBUTE_NONNULL
-//
-// Tells the compiler either (a) that a particular function parameter
-// should be a non-null pointer, or (b) that all pointer arguments should
-// be non-null.
-//
-// Note: As the GCC manual states, "[s]ince non-static C++ methods
-// have an implicit 'this' argument, the arguments of such methods
-// should be counted from two, not one."
-//
-// Args are indexed starting at 1.
-//
-// For non-static class member functions, the implicit `this` argument
-// is arg 1, and the first explicit argument is arg 2. For static class member
-// functions, there is no implicit `this`, and the first explicit argument is
-// arg 1.
-//
-// Example:
-//
-// /* arg_a cannot be null, but arg_b can */
-// void Function(void* arg_a, void* arg_b) ABSL_ATTRIBUTE_NONNULL(1);
-//
-// class C {
-// /* arg_a cannot be null, but arg_b can */
-// void Method(void* arg_a, void* arg_b) ABSL_ATTRIBUTE_NONNULL(2);
-//
-// /* arg_a cannot be null, but arg_b can */
-// static void StaticMethod(void* arg_a, void* arg_b)
-// ABSL_ATTRIBUTE_NONNULL(1);
-// };
-//
-// If no arguments are provided, then all pointer arguments should be non-null.
-//
-// /* No pointer arguments may be null. */
-// void Function(void* arg_a, void* arg_b, int arg_c) ABSL_ATTRIBUTE_NONNULL();
-//
-// NOTE: The GCC nonnull attribute actually accepts a list of arguments, but
-// ABSL_ATTRIBUTE_NONNULL does not.
-#if ABSL_HAVE_ATTRIBUTE(nonnull) || (defined(__GNUC__) && !defined(__clang__))
-#define ABSL_ATTRIBUTE_NONNULL(arg_index) __attribute__((nonnull(arg_index)))
-#else
-#define ABSL_ATTRIBUTE_NONNULL(...)
-#endif
-
-// ABSL_ATTRIBUTE_NORETURN
-//
-// Tells the compiler that a given function never returns.
-#if ABSL_HAVE_ATTRIBUTE(noreturn) || (defined(__GNUC__) && !defined(__clang__))
-#define ABSL_ATTRIBUTE_NORETURN __attribute__((noreturn))
-#elif defined(_MSC_VER)
-#define ABSL_ATTRIBUTE_NORETURN __declspec(noreturn)
-#else
-#define ABSL_ATTRIBUTE_NORETURN
-#endif
-
-// ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS
-//
-// Tells the AddressSanitizer (or other memory testing tools) to ignore a given
-// function. Useful for cases when a function reads random locations on stack,
-// calls _exit from a cloned subprocess, deliberately accesses buffer
-// out of bounds or does other scary things with memory.
-// NOTE: GCC supports AddressSanitizer(asan) since 4.8.
-// https://gcc.gnu.org/gcc-4.8/changes.html
-#if ABSL_HAVE_ATTRIBUTE(no_sanitize_address)
-#define ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS __attribute__((no_sanitize_address))
-#elif defined(_MSC_VER) && _MSC_VER >= 1928
-// https://docs.microsoft.com/en-us/cpp/cpp/no-sanitize-address
-#define ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS __declspec(no_sanitize_address)
-#else
-#define ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS
-#endif
-
-// ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY
-//
-// Tells the MemorySanitizer to relax the handling of a given function. All "Use
-// of uninitialized value" warnings from such functions will be suppressed, and
-// all values loaded from memory will be considered fully initialized. This
-// attribute is similar to the ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS attribute
-// above, but deals with initialized-ness rather than addressability issues.
-// NOTE: MemorySanitizer(msan) is supported by Clang but not GCC.
-#if ABSL_HAVE_ATTRIBUTE(no_sanitize_memory)
-#define ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY __attribute__((no_sanitize_memory))
-#else
-#define ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY
-#endif
-
-// ABSL_ATTRIBUTE_NO_SANITIZE_THREAD
-//
-// Tells the ThreadSanitizer to not instrument a given function.
-// NOTE: GCC supports ThreadSanitizer(tsan) since 4.8.
-// https://gcc.gnu.org/gcc-4.8/changes.html
-#if ABSL_HAVE_ATTRIBUTE(no_sanitize_thread)
-#define ABSL_ATTRIBUTE_NO_SANITIZE_THREAD __attribute__((no_sanitize_thread))
-#else
-#define ABSL_ATTRIBUTE_NO_SANITIZE_THREAD
-#endif
-
-// ABSL_ATTRIBUTE_NO_SANITIZE_UNDEFINED
-//
-// Tells the UndefinedSanitizer to ignore a given function. Useful for cases
-// where certain behavior (eg. division by zero) is being used intentionally.
-// NOTE: GCC supports UndefinedBehaviorSanitizer(ubsan) since 4.9.
-// https://gcc.gnu.org/gcc-4.9/changes.html
-#if ABSL_HAVE_ATTRIBUTE(no_sanitize_undefined)
-#define ABSL_ATTRIBUTE_NO_SANITIZE_UNDEFINED \
- __attribute__((no_sanitize_undefined))
-#elif ABSL_HAVE_ATTRIBUTE(no_sanitize)
-#define ABSL_ATTRIBUTE_NO_SANITIZE_UNDEFINED \
- __attribute__((no_sanitize("undefined")))
-#else
-#define ABSL_ATTRIBUTE_NO_SANITIZE_UNDEFINED
-#endif
-
-// ABSL_ATTRIBUTE_NO_SANITIZE_CFI
-//
-// Tells the ControlFlowIntegrity sanitizer to not instrument a given function.
-// See https://clang.llvm.org/docs/ControlFlowIntegrity.html for details.
-#if ABSL_HAVE_ATTRIBUTE(no_sanitize)
-#define ABSL_ATTRIBUTE_NO_SANITIZE_CFI __attribute__((no_sanitize("cfi")))
-#else
-#define ABSL_ATTRIBUTE_NO_SANITIZE_CFI
-#endif
-
-// ABSL_ATTRIBUTE_NO_SANITIZE_SAFESTACK
-//
-// Tells the SafeStack to not instrument a given function.
-// See https://clang.llvm.org/docs/SafeStack.html for details.
-#if ABSL_HAVE_ATTRIBUTE(no_sanitize)
-#define ABSL_ATTRIBUTE_NO_SANITIZE_SAFESTACK \
- __attribute__((no_sanitize("safe-stack")))
-#else
-#define ABSL_ATTRIBUTE_NO_SANITIZE_SAFESTACK
-#endif
-
-// ABSL_ATTRIBUTE_RETURNS_NONNULL
-//
-// Tells the compiler that a particular function never returns a null pointer.
-#if ABSL_HAVE_ATTRIBUTE(returns_nonnull)
-#define ABSL_ATTRIBUTE_RETURNS_NONNULL __attribute__((returns_nonnull))
-#else
-#define ABSL_ATTRIBUTE_RETURNS_NONNULL
-#endif
-
-// ABSL_HAVE_ATTRIBUTE_SECTION
-//
-// Indicates whether labeled sections are supported. Weak symbol support is
-// a prerequisite. Labeled sections are not supported on Darwin/iOS.
-#ifdef ABSL_HAVE_ATTRIBUTE_SECTION
-#error ABSL_HAVE_ATTRIBUTE_SECTION cannot be directly set
-#elif (ABSL_HAVE_ATTRIBUTE(section) || \
- (defined(__GNUC__) && !defined(__clang__))) && \
- !defined(__APPLE__) && ABSL_HAVE_ATTRIBUTE_WEAK
-#define ABSL_HAVE_ATTRIBUTE_SECTION 1
-
-// ABSL_ATTRIBUTE_SECTION
-//
-// Tells the compiler/linker to put a given function into a section and define
-// `__start_ ## name` and `__stop_ ## name` symbols to bracket the section.
-// This functionality is supported by GNU linker. Any function annotated with
-// `ABSL_ATTRIBUTE_SECTION` must not be inlined, or it will be placed into
-// whatever section its caller is placed into.
-//
-#ifndef ABSL_ATTRIBUTE_SECTION
-#define ABSL_ATTRIBUTE_SECTION(name) \
- __attribute__((section(#name))) __attribute__((noinline))
-#endif
-
-// ABSL_ATTRIBUTE_SECTION_VARIABLE
-//
-// Tells the compiler/linker to put a given variable into a section and define
-// `__start_ ## name` and `__stop_ ## name` symbols to bracket the section.
-// This functionality is supported by GNU linker.
-#ifndef ABSL_ATTRIBUTE_SECTION_VARIABLE
-#ifdef _AIX
-// __attribute__((section(#name))) on AIX is achived by using the `.csect` psudo
-// op which includes an additional integer as part of its syntax indcating
-// alignment. If data fall under different alignments then you might get a
-// compilation error indicating a `Section type conflict`.
-#define ABSL_ATTRIBUTE_SECTION_VARIABLE(name)
-#else
-#define ABSL_ATTRIBUTE_SECTION_VARIABLE(name) __attribute__((section(#name)))
-#endif
-#endif
-
-// ABSL_DECLARE_ATTRIBUTE_SECTION_VARS
-//
-// A weak section declaration to be used as a global declaration
-// for ABSL_ATTRIBUTE_SECTION_START|STOP(name) to compile and link
-// even without functions with ABSL_ATTRIBUTE_SECTION(name).
-// ABSL_DEFINE_ATTRIBUTE_SECTION should be in the exactly one file; it's
-// a no-op on ELF but not on Mach-O.
-//
-#ifndef ABSL_DECLARE_ATTRIBUTE_SECTION_VARS
-#define ABSL_DECLARE_ATTRIBUTE_SECTION_VARS(name) \
- extern char __start_##name[] ABSL_ATTRIBUTE_WEAK; \
- extern char __stop_##name[] ABSL_ATTRIBUTE_WEAK
-#endif
-#ifndef ABSL_DEFINE_ATTRIBUTE_SECTION_VARS
-#define ABSL_INIT_ATTRIBUTE_SECTION_VARS(name)
-#define ABSL_DEFINE_ATTRIBUTE_SECTION_VARS(name)
-#endif
-
-// ABSL_ATTRIBUTE_SECTION_START
-//
-// Returns `void*` pointers to start/end of a section of code with
-// functions having ABSL_ATTRIBUTE_SECTION(name).
-// Returns 0 if no such functions exist.
-// One must ABSL_DECLARE_ATTRIBUTE_SECTION_VARS(name) for this to compile and
-// link.
-//
-#define ABSL_ATTRIBUTE_SECTION_START(name) \
- (reinterpret_cast<void *>(__start_##name))
-#define ABSL_ATTRIBUTE_SECTION_STOP(name) \
- (reinterpret_cast<void *>(__stop_##name))
-
-#else // !ABSL_HAVE_ATTRIBUTE_SECTION
-
-#define ABSL_HAVE_ATTRIBUTE_SECTION 0
-
-// provide dummy definitions
-#define ABSL_ATTRIBUTE_SECTION(name)
-#define ABSL_ATTRIBUTE_SECTION_VARIABLE(name)
-#define ABSL_INIT_ATTRIBUTE_SECTION_VARS(name)
-#define ABSL_DEFINE_ATTRIBUTE_SECTION_VARS(name)
-#define ABSL_DECLARE_ATTRIBUTE_SECTION_VARS(name)
-#define ABSL_ATTRIBUTE_SECTION_START(name) (reinterpret_cast<void *>(0))
-#define ABSL_ATTRIBUTE_SECTION_STOP(name) (reinterpret_cast<void *>(0))
-
-#endif // ABSL_ATTRIBUTE_SECTION
-
-// ABSL_ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC
-//
-// Support for aligning the stack on 32-bit x86.
-#if ABSL_HAVE_ATTRIBUTE(force_align_arg_pointer) || \
- (defined(__GNUC__) && !defined(__clang__))
-#if defined(__i386__)
-#define ABSL_ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC \
- __attribute__((force_align_arg_pointer))
-#define ABSL_REQUIRE_STACK_ALIGN_TRAMPOLINE (0)
-#elif defined(__x86_64__)
-#define ABSL_REQUIRE_STACK_ALIGN_TRAMPOLINE (1)
-#define ABSL_ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC
-#else // !__i386__ && !__x86_64
-#define ABSL_REQUIRE_STACK_ALIGN_TRAMPOLINE (0)
-#define ABSL_ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC
-#endif // __i386__
-#else
-#define ABSL_ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC
-#define ABSL_REQUIRE_STACK_ALIGN_TRAMPOLINE (0)
-#endif
-
-// ABSL_MUST_USE_RESULT
-//
-// Tells the compiler to warn about unused results.
-//
-// For code or headers that are assured to only build with C++17 and up, prefer
-// just using the standard `[[nodiscard]]` directly over this macro.
-//
-// When annotating a function, it must appear as the first part of the
-// declaration or definition. The compiler will warn if the return value from
-// such a function is unused:
-//
-// ABSL_MUST_USE_RESULT Sprocket* AllocateSprocket();
-// AllocateSprocket(); // Triggers a warning.
-//
-// When annotating a class, it is equivalent to annotating every function which
-// returns an instance.
-//
-// class ABSL_MUST_USE_RESULT Sprocket {};
-// Sprocket(); // Triggers a warning.
-//
-// Sprocket MakeSprocket();
-// MakeSprocket(); // Triggers a warning.
-//
-// Note that references and pointers are not instances:
-//
-// Sprocket* SprocketPointer();
-// SprocketPointer(); // Does *not* trigger a warning.
-//
-// ABSL_MUST_USE_RESULT allows using cast-to-void to suppress the unused result
-// warning. For that, warn_unused_result is used only for clang but not for gcc.
-// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66425
-//
-// Note: past advice was to place the macro after the argument list.
-//
-// TODO(b/176172494): Use ABSL_HAVE_CPP_ATTRIBUTE(nodiscard) when all code is
-// compliant with the stricter [[nodiscard]].
-#if defined(__clang__) && ABSL_HAVE_ATTRIBUTE(warn_unused_result)
-#define ABSL_MUST_USE_RESULT __attribute__((warn_unused_result))
-#else
-#define ABSL_MUST_USE_RESULT
-#endif
-
-// ABSL_ATTRIBUTE_HOT, ABSL_ATTRIBUTE_COLD
-//
-// Tells GCC that a function is hot or cold. GCC can use this information to
-// improve static analysis, i.e. a conditional branch to a cold function
-// is likely to be not-taken.
-// This annotation is used for function declarations.
-//
-// Example:
-//
-// int foo() ABSL_ATTRIBUTE_HOT;
-#if ABSL_HAVE_ATTRIBUTE(hot) || (defined(__GNUC__) && !defined(__clang__))
-#define ABSL_ATTRIBUTE_HOT __attribute__((hot))
-#else
-#define ABSL_ATTRIBUTE_HOT
-#endif
-
-#if ABSL_HAVE_ATTRIBUTE(cold) || (defined(__GNUC__) && !defined(__clang__))
-#define ABSL_ATTRIBUTE_COLD __attribute__((cold))
-#else
-#define ABSL_ATTRIBUTE_COLD
-#endif
-
-// ABSL_XRAY_ALWAYS_INSTRUMENT, ABSL_XRAY_NEVER_INSTRUMENT, ABSL_XRAY_LOG_ARGS
-//
-// We define the ABSL_XRAY_ALWAYS_INSTRUMENT and ABSL_XRAY_NEVER_INSTRUMENT
-// macro used as an attribute to mark functions that must always or never be
-// instrumented by XRay. Currently, this is only supported in Clang/LLVM.
-//
-// For reference on the LLVM XRay instrumentation, see
-// http://llvm.org/docs/XRay.html.
-//
-// A function with the XRAY_ALWAYS_INSTRUMENT macro attribute in its declaration
-// will always get the XRay instrumentation sleds. These sleds may introduce
-// some binary size and runtime overhead and must be used sparingly.
-//
-// These attributes only take effect when the following conditions are met:
-//
-// * The file/target is built in at least C++11 mode, with a Clang compiler
-// that supports XRay attributes.
-// * The file/target is built with the -fxray-instrument flag set for the
-// Clang/LLVM compiler.
-// * The function is defined in the translation unit (the compiler honors the
-// attribute in either the definition or the declaration, and must match).
-//
-// There are cases when, even when building with XRay instrumentation, users
-// might want to control specifically which functions are instrumented for a
-// particular build using special-case lists provided to the compiler. These
-// special case lists are provided to Clang via the
-// -fxray-always-instrument=... and -fxray-never-instrument=... flags. The
-// attributes in source take precedence over these special-case lists.
-//
-// To disable the XRay attributes at build-time, users may define
-// ABSL_NO_XRAY_ATTRIBUTES. Do NOT define ABSL_NO_XRAY_ATTRIBUTES on specific
-// packages/targets, as this may lead to conflicting definitions of functions at
-// link-time.
-//
-// XRay isn't currently supported on Android:
-// https://github.com/android/ndk/issues/368
-#if ABSL_HAVE_CPP_ATTRIBUTE(clang::xray_always_instrument) && \
- !defined(ABSL_NO_XRAY_ATTRIBUTES) && !defined(__ANDROID__)
-#define ABSL_XRAY_ALWAYS_INSTRUMENT [[clang::xray_always_instrument]]
-#define ABSL_XRAY_NEVER_INSTRUMENT [[clang::xray_never_instrument]]
-#if ABSL_HAVE_CPP_ATTRIBUTE(clang::xray_log_args)
-#define ABSL_XRAY_LOG_ARGS(N) \
- [[clang::xray_always_instrument, clang::xray_log_args(N)]]
-#else
-#define ABSL_XRAY_LOG_ARGS(N) [[clang::xray_always_instrument]]
-#endif
-#else
-#define ABSL_XRAY_ALWAYS_INSTRUMENT
-#define ABSL_XRAY_NEVER_INSTRUMENT
-#define ABSL_XRAY_LOG_ARGS(N)
-#endif
-
-// ABSL_ATTRIBUTE_REINITIALIZES
-//
-// Indicates that a member function reinitializes the entire object to a known
-// state, independent of the previous state of the object.
-//
-// The clang-tidy check bugprone-use-after-move allows member functions marked
-// with this attribute to be called on objects that have been moved from;
-// without the attribute, this would result in a use-after-move warning.
-#if ABSL_HAVE_CPP_ATTRIBUTE(clang::reinitializes)
-#define ABSL_ATTRIBUTE_REINITIALIZES [[clang::reinitializes]]
-#else
-#define ABSL_ATTRIBUTE_REINITIALIZES
-#endif
-
-// -----------------------------------------------------------------------------
-// Variable Attributes
-// -----------------------------------------------------------------------------
-
-// ABSL_ATTRIBUTE_UNUSED
-//
-// Prevents the compiler from complaining about variables that appear unused.
-//
-// For code or headers that are assured to only build with C++17 and up, prefer
-// just using the standard '[[maybe_unused]]' directly over this macro.
-//
-// Due to differences in positioning requirements between the old, compiler
-// specific __attribute__ syntax and the now standard [[maybe_unused]], this
-// macro does not attempt to take advantage of '[[maybe_unused]]'.
-#if ABSL_HAVE_ATTRIBUTE(unused) || (defined(__GNUC__) && !defined(__clang__))
-#undef ABSL_ATTRIBUTE_UNUSED
-#define ABSL_ATTRIBUTE_UNUSED __attribute__((__unused__))
-#else
-#define ABSL_ATTRIBUTE_UNUSED
-#endif
-
-// ABSL_ATTRIBUTE_INITIAL_EXEC
-//
-// Tells the compiler to use "initial-exec" mode for a thread-local variable.
-// See http://people.redhat.com/drepper/tls.pdf for the gory details.
-#if ABSL_HAVE_ATTRIBUTE(tls_model) || (defined(__GNUC__) && !defined(__clang__))
-#define ABSL_ATTRIBUTE_INITIAL_EXEC __attribute__((tls_model("initial-exec")))
-#else
-#define ABSL_ATTRIBUTE_INITIAL_EXEC
-#endif
-
-// ABSL_ATTRIBUTE_PACKED
-//
-// Instructs the compiler not to use natural alignment for a tagged data
-// structure, but instead to reduce its alignment to 1.
-//
-// Therefore, DO NOT APPLY THIS ATTRIBUTE TO STRUCTS CONTAINING ATOMICS. Doing
-// so can cause atomic variables to be mis-aligned and silently violate
-// atomicity on x86.
-//
-// This attribute can either be applied to members of a structure or to a
-// structure in its entirety. Applying this attribute (judiciously) to a
-// structure in its entirety to optimize the memory footprint of very
-// commonly-used structs is fine. Do not apply this attribute to a structure in
-// its entirety if the purpose is to control the offsets of the members in the
-// structure. Instead, apply this attribute only to structure members that need
-// it.
-//
-// When applying ABSL_ATTRIBUTE_PACKED only to specific structure members the
-// natural alignment of structure members not annotated is preserved. Aligned
-// member accesses are faster than non-aligned member accesses even if the
-// targeted microprocessor supports non-aligned accesses.
-#if ABSL_HAVE_ATTRIBUTE(packed) || (defined(__GNUC__) && !defined(__clang__))
-#define ABSL_ATTRIBUTE_PACKED __attribute__((__packed__))
-#else
-#define ABSL_ATTRIBUTE_PACKED
-#endif
-
-// ABSL_ATTRIBUTE_FUNC_ALIGN
-//
-// Tells the compiler to align the function start at least to certain
-// alignment boundary
-#if ABSL_HAVE_ATTRIBUTE(aligned) || (defined(__GNUC__) && !defined(__clang__))
-#define ABSL_ATTRIBUTE_FUNC_ALIGN(bytes) __attribute__((aligned(bytes)))
-#else
-#define ABSL_ATTRIBUTE_FUNC_ALIGN(bytes)
-#endif
-
-// ABSL_FALLTHROUGH_INTENDED
-//
-// Annotates implicit fall-through between switch labels, allowing a case to
-// indicate intentional fallthrough and turn off warnings about any lack of a
-// `break` statement. The ABSL_FALLTHROUGH_INTENDED macro should be followed by
-// a semicolon and can be used in most places where `break` can, provided that
-// no statements exist between it and the next switch label.
-//
-// Example:
-//
-// switch (x) {
-// case 40:
-// case 41:
-// if (truth_is_out_there) {
-// ++x;
-// ABSL_FALLTHROUGH_INTENDED; // Use instead of/along with annotations
-// // in comments
-// } else {
-// return x;
-// }
-// case 42:
-// ...
-//
-// Notes: When supported, GCC and Clang can issue a warning on switch labels
-// with unannotated fallthrough using the warning `-Wimplicit-fallthrough`. See
-// clang documentation on language extensions for details:
-// https://clang.llvm.org/docs/AttributeReference.html#fallthrough-clang-fallthrough
-//
-// When used with unsupported compilers, the ABSL_FALLTHROUGH_INTENDED macro has
-// no effect on diagnostics. In any case this macro has no effect on runtime
-// behavior and performance of code.
-
-#ifdef ABSL_FALLTHROUGH_INTENDED
-#error "ABSL_FALLTHROUGH_INTENDED should not be defined."
-#elif ABSL_HAVE_CPP_ATTRIBUTE(fallthrough)
-#define ABSL_FALLTHROUGH_INTENDED [[fallthrough]]
-#elif ABSL_HAVE_CPP_ATTRIBUTE(clang::fallthrough)
-#define ABSL_FALLTHROUGH_INTENDED [[clang::fallthrough]]
-#elif ABSL_HAVE_CPP_ATTRIBUTE(gnu::fallthrough)
-#define ABSL_FALLTHROUGH_INTENDED [[gnu::fallthrough]]
-#else
-#define ABSL_FALLTHROUGH_INTENDED \
- do { \
- } while (0)
-#endif
-
-// ABSL_DEPRECATED()
-//
-// Marks a deprecated class, struct, enum, function, method and variable
-// declarations. The macro argument is used as a custom diagnostic message (e.g.
-// suggestion of a better alternative).
-//
-// For code or headers that are assured to only build with C++14 and up, prefer
-// just using the standard `[[deprecated("message")]]` directly over this macro.
-//
-// Examples:
-//
-// class ABSL_DEPRECATED("Use Bar instead") Foo {...};
-//
-// ABSL_DEPRECATED("Use Baz() instead") void Bar() {...}
-//
-// template <typename T>
-// ABSL_DEPRECATED("Use DoThat() instead")
-// void DoThis();
-//
-// enum FooEnum {
-// kBar ABSL_DEPRECATED("Use kBaz instead"),
-// };
-//
-// Every usage of a deprecated entity will trigger a warning when compiled with
-// GCC/Clang's `-Wdeprecated-declarations` option. Google's production toolchain
-// turns this warning off by default, instead relying on clang-tidy to report
-// new uses of deprecated code.
-#if ABSL_HAVE_ATTRIBUTE(deprecated)
-#define ABSL_DEPRECATED(message) __attribute__((deprecated(message)))
-#else
-#define ABSL_DEPRECATED(message)
-#endif
-
-// ABSL_CONST_INIT
-//
-// A variable declaration annotated with the `ABSL_CONST_INIT` attribute will
-// not compile (on supported platforms) unless the variable has a constant
-// initializer. This is useful for variables with static and thread storage
-// duration, because it guarantees that they will not suffer from the so-called
-// "static init order fiasco".
-//
-// This attribute must be placed on the initializing declaration of the
-// variable. Some compilers will give a -Wmissing-constinit warning when this
-// attribute is placed on some other declaration but missing from the
-// initializing declaration.
-//
-// In some cases (notably with thread_local variables), `ABSL_CONST_INIT` can
-// also be used in a non-initializing declaration to tell the compiler that a
-// variable is already initialized, reducing overhead that would otherwise be
-// incurred by a hidden guard variable. Thus annotating all declarations with
-// this attribute is recommended to potentially enhance optimization.
-//
-// Example:
-//
-// class MyClass {
-// public:
-// ABSL_CONST_INIT static MyType my_var;
-// };
-//
-// ABSL_CONST_INIT MyType MyClass::my_var = MakeMyType(...);
-//
-// For code or headers that are assured to only build with C++20 and up, prefer
-// just using the standard `constinit` keyword directly over this macro.
-//
-// Note that this attribute is redundant if the variable is declared constexpr.
-#if defined(__cpp_constinit) && __cpp_constinit >= 201907L
-#define ABSL_CONST_INIT constinit
-#elif ABSL_HAVE_CPP_ATTRIBUTE(clang::require_constant_initialization)
-#define ABSL_CONST_INIT [[clang::require_constant_initialization]]
-#else
-#define ABSL_CONST_INIT
-#endif
-
-// ABSL_ATTRIBUTE_PURE_FUNCTION
-//
-// ABSL_ATTRIBUTE_PURE_FUNCTION is used to annotate declarations of "pure"
-// functions. A function is pure if its return value is only a function of its
-// arguments. The pure attribute prohibits a function from modifying the state
-// of the program that is observable by means other than inspecting the
-// function's return value. Declaring such functions with the pure attribute
-// allows the compiler to avoid emitting some calls in repeated invocations of
-// the function with the same argument values.
-//
-// Example:
-//
-// ABSL_ATTRIBUTE_PURE_FUNCTION int64_t ToInt64Milliseconds(Duration d);
-#if ABSL_HAVE_CPP_ATTRIBUTE(gnu::pure)
-#define ABSL_ATTRIBUTE_PURE_FUNCTION [[gnu::pure]]
-#elif ABSL_HAVE_ATTRIBUTE(pure)
-#define ABSL_ATTRIBUTE_PURE_FUNCTION __attribute__((pure))
-#else
-#define ABSL_ATTRIBUTE_PURE_FUNCTION
-#endif
-
-// ABSL_ATTRIBUTE_LIFETIME_BOUND indicates that a resource owned by a function
-// parameter or implicit object parameter is retained by the return value of the
-// annotated function (or, for a parameter of a constructor, in the value of the
-// constructed object). This attribute causes warnings to be produced if a
-// temporary object does not live long enough.
-//
-// When applied to a reference parameter, the referenced object is assumed to be
-// retained by the return value of the function. When applied to a non-reference
-// parameter (for example, a pointer or a class type), all temporaries
-// referenced by the parameter are assumed to be retained by the return value of
-// the function.
-//
-// See also the upstream documentation:
-// https://clang.llvm.org/docs/AttributeReference.html#lifetimebound
-#if ABSL_HAVE_CPP_ATTRIBUTE(clang::lifetimebound)
-#define ABSL_ATTRIBUTE_LIFETIME_BOUND [[clang::lifetimebound]]
-#elif ABSL_HAVE_ATTRIBUTE(lifetimebound)
-#define ABSL_ATTRIBUTE_LIFETIME_BOUND __attribute__((lifetimebound))
-#else
-#define ABSL_ATTRIBUTE_LIFETIME_BOUND
-#endif
-
-// ABSL_ATTRIBUTE_TRIVIAL_ABI
-// Indicates that a type is "trivially relocatable" -- meaning it can be
-// relocated without invoking the constructor/destructor, using a form of move
-// elision.
-//
-// From a memory safety point of view, putting aside destructor ordering, it's
-// safe to apply ABSL_ATTRIBUTE_TRIVIAL_ABI if an object's location
-// can change over the course of its lifetime: if a constructor can be run one
-// place, and then the object magically teleports to another place where some
-// methods are run, and then the object teleports to yet another place where it
-// is destroyed. This is notably not true for self-referential types, where the
-// move-constructor must keep the self-reference up to date. If the type changed
-// location without invoking the move constructor, it would have a dangling
-// self-reference.
-//
-// The use of this teleporting machinery means that the number of paired
-// move/destroy operations can change, and so it is a bad idea to apply this to
-// a type meant to count the number of moves.
-//
-// Warning: applying this can, rarely, break callers. Objects passed by value
-// will be destroyed at the end of the call, instead of the end of the
-// full-expression containing the call. In addition, it changes the ABI
-// of functions accepting this type by value (e.g. to pass in registers).
-//
-// See also the upstream documentation:
-// https://clang.llvm.org/docs/AttributeReference.html#trivial-abi
-//
-#if ABSL_HAVE_CPP_ATTRIBUTE(clang::trivial_abi)
-#define ABSL_ATTRIBUTE_TRIVIAL_ABI [[clang::trivial_abi]]
-#define ABSL_HAVE_ATTRIBUTE_TRIVIAL_ABI 1
-#elif ABSL_HAVE_ATTRIBUTE(trivial_abi)
-#define ABSL_ATTRIBUTE_TRIVIAL_ABI __attribute__((trivial_abi))
-#define ABSL_HAVE_ATTRIBUTE_TRIVIAL_ABI 1
-#else
-#define ABSL_ATTRIBUTE_TRIVIAL_ABI
-#endif
-
-#endif // ABSL_BASE_ATTRIBUTES_H_
diff --git a/third_party/abseil-cpp/absl/base/bit_cast_test.cc b/third_party/abseil-cpp/absl/base/bit_cast_test.cc
deleted file mode 100644
index 8a3a41e..0000000
--- a/third_party/abseil-cpp/absl/base/bit_cast_test.cc
+++ /dev/null
@@ -1,109 +0,0 @@
-// Copyright 2017 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.
-
-// Unit test for bit_cast template.
-
-#include <cstdint>
-#include <cstring>
-
-#include "gtest/gtest.h"
-#include "absl/base/casts.h"
-#include "absl/base/macros.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace {
-
-template <int N>
-struct marshall { char buf[N]; };
-
-template <typename T>
-void TestMarshall(const T values[], int num_values) {
- for (int i = 0; i < num_values; ++i) {
- T t0 = values[i];
- marshall<sizeof(T)> m0 = absl::bit_cast<marshall<sizeof(T)> >(t0);
- T t1 = absl::bit_cast<T>(m0);
- marshall<sizeof(T)> m1 = absl::bit_cast<marshall<sizeof(T)> >(t1);
- ASSERT_EQ(0, memcmp(&t0, &t1, sizeof(T)));
- ASSERT_EQ(0, memcmp(&m0, &m1, sizeof(T)));
- }
-}
-
-// Convert back and forth to an integral type. The C++ standard does
-// not guarantee this will work, but we test that this works on all the
-// platforms we support.
-//
-// Likewise, we below make assumptions about sizeof(float) and
-// sizeof(double) which the standard does not guarantee, but which hold on the
-// platforms we support.
-
-template <typename T, typename I>
-void TestIntegral(const T values[], int num_values) {
- for (int i = 0; i < num_values; ++i) {
- T t0 = values[i];
- I i0 = absl::bit_cast<I>(t0);
- T t1 = absl::bit_cast<T>(i0);
- I i1 = absl::bit_cast<I>(t1);
- ASSERT_EQ(0, memcmp(&t0, &t1, sizeof(T)));
- ASSERT_EQ(i0, i1);
- }
-}
-
-TEST(BitCast, Bool) {
- static const bool bool_list[] = { false, true };
- TestMarshall<bool>(bool_list, ABSL_ARRAYSIZE(bool_list));
-}
-
-TEST(BitCast, Int32) {
- static const int32_t int_list[] =
- { 0, 1, 100, 2147483647, -1, -100, -2147483647, -2147483647-1 };
- TestMarshall<int32_t>(int_list, ABSL_ARRAYSIZE(int_list));
-}
-
-TEST(BitCast, Int64) {
- static const int64_t int64_list[] =
- { 0, 1, 1LL << 40, -1, -(1LL<<40) };
- TestMarshall<int64_t>(int64_list, ABSL_ARRAYSIZE(int64_list));
-}
-
-TEST(BitCast, Uint64) {
- static const uint64_t uint64_list[] =
- { 0, 1, 1LLU << 40, 1LLU << 63 };
- TestMarshall<uint64_t>(uint64_list, ABSL_ARRAYSIZE(uint64_list));
-}
-
-TEST(BitCast, Float) {
- static const float float_list[] =
- { 0.0f, 1.0f, -1.0f, 10.0f, -10.0f,
- 1e10f, 1e20f, 1e-10f, 1e-20f,
- 2.71828f, 3.14159f };
- TestMarshall<float>(float_list, ABSL_ARRAYSIZE(float_list));
- TestIntegral<float, int>(float_list, ABSL_ARRAYSIZE(float_list));
- TestIntegral<float, unsigned>(float_list, ABSL_ARRAYSIZE(float_list));
-}
-
-TEST(BitCast, Double) {
- static const double double_list[] =
- { 0.0, 1.0, -1.0, 10.0, -10.0,
- 1e10, 1e100, 1e-10, 1e-100,
- 2.718281828459045,
- 3.141592653589793238462643383279502884197169399375105820974944 };
- TestMarshall<double>(double_list, ABSL_ARRAYSIZE(double_list));
- TestIntegral<double, int64_t>(double_list, ABSL_ARRAYSIZE(double_list));
- TestIntegral<double, uint64_t>(double_list, ABSL_ARRAYSIZE(double_list));
-}
-
-} // namespace
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/base/call_once.h b/third_party/abseil-cpp/absl/base/call_once.h
deleted file mode 100644
index 96109f5..0000000
--- a/third_party/abseil-cpp/absl/base/call_once.h
+++ /dev/null
@@ -1,219 +0,0 @@
-// Copyright 2017 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.
-//
-// -----------------------------------------------------------------------------
-// File: call_once.h
-// -----------------------------------------------------------------------------
-//
-// This header file provides an Abseil version of `std::call_once` for invoking
-// a given function at most once, across all threads. This Abseil version is
-// faster than the C++11 version and incorporates the C++17 argument-passing
-// fix, so that (for example) non-const references may be passed to the invoked
-// function.
-
-#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/optimization.h"
-#include "absl/base/port.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-
-class once_flag;
-
-namespace base_internal {
-std::atomic<uint32_t>* ControlWord(absl::once_flag* flag);
-} // namespace base_internal
-
-// call_once()
-//
-// For all invocations using a given `once_flag`, invokes a given `fn` exactly
-// once across all threads. The first call to `call_once()` with a particular
-// `once_flag` argument (that does not throw an exception) will run the
-// specified function with the provided `args`; other calls with the same
-// `once_flag` argument will not run the function, but will wait
-// for the provided function to finish running (if it is still running).
-//
-// This mechanism provides a safe, simple, and fast mechanism for one-time
-// initialization in a multi-threaded process.
-//
-// Example:
-//
-// class MyInitClass {
-// public:
-// ...
-// mutable absl::once_flag once_;
-//
-// MyInitClass* init() const {
-// absl::call_once(once_, &MyInitClass::Init, this);
-// return ptr_;
-// }
-//
-template <typename Callable, typename... Args>
-void call_once(absl::once_flag& flag, Callable&& fn, Args&&... args);
-
-// once_flag
-//
-// Objects of this type are used to distinguish calls to `call_once()` and
-// ensure the provided function is only invoked once across all threads. This
-// type is not copyable or movable. However, it has a `constexpr`
-// constructor, and is safe to use as a namespace-scoped global variable.
-class once_flag {
- public:
- constexpr once_flag() : control_(0) {}
- once_flag(const once_flag&) = delete;
- once_flag& operator=(const once_flag&) = delete;
-
- private:
- friend std::atomic<uint32_t>* base_internal::ControlWord(once_flag* flag);
- std::atomic<uint32_t> control_;
-};
-
-//------------------------------------------------------------------------------
-// End of public interfaces.
-// Implementation details follow.
-//------------------------------------------------------------------------------
-
-namespace base_internal {
-
-// Like call_once, but uses KERNEL_ONLY scheduling. Intended to be used to
-// initialize entities used by the scheduler implementation.
-template <typename Callable, typename... Args>
-void LowLevelCallOnce(absl::once_flag* flag, Callable&& fn, Args&&... args);
-
-// Disables scheduling while on stack when scheduling mode is non-cooperative.
-// No effect for cooperative scheduling modes.
-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_;
-};
-
-// Bit patterns for call_once state machine values. Internal implementation
-// detail, not for use by clients.
-//
-// The bit patterns are arbitrarily chosen from unlikely values, to aid in
-// debugging. However, kOnceInit must be 0, so that a zero-initialized
-// once_flag will be valid for immediate use.
-enum {
- kOnceInit = 0,
- kOnceRunning = 0x65C2937B,
- kOnceWaiter = 0x05A308D2,
- // A very small constant is chosen for kOnceDone so that it fit in a single
- // compare with immediate instruction for most common ISAs. This is verified
- // for x86, POWER and ARM.
- kOnceDone = 221, // Random Number
-};
-
-template <typename Callable, typename... Args>
-ABSL_ATTRIBUTE_NOINLINE
-void CallOnceImpl(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)); // NOLINT
- }
- }
-#endif // NDEBUG
- static const base_internal::SpinLockWaitTransition trans[] = {
- {kOnceInit, kOnceRunning, true},
- {kOnceRunning, kOnceWaiter, false},
- {kOnceDone, kOnceDone, true}};
-
- // Must do this before potentially modifying control word's state.
- base_internal::SchedulingHelper maybe_disable_scheduling(scheduling_mode);
- // Short circuit the simplest case to avoid procedure call overhead.
- // The base_internal::SpinLockWait() call returns either kOnceInit or
- // kOnceDone. If it returns kOnceDone, it must have loaded the control word
- // with std::memory_order_acquire and seen a value of kOnceDone.
- 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);
- }
- } // else *control is already kOnceDone
-}
-
-inline std::atomic<uint32_t>* ControlWord(once_flag* flag) {
- return &flag->control_;
-}
-
-template <typename Callable, typename... Args>
-void LowLevelCallOnce(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)...);
- }
-}
-
-} // namespace base_internal
-
-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
-} // namespace absl
-
-#endif // ABSL_BASE_CALL_ONCE_H_
diff --git a/third_party/abseil-cpp/absl/base/call_once_test.cc b/third_party/abseil-cpp/absl/base/call_once_test.cc
deleted file mode 100644
index 11d26c4..0000000
--- a/third_party/abseil-cpp/absl/base/call_once_test.cc
+++ /dev/null
@@ -1,107 +0,0 @@
-// Copyright 2017 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/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;
-
-// Function to be called from absl::call_once. Waits for a notification.
-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();
-}
-
-// Returns true if all threads are set up for the test.
-bool ThreadsAreSetup(void*) ABSL_EXCLUSIVE_LOCKS_REQUIRED(counters_mu) {
- // All ten threads must be running, and WaitAndIncrement should be blocked.
- return running_thread_count == 10 && call_once_invoke_count == 1;
-}
-
-TEST(CallOnceTest, ExecutionCount) {
- std::vector<std::thread> threads;
-
- // Start 10 threads all calling call_once on the same once_flag.
- for (int i = 0; i < 10; ++i) {
- threads.emplace_back(ThreadBody);
- }
-
-
- // Wait until all ten threads have started, and WaitAndIncrement has been
- // invoked.
- counters_mu.LockWhen(Condition(ThreadsAreSetup, nullptr));
-
- // WaitAndIncrement should have been invoked by exactly one call_once()
- // instance. That thread should be blocking on a notification, and all other
- // call_once instances should be blocking as well.
- EXPECT_EQ(call_once_invoke_count, 1);
- EXPECT_EQ(call_once_finished_count, 0);
- EXPECT_EQ(call_once_return_count, 0);
-
- // Allow WaitAndIncrement to finish executing. Once it does, the other
- // call_once waiters will be unblocked.
- 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();
-}
-
-} // namespace
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/base/casts.h b/third_party/abseil-cpp/absl/base/casts.h
deleted file mode 100644
index b99adb0..0000000
--- a/third_party/abseil-cpp/absl/base/casts.h
+++ /dev/null
@@ -1,180 +0,0 @@
-//
-// Copyright 2017 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.
-//
-// -----------------------------------------------------------------------------
-// File: casts.h
-// -----------------------------------------------------------------------------
-//
-// This header file defines casting templates to fit use cases not covered by
-// the standard casts provided in the C++ standard. As with all cast operations,
-// use these with caution and only if alternatives do not exist.
-
-#ifndef ABSL_BASE_CASTS_H_
-#define ABSL_BASE_CASTS_H_
-
-#include <cstring>
-#include <memory>
-#include <type_traits>
-#include <utility>
-
-#if defined(__cpp_lib_bit_cast) && __cpp_lib_bit_cast >= 201806L
-#include <bit> // For std::bit_cast.
-#endif // defined(__cpp_lib_bit_cast) && __cpp_lib_bit_cast >= 201806L
-
-#include "absl/base/internal/identity.h"
-#include "absl/base/macros.h"
-#include "absl/meta/type_traits.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-
-// implicit_cast()
-//
-// Performs an implicit conversion between types following the language
-// rules for implicit conversion; if an implicit conversion is otherwise
-// allowed by the language in the given context, this function performs such an
-// implicit conversion.
-//
-// Example:
-//
-// // If the context allows implicit conversion:
-// From from;
-// To to = from;
-//
-// // Such code can be replaced by:
-// implicit_cast<To>(from);
-//
-// An `implicit_cast()` may also be used to annotate numeric type conversions
-// that, although safe, may produce compiler warnings (such as `long` to `int`).
-// Additionally, an `implicit_cast()` is also useful within return statements to
-// indicate a specific implicit conversion is being undertaken.
-//
-// Example:
-//
-// return implicit_cast<double>(size_in_bytes) / capacity_;
-//
-// Annotating code with `implicit_cast()` allows you to explicitly select
-// particular overloads and template instantiations, while providing a safer
-// cast than `reinterpret_cast()` or `static_cast()`.
-//
-// Additionally, an `implicit_cast()` can be used to allow upcasting within a
-// type hierarchy where incorrect use of `static_cast()` could accidentally
-// allow downcasting.
-//
-// Finally, an `implicit_cast()` can be used to perform implicit conversions
-// from unrelated types that otherwise couldn't be implicitly cast directly;
-// C++ will normally only implicitly cast "one step" in such conversions.
-//
-// That is, if C is a type which can be implicitly converted to B, with B being
-// a type that can be implicitly converted to A, an `implicit_cast()` can be
-// used to convert C to B (which the compiler can then implicitly convert to A
-// using language rules).
-//
-// Example:
-//
-// // Assume an object C is convertible to B, which is implicitly convertible
-// // to A
-// A a = implicit_cast<B>(C);
-//
-// Such implicit cast chaining may be useful within template logic.
-template <typename To>
-constexpr To implicit_cast(typename absl::internal::identity_t<To> to) {
- return to;
-}
-
-// bit_cast()
-//
-// Creates a value of the new type `Dest` whose representation is the same as
-// that of the argument, which is of (deduced) type `Source` (a "bitwise cast";
-// every bit in the value representation of the result is equal to the
-// corresponding bit in the object representation of the source). Source and
-// destination types must be of the same size, and both types must be trivially
-// copyable.
-//
-// As with most casts, use with caution. A `bit_cast()` might be needed when you
-// need to treat a value as the value of some other type, for example, to access
-// the individual bits of an object which are not normally accessible through
-// the object's type, such as for working with the binary representation of a
-// floating point value:
-//
-// float f = 3.14159265358979;
-// int i = bit_cast<int>(f);
-// // i = 0x40490fdb
-//
-// Reinterpreting and accessing a value directly as a different type (as shown
-// below) usually results in undefined behavior.
-//
-// Example:
-//
-// // WRONG
-// float f = 3.14159265358979;
-// int i = reinterpret_cast<int&>(f); // Wrong
-// int j = *reinterpret_cast<int*>(&f); // Equally wrong
-// int k = *bit_cast<int*>(&f); // Equally wrong
-//
-// Reinterpret-casting results in undefined behavior according to the ISO C++
-// specification, section [basic.lval]. Roughly, this section says: if an object
-// in memory has one type, and a program accesses it with a different type, the
-// result is undefined behavior for most "different type".
-//
-// Using bit_cast on a pointer and then dereferencing it is no better than using
-// reinterpret_cast. You should only use bit_cast on the value itself.
-//
-// Such casting results in type punning: holding an object in memory of one type
-// and reading its bits back using a different type. A `bit_cast()` avoids this
-// issue by copying the object representation to a new value, which avoids
-// introducing this undefined behavior (since the original value is never
-// accessed in the wrong way).
-//
-// The requirements of `absl::bit_cast` are more strict than that of
-// `std::bit_cast` unless compiler support is available. Specifically, without
-// compiler support, this implementation also requires `Dest` to be
-// default-constructible. In C++20, `absl::bit_cast` is replaced by
-// `std::bit_cast`.
-#if defined(__cpp_lib_bit_cast) && __cpp_lib_bit_cast >= 201806L
-
-using std::bit_cast;
-
-#else // defined(__cpp_lib_bit_cast) && __cpp_lib_bit_cast >= 201806L
-
-template <typename Dest, typename Source,
- typename std::enable_if<
- sizeof(Dest) == sizeof(Source) &&
- type_traits_internal::is_trivially_copyable<Source>::value &&
- type_traits_internal::is_trivially_copyable<Dest>::value
-#if !ABSL_HAVE_BUILTIN(__builtin_bit_cast)
- && std::is_default_constructible<Dest>::value
-#endif // !ABSL_HAVE_BUILTIN(__builtin_bit_cast)
- ,
- int>::type = 0>
-#if ABSL_HAVE_BUILTIN(__builtin_bit_cast)
-inline constexpr Dest bit_cast(const Source& source) {
- return __builtin_bit_cast(Dest, source);
-}
-#else // ABSL_HAVE_BUILTIN(__builtin_bit_cast)
-inline Dest bit_cast(const Source& source) {
- Dest dest;
- memcpy(static_cast<void*>(std::addressof(dest)),
- static_cast<const void*>(std::addressof(source)), sizeof(dest));
- return dest;
-}
-#endif // ABSL_HAVE_BUILTIN(__builtin_bit_cast)
-
-#endif // defined(__cpp_lib_bit_cast) && __cpp_lib_bit_cast >= 201806L
-
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_BASE_CASTS_H_
diff --git a/third_party/abseil-cpp/absl/base/config.h b/third_party/abseil-cpp/absl/base/config.h
deleted file mode 100644
index 1058ce7..0000000
--- a/third_party/abseil-cpp/absl/base/config.h
+++ /dev/null
@@ -1,931 +0,0 @@
-//
-// Copyright 2017 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.
-//
-// -----------------------------------------------------------------------------
-// File: config.h
-// -----------------------------------------------------------------------------
-//
-// This header file defines a set of macros for checking the presence of
-// important compiler and platform features. Such macros can be used to
-// produce portable code by parameterizing compilation based on the presence or
-// lack of a given feature.
-//
-// We define a "feature" as some interface we wish to program to: for example,
-// a library function or system call. A value of `1` indicates support for
-// that feature; any other value indicates the feature support is undefined.
-//
-// Example:
-//
-// Suppose a programmer wants to write a program that uses the 'mmap()' system
-// call. The Abseil macro for that feature (`ABSL_HAVE_MMAP`) allows you to
-// selectively include the `mmap.h` header and bracket code using that feature
-// in the macro:
-//
-// #include "absl/base/config.h"
-//
-// #ifdef ABSL_HAVE_MMAP
-// #include "sys/mman.h"
-// #endif //ABSL_HAVE_MMAP
-//
-// ...
-// #ifdef ABSL_HAVE_MMAP
-// void *ptr = mmap(...);
-// ...
-// #endif // ABSL_HAVE_MMAP
-
-#ifndef ABSL_BASE_CONFIG_H_
-#define ABSL_BASE_CONFIG_H_
-
-// Included for the __GLIBC__ macro (or similar macros on other systems).
-#include <limits.h>
-
-#ifdef __cplusplus
-// Included for __GLIBCXX__, _LIBCPP_VERSION
-#include <cstddef>
-#endif // __cplusplus
-
-// ABSL_INTERNAL_CPLUSPLUS_LANG
-//
-// MSVC does not set the value of __cplusplus correctly, but instead uses
-// _MSVC_LANG as a stand-in.
-// https://docs.microsoft.com/en-us/cpp/preprocessor/predefined-macros
-//
-// However, there are reports that MSVC even sets _MSVC_LANG incorrectly at
-// times, for example:
-// https://github.com/microsoft/vscode-cpptools/issues/1770
-// https://reviews.llvm.org/D70996
-//
-// For this reason, this symbol is considered INTERNAL and code outside of
-// Abseil must not use it.
-#if defined(_MSVC_LANG)
-#define ABSL_INTERNAL_CPLUSPLUS_LANG _MSVC_LANG
-#elif defined(__cplusplus)
-#define ABSL_INTERNAL_CPLUSPLUS_LANG __cplusplus
-#endif
-
-#if defined(__APPLE__)
-// Included for TARGET_OS_IPHONE, __IPHONE_OS_VERSION_MIN_REQUIRED,
-// __IPHONE_8_0.
-#include <Availability.h>
-#include <TargetConditionals.h>
-#endif
-
-#include "absl/base/options.h"
-#include "absl/base/policy_checks.h"
-
-// Abseil long-term support (LTS) releases will define
-// `ABSL_LTS_RELEASE_VERSION` to the integer representing the date string of the
-// LTS release version, and will define `ABSL_LTS_RELEASE_PATCH_LEVEL` to the
-// integer representing the patch-level for that release.
-//
-// For example, for LTS release version "20300401.2", this would give us
-// ABSL_LTS_RELEASE_VERSION == 20300401 && ABSL_LTS_RELEASE_PATCH_LEVEL == 2
-//
-// These symbols will not be defined in non-LTS code.
-//
-// Abseil recommends that clients live-at-head. Therefore, if you are using
-// these symbols to assert a minimum version requirement, we recommend you do it
-// as
-//
-// #if defined(ABSL_LTS_RELEASE_VERSION) && ABSL_LTS_RELEASE_VERSION < 20300401
-// #error Project foo requires Abseil LTS version >= 20300401
-// #endif
-//
-// The `defined(ABSL_LTS_RELEASE_VERSION)` part of the check excludes
-// live-at-head clients from the minimum version assertion.
-//
-// See https://abseil.io/about/releases for more information on Abseil release
-// management.
-//
-// LTS releases can be obtained from
-// https://github.com/abseil/abseil-cpp/releases.
-#undef ABSL_LTS_RELEASE_VERSION
-#undef ABSL_LTS_RELEASE_PATCH_LEVEL
-
-// Helper macro to convert a CPP variable to a string literal.
-#define ABSL_INTERNAL_DO_TOKEN_STR(x) #x
-#define ABSL_INTERNAL_TOKEN_STR(x) ABSL_INTERNAL_DO_TOKEN_STR(x)
-
-// -----------------------------------------------------------------------------
-// Abseil namespace annotations
-// -----------------------------------------------------------------------------
-
-// ABSL_NAMESPACE_BEGIN/ABSL_NAMESPACE_END
-//
-// An annotation placed at the beginning/end of each `namespace absl` scope.
-// This is used to inject an inline namespace.
-//
-// The proper way to write Abseil code in the `absl` namespace is:
-//
-// namespace absl {
-// ABSL_NAMESPACE_BEGIN
-//
-// void Foo(); // absl::Foo().
-//
-// ABSL_NAMESPACE_END
-// } // namespace absl
-//
-// Users of Abseil should not use these macros, because users of Abseil should
-// not write `namespace absl {` in their own code for any reason. (Abseil does
-// not support forward declarations of its own types, nor does it support
-// user-provided specialization of Abseil templates. Code that violates these
-// rules may be broken without warning.)
-#if !defined(ABSL_OPTION_USE_INLINE_NAMESPACE) || \
- !defined(ABSL_OPTION_INLINE_NAMESPACE_NAME)
-#error options.h is misconfigured.
-#endif
-
-// Check that ABSL_OPTION_INLINE_NAMESPACE_NAME is neither "head" nor ""
-#if defined(__cplusplus) && ABSL_OPTION_USE_INLINE_NAMESPACE == 1
-
-#define ABSL_INTERNAL_INLINE_NAMESPACE_STR \
- ABSL_INTERNAL_TOKEN_STR(ABSL_OPTION_INLINE_NAMESPACE_NAME)
-
-static_assert(ABSL_INTERNAL_INLINE_NAMESPACE_STR[0] != '\0',
- "options.h misconfigured: ABSL_OPTION_INLINE_NAMESPACE_NAME must "
- "not be empty.");
-static_assert(ABSL_INTERNAL_INLINE_NAMESPACE_STR[0] != 'h' ||
- ABSL_INTERNAL_INLINE_NAMESPACE_STR[1] != 'e' ||
- ABSL_INTERNAL_INLINE_NAMESPACE_STR[2] != 'a' ||
- ABSL_INTERNAL_INLINE_NAMESPACE_STR[3] != 'd' ||
- ABSL_INTERNAL_INLINE_NAMESPACE_STR[4] != '\0',
- "options.h misconfigured: ABSL_OPTION_INLINE_NAMESPACE_NAME must "
- "be changed to a new, unique identifier name.");
-
-#endif
-
-#if ABSL_OPTION_USE_INLINE_NAMESPACE == 0
-#define ABSL_NAMESPACE_BEGIN
-#define ABSL_NAMESPACE_END
-#define ABSL_INTERNAL_C_SYMBOL(x) x
-#elif ABSL_OPTION_USE_INLINE_NAMESPACE == 1
-#define ABSL_NAMESPACE_BEGIN \
- inline namespace ABSL_OPTION_INLINE_NAMESPACE_NAME {
-#define ABSL_NAMESPACE_END }
-#define ABSL_INTERNAL_C_SYMBOL_HELPER_2(x, v) x##_##v
-#define ABSL_INTERNAL_C_SYMBOL_HELPER_1(x, v) \
- ABSL_INTERNAL_C_SYMBOL_HELPER_2(x, v)
-#define ABSL_INTERNAL_C_SYMBOL(x) \
- ABSL_INTERNAL_C_SYMBOL_HELPER_1(x, ABSL_OPTION_INLINE_NAMESPACE_NAME)
-#else
-#error options.h is misconfigured.
-#endif
-
-// -----------------------------------------------------------------------------
-// Compiler Feature Checks
-// -----------------------------------------------------------------------------
-
-// ABSL_HAVE_BUILTIN()
-//
-// Checks whether the compiler supports a Clang Feature Checking Macro, and if
-// so, checks whether it supports the provided builtin function "x" where x
-// is one of the functions noted in
-// https://clang.llvm.org/docs/LanguageExtensions.html
-//
-// Note: Use this macro to avoid an extra level of #ifdef __has_builtin check.
-// http://releases.llvm.org/3.3/tools/clang/docs/LanguageExtensions.html
-#ifdef __has_builtin
-#define ABSL_HAVE_BUILTIN(x) __has_builtin(x)
-#else
-#define ABSL_HAVE_BUILTIN(x) 0
-#endif
-
-#ifdef __has_feature
-#define ABSL_HAVE_FEATURE(f) __has_feature(f)
-#else
-#define ABSL_HAVE_FEATURE(f) 0
-#endif
-
-// Portable check for GCC minimum version:
-// https://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html
-#if defined(__GNUC__) && defined(__GNUC_MINOR__)
-#define ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(x, y) \
- (__GNUC__ > (x) || __GNUC__ == (x) && __GNUC_MINOR__ >= (y))
-#else
-#define ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(x, y) 0
-#endif
-
-#if defined(__clang__) && defined(__clang_major__) && defined(__clang_minor__)
-#define ABSL_INTERNAL_HAVE_MIN_CLANG_VERSION(x, y) \
- (__clang_major__ > (x) || __clang_major__ == (x) && __clang_minor__ >= (y))
-#else
-#define ABSL_INTERNAL_HAVE_MIN_CLANG_VERSION(x, y) 0
-#endif
-
-// ABSL_HAVE_TLS is defined to 1 when __thread should be supported.
-// We assume __thread is supported on Linux or Asylo when compiled with Clang or
-// compiled against libstdc++ with _GLIBCXX_HAVE_TLS defined.
-#ifdef ABSL_HAVE_TLS
-#error ABSL_HAVE_TLS cannot be directly set
-#elif (defined(__linux__) || defined(__ASYLO__)) && \
- (defined(__clang__) || defined(_GLIBCXX_HAVE_TLS))
-#define ABSL_HAVE_TLS 1
-#endif
-
-// ABSL_HAVE_STD_IS_TRIVIALLY_DESTRUCTIBLE
-//
-// Checks whether `std::is_trivially_destructible<T>` is supported.
-//
-// Notes: All supported compilers using libc++ support this feature, as does
-// gcc >= 4.8.1 using libstdc++, and Visual Studio.
-#ifdef ABSL_HAVE_STD_IS_TRIVIALLY_DESTRUCTIBLE
-#error ABSL_HAVE_STD_IS_TRIVIALLY_DESTRUCTIBLE cannot be directly set
-#elif defined(_LIBCPP_VERSION) || defined(_MSC_VER) || \
- (defined(__clang__) && __clang_major__ >= 15) || \
- (!defined(__clang__) && defined(__GLIBCXX__) && \
- ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(4, 8))
-#define ABSL_HAVE_STD_IS_TRIVIALLY_DESTRUCTIBLE 1
-#endif
-
-// ABSL_HAVE_STD_IS_TRIVIALLY_CONSTRUCTIBLE
-//
-// Checks whether `std::is_trivially_default_constructible<T>` and
-// `std::is_trivially_copy_constructible<T>` are supported.
-
-// ABSL_HAVE_STD_IS_TRIVIALLY_ASSIGNABLE
-//
-// Checks whether `std::is_trivially_copy_assignable<T>` is supported.
-
-// Notes: Clang with libc++ supports these features, as does gcc >= 7.4 with
-// libstdc++, or gcc >= 8.2 with libc++, and Visual Studio (but not NVCC).
-#if defined(ABSL_HAVE_STD_IS_TRIVIALLY_CONSTRUCTIBLE)
-#error ABSL_HAVE_STD_IS_TRIVIALLY_CONSTRUCTIBLE cannot be directly set
-#elif defined(ABSL_HAVE_STD_IS_TRIVIALLY_ASSIGNABLE)
-#error ABSL_HAVE_STD_IS_TRIVIALLY_ASSIGNABLE cannot directly set
-#elif (defined(__clang__) && defined(_LIBCPP_VERSION)) || \
- (defined(__clang__) && __clang_major__ >= 15) || \
- (!defined(__clang__) && \
- ((ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(7, 4) && defined(__GLIBCXX__)) || \
- (ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(8, 2) && \
- defined(_LIBCPP_VERSION)))) || \
- (defined(_MSC_VER) && !defined(__NVCC__) && !defined(__clang__))
-#define ABSL_HAVE_STD_IS_TRIVIALLY_CONSTRUCTIBLE 1
-#define ABSL_HAVE_STD_IS_TRIVIALLY_ASSIGNABLE 1
-#endif
-
-// ABSL_HAVE_STD_IS_TRIVIALLY_COPYABLE
-//
-// Checks whether `std::is_trivially_copyable<T>` is supported.
-//
-// Notes: Clang 15+ with libc++ supports these features, GCC hasn't been tested.
-#if defined(ABSL_HAVE_STD_IS_TRIVIALLY_COPYABLE)
-#error ABSL_HAVE_STD_IS_TRIVIALLY_COPYABLE cannot be directly set
-#elif defined(__clang__) && (__clang_major__ >= 15)
-#define ABSL_HAVE_STD_IS_TRIVIALLY_COPYABLE 1
-#endif
-
-// ABSL_HAVE_THREAD_LOCAL
-//
-// Checks whether C++11's `thread_local` storage duration specifier is
-// supported.
-#ifdef ABSL_HAVE_THREAD_LOCAL
-#error ABSL_HAVE_THREAD_LOCAL cannot be directly set
-#elif defined(__APPLE__)
-// Notes:
-// * Xcode's clang did not support `thread_local` until version 8, and
-// even then not for all iOS < 9.0.
-// * Xcode 9.3 started disallowing `thread_local` for 32-bit iOS simulator
-// targeting iOS 9.x.
-// * Xcode 10 moves the deployment target check for iOS < 9.0 to link time
-// making ABSL_HAVE_FEATURE unreliable there.
-//
-#if ABSL_HAVE_FEATURE(cxx_thread_local) && \
- !(TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_9_0)
-#define ABSL_HAVE_THREAD_LOCAL 1
-#endif
-#else // !defined(__APPLE__)
-#define ABSL_HAVE_THREAD_LOCAL 1
-#endif
-
-// There are platforms for which TLS should not be used even though the compiler
-// makes it seem like it's supported (Android NDK < r12b for example).
-// This is primarily because of linker problems and toolchain misconfiguration:
-// Abseil does not intend to support this indefinitely. Currently, the newest
-// toolchain that we intend to support that requires this behavior is the
-// r11 NDK - allowing for a 5 year support window on that means this option
-// is likely to be removed around June of 2021.
-// TLS isn't supported until NDK r12b per
-// https://developer.android.com/ndk/downloads/revision_history.html
-// Since NDK r16, `__NDK_MAJOR__` and `__NDK_MINOR__` are defined in
-// <android/ndk-version.h>. For NDK < r16, users should define these macros,
-// e.g. `-D__NDK_MAJOR__=11 -D__NKD_MINOR__=0` for NDK r11.
-#if defined(__ANDROID__) && defined(__clang__)
-#if __has_include(<android/ndk-version.h>)
-#include <android/ndk-version.h>
-#endif // __has_include(<android/ndk-version.h>)
-#if defined(__ANDROID__) && defined(__clang__) && defined(__NDK_MAJOR__) && \
- defined(__NDK_MINOR__) && \
- ((__NDK_MAJOR__ < 12) || ((__NDK_MAJOR__ == 12) && (__NDK_MINOR__ < 1)))
-#undef ABSL_HAVE_TLS
-#undef ABSL_HAVE_THREAD_LOCAL
-#endif
-#endif // defined(__ANDROID__) && defined(__clang__)
-
-// ABSL_HAVE_INTRINSIC_INT128
-//
-// Checks whether the __int128 compiler extension for a 128-bit integral type is
-// supported.
-//
-// Note: __SIZEOF_INT128__ is defined by Clang and GCC when __int128 is
-// supported, but we avoid using it in certain cases:
-// * On Clang:
-// * Building using Clang for Windows, where the Clang runtime library has
-// 128-bit support only on LP64 architectures, but Windows is LLP64.
-// * On Nvidia's nvcc:
-// * nvcc also defines __GNUC__ and __SIZEOF_INT128__, but not all versions
-// actually support __int128.
-#ifdef ABSL_HAVE_INTRINSIC_INT128
-#error ABSL_HAVE_INTRINSIC_INT128 cannot be directly set
-#elif defined(__SIZEOF_INT128__)
-#if (defined(__clang__) && !defined(_WIN32)) || \
- (defined(__CUDACC__) && __CUDACC_VER_MAJOR__ >= 9) || \
- (defined(__GNUC__) && !defined(__clang__) && !defined(__CUDACC__))
-#define ABSL_HAVE_INTRINSIC_INT128 1
-#elif defined(__CUDACC__)
-// __CUDACC_VER__ is a full version number before CUDA 9, and is defined to a
-// string explaining that it has been removed starting with CUDA 9. We use
-// nested #ifs because there is no short-circuiting in the preprocessor.
-// NOTE: `__CUDACC__` could be undefined while `__CUDACC_VER__` is defined.
-#if __CUDACC_VER__ >= 70000
-#define ABSL_HAVE_INTRINSIC_INT128 1
-#endif // __CUDACC_VER__ >= 70000
-#endif // defined(__CUDACC__)
-#endif // ABSL_HAVE_INTRINSIC_INT128
-
-// ABSL_HAVE_EXCEPTIONS
-//
-// Checks whether the compiler both supports and enables exceptions. Many
-// compilers support a "no exceptions" mode that disables exceptions.
-//
-// Generally, when ABSL_HAVE_EXCEPTIONS is not defined:
-//
-// * Code using `throw` and `try` may not compile.
-// * The `noexcept` specifier will still compile and behave as normal.
-// * The `noexcept` operator may still return `false`.
-//
-// For further details, consult the compiler's documentation.
-#ifdef ABSL_HAVE_EXCEPTIONS
-#error ABSL_HAVE_EXCEPTIONS cannot be directly set.
-#elif ABSL_INTERNAL_HAVE_MIN_CLANG_VERSION(3, 6)
-// Clang >= 3.6
-#if ABSL_HAVE_FEATURE(cxx_exceptions)
-#define ABSL_HAVE_EXCEPTIONS 1
-#endif // ABSL_HAVE_FEATURE(cxx_exceptions)
-#elif defined(__clang__)
-// Clang < 3.6
-// http://releases.llvm.org/3.6.0/tools/clang/docs/ReleaseNotes.html#the-exceptions-macro
-#if defined(__EXCEPTIONS) && ABSL_HAVE_FEATURE(cxx_exceptions)
-#define ABSL_HAVE_EXCEPTIONS 1
-#endif // defined(__EXCEPTIONS) && ABSL_HAVE_FEATURE(cxx_exceptions)
-// Handle remaining special cases and default to exceptions being supported.
-#elif !(defined(__GNUC__) && (__GNUC__ < 5) && !defined(__EXCEPTIONS)) && \
- !(ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(5, 0) && \
- !defined(__cpp_exceptions)) && \
- !(defined(_MSC_VER) && !defined(_CPPUNWIND))
-#define ABSL_HAVE_EXCEPTIONS 1
-#endif
-
-// -----------------------------------------------------------------------------
-// Platform Feature Checks
-// -----------------------------------------------------------------------------
-
-// Currently supported operating systems and associated preprocessor
-// symbols:
-//
-// Linux and Linux-derived __linux__
-// Android __ANDROID__ (implies __linux__)
-// Linux (non-Android) __linux__ && !__ANDROID__
-// Darwin (macOS and iOS) __APPLE__
-// Akaros (http://akaros.org) __ros__
-// Windows _WIN32
-// NaCL __native_client__
-// AsmJS __asmjs__
-// WebAssembly __wasm__
-// Fuchsia __Fuchsia__
-//
-// Note that since Android defines both __ANDROID__ and __linux__, one
-// may probe for either Linux or Android by simply testing for __linux__.
-
-// ABSL_HAVE_MMAP
-//
-// Checks whether the platform has an mmap(2) implementation as defined in
-// POSIX.1-2001.
-#ifdef ABSL_HAVE_MMAP
-#error ABSL_HAVE_MMAP cannot be directly set
-#elif defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || \
- defined(_AIX) || defined(__ros__) || defined(__native_client__) || \
- defined(__asmjs__) || defined(__wasm__) || defined(__Fuchsia__) || \
- defined(__sun) || defined(__ASYLO__) || defined(__myriad2__) || \
- defined(__HAIKU__) || defined(__OpenBSD__) || defined(__NetBSD__) || \
- defined(__QNX__)
-#define ABSL_HAVE_MMAP 1
-#endif
-
-// ABSL_HAVE_PTHREAD_GETSCHEDPARAM
-//
-// Checks whether the platform implements the pthread_(get|set)schedparam(3)
-// functions as defined in POSIX.1-2001.
-#ifdef ABSL_HAVE_PTHREAD_GETSCHEDPARAM
-#error ABSL_HAVE_PTHREAD_GETSCHEDPARAM cannot be directly set
-#elif defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || \
- defined(_AIX) || defined(__ros__) || defined(__OpenBSD__) || \
- defined(__NetBSD__)
-#define ABSL_HAVE_PTHREAD_GETSCHEDPARAM 1
-#endif
-
-// ABSL_HAVE_SCHED_GETCPU
-//
-// Checks whether sched_getcpu is available.
-#ifdef ABSL_HAVE_SCHED_GETCPU
-#error ABSL_HAVE_SCHED_GETCPU cannot be directly set
-#elif defined(__linux__)
-#define ABSL_HAVE_SCHED_GETCPU 1
-#endif
-
-// ABSL_HAVE_SCHED_YIELD
-//
-// Checks whether the platform implements sched_yield(2) as defined in
-// POSIX.1-2001.
-#ifdef ABSL_HAVE_SCHED_YIELD
-#error ABSL_HAVE_SCHED_YIELD cannot be directly set
-#elif defined(__linux__) || defined(__ros__) || defined(__native_client__)
-#define ABSL_HAVE_SCHED_YIELD 1
-#endif
-
-// ABSL_HAVE_SEMAPHORE_H
-//
-// Checks whether the platform supports the <semaphore.h> header and sem_init(3)
-// family of functions as standardized in POSIX.1-2001.
-//
-// Note: While Apple provides <semaphore.h> for both iOS and macOS, it is
-// explicitly deprecated and will cause build failures if enabled for those
-// platforms. We side-step the issue by not defining it here for Apple
-// platforms.
-#ifdef ABSL_HAVE_SEMAPHORE_H
-#error ABSL_HAVE_SEMAPHORE_H cannot be directly set
-#elif defined(__linux__) || defined(__ros__)
-#define ABSL_HAVE_SEMAPHORE_H 1
-#endif
-
-// ABSL_HAVE_ALARM
-//
-// Checks whether the platform supports the <signal.h> header and alarm(2)
-// function as standardized in POSIX.1-2001.
-#ifdef ABSL_HAVE_ALARM
-#error ABSL_HAVE_ALARM cannot be directly set
-#elif defined(__GOOGLE_GRTE_VERSION__)
-// feature tests for Google's GRTE
-#define ABSL_HAVE_ALARM 1
-#elif defined(__GLIBC__)
-// feature test for glibc
-#define ABSL_HAVE_ALARM 1
-#elif defined(_MSC_VER)
-// feature tests for Microsoft's library
-#elif defined(__MINGW32__)
-// mingw32 doesn't provide alarm(2):
-// https://osdn.net/projects/mingw/scm/git/mingw-org-wsl/blobs/5.2-trunk/mingwrt/include/unistd.h
-// mingw-w64 provides a no-op implementation:
-// https://sourceforge.net/p/mingw-w64/mingw-w64/ci/master/tree/mingw-w64-crt/misc/alarm.c
-#elif defined(__EMSCRIPTEN__)
-// emscripten doesn't support signals
-#elif defined(__Fuchsia__)
-// Signals don't exist on fuchsia.
-#elif defined(__native_client__)
-#else
-// other standard libraries
-#define ABSL_HAVE_ALARM 1
-#endif
-
-// ABSL_IS_LITTLE_ENDIAN
-// ABSL_IS_BIG_ENDIAN
-//
-// Checks the endianness of the platform.
-//
-// Notes: uses the built in endian macros provided by GCC (since 4.6) and
-// Clang (since 3.2); see
-// https://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html.
-// Otherwise, if _WIN32, assume little endian. Otherwise, bail with an error.
-#if defined(ABSL_IS_BIG_ENDIAN)
-#error "ABSL_IS_BIG_ENDIAN cannot be directly set."
-#endif
-#if defined(ABSL_IS_LITTLE_ENDIAN)
-#error "ABSL_IS_LITTLE_ENDIAN cannot be directly set."
-#endif
-
-#if (defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && \
- __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
-#define ABSL_IS_LITTLE_ENDIAN 1
-#elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && \
- __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
-#define ABSL_IS_BIG_ENDIAN 1
-#elif defined(_WIN32)
-#define ABSL_IS_LITTLE_ENDIAN 1
-#else
-#error "absl endian detection needs to be set up for your compiler"
-#endif
-
-// macOS < 10.13 and iOS < 11 don't let you use <any>, <optional>, or <variant>
-// even though the headers exist and are publicly noted to work, because the
-// libc++ shared library shipped on the system doesn't have the requisite
-// exported symbols. See https://github.com/abseil/abseil-cpp/issues/207 and
-// https://developer.apple.com/documentation/xcode_release_notes/xcode_10_release_notes
-//
-// libc++ spells out the availability requirements in the file
-// llvm-project/libcxx/include/__config via the #define
-// _LIBCPP_AVAILABILITY_BAD_OPTIONAL_ACCESS.
-//
-// Unfortunately, Apple initially mis-stated the requirements as macOS < 10.14
-// and iOS < 12 in the libc++ headers. This was corrected by
-// https://github.com/llvm/llvm-project/commit/7fb40e1569dd66292b647f4501b85517e9247953
-// which subsequently made it into the XCode 12.5 release. We need to match the
-// old (incorrect) conditions when built with old XCode, but can use the
-// corrected earlier versions with new XCode.
-#if defined(__APPLE__) && defined(_LIBCPP_VERSION) && \
- ((_LIBCPP_VERSION >= 11000 && /* XCode 12.5 or later: */ \
- ((defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && \
- __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 101300) || \
- (defined(__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__) && \
- __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ < 110000) || \
- (defined(__ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__) && \
- __ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__ < 40000) || \
- (defined(__ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__) && \
- __ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__ < 110000))) || \
- (_LIBCPP_VERSION < 11000 && /* Pre-XCode 12.5: */ \
- ((defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && \
- __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 101400) || \
- (defined(__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__) && \
- __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ < 120000) || \
- (defined(__ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__) && \
- __ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__ < 50000) || \
- (defined(__ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__) && \
- __ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__ < 120000))))
-#define ABSL_INTERNAL_APPLE_CXX17_TYPES_UNAVAILABLE 1
-#else
-#define ABSL_INTERNAL_APPLE_CXX17_TYPES_UNAVAILABLE 0
-#endif
-
-// ABSL_HAVE_STD_ANY
-//
-// Checks whether C++17 std::any is available by checking whether <any> exists.
-#ifdef ABSL_HAVE_STD_ANY
-#error "ABSL_HAVE_STD_ANY cannot be directly set."
-#endif
-
-#ifdef __has_include
-#if __has_include(<any>) && defined(__cplusplus) && __cplusplus >= 201703L && \
- !ABSL_INTERNAL_APPLE_CXX17_TYPES_UNAVAILABLE
-#define ABSL_HAVE_STD_ANY 1
-#endif
-#endif
-
-// ABSL_HAVE_STD_OPTIONAL
-//
-// Checks whether C++17 std::optional is available.
-#ifdef ABSL_HAVE_STD_OPTIONAL
-#error "ABSL_HAVE_STD_OPTIONAL cannot be directly set."
-#endif
-
-#ifdef __has_include
-#if __has_include(<optional>) && defined(__cplusplus) && \
- __cplusplus >= 201703L && !ABSL_INTERNAL_APPLE_CXX17_TYPES_UNAVAILABLE
-#define ABSL_HAVE_STD_OPTIONAL 1
-#endif
-#endif
-
-// ABSL_HAVE_STD_VARIANT
-//
-// Checks whether C++17 std::variant is available.
-#ifdef ABSL_HAVE_STD_VARIANT
-#error "ABSL_HAVE_STD_VARIANT cannot be directly set."
-#endif
-
-#ifdef __has_include
-#if __has_include(<variant>) && defined(__cplusplus) && \
- __cplusplus >= 201703L && !ABSL_INTERNAL_APPLE_CXX17_TYPES_UNAVAILABLE
-#define ABSL_HAVE_STD_VARIANT 1
-#endif
-#endif
-
-// ABSL_HAVE_STD_STRING_VIEW
-//
-// Checks whether C++17 std::string_view is available.
-#ifdef ABSL_HAVE_STD_STRING_VIEW
-#error "ABSL_HAVE_STD_STRING_VIEW cannot be directly set."
-#endif
-
-#ifdef __has_include
-#if __has_include(<string_view>) && defined(__cplusplus) && \
- __cplusplus >= 201703L
-#define ABSL_HAVE_STD_STRING_VIEW 1
-#endif
-#endif
-
-// For MSVC, `__has_include` is supported in VS 2017 15.3, which is later than
-// the support for <optional>, <any>, <string_view>, <variant>. So we use
-// _MSC_VER to check whether we have VS 2017 RTM (when <optional>, <any>,
-// <string_view>, <variant> is implemented) or higher. Also, `__cplusplus` is
-// not correctly set by MSVC, so we use `_MSVC_LANG` to check the language
-// version.
-// TODO(zhangxy): fix tests before enabling aliasing for `std::any`.
-#if defined(_MSC_VER) && _MSC_VER >= 1910 && \
- ((defined(_MSVC_LANG) && _MSVC_LANG > 201402) || \
- (defined(__cplusplus) && __cplusplus > 201402))
-// #define ABSL_HAVE_STD_ANY 1
-#define ABSL_HAVE_STD_OPTIONAL 1
-#define ABSL_HAVE_STD_VARIANT 1
-#define ABSL_HAVE_STD_STRING_VIEW 1
-#endif
-
-// ABSL_USES_STD_ANY
-//
-// Indicates whether absl::any is an alias for std::any.
-#if !defined(ABSL_OPTION_USE_STD_ANY)
-#error options.h is misconfigured.
-#elif ABSL_OPTION_USE_STD_ANY == 0 || \
- (ABSL_OPTION_USE_STD_ANY == 2 && !defined(ABSL_HAVE_STD_ANY))
-#undef ABSL_USES_STD_ANY
-#elif ABSL_OPTION_USE_STD_ANY == 1 || \
- (ABSL_OPTION_USE_STD_ANY == 2 && defined(ABSL_HAVE_STD_ANY))
-#define ABSL_USES_STD_ANY 1
-#else
-#error options.h is misconfigured.
-#endif
-
-// ABSL_USES_STD_OPTIONAL
-//
-// Indicates whether absl::optional is an alias for std::optional.
-#if !defined(ABSL_OPTION_USE_STD_OPTIONAL)
-#error options.h is misconfigured.
-#elif ABSL_OPTION_USE_STD_OPTIONAL == 0 || \
- (ABSL_OPTION_USE_STD_OPTIONAL == 2 && !defined(ABSL_HAVE_STD_OPTIONAL))
-#undef ABSL_USES_STD_OPTIONAL
-#elif ABSL_OPTION_USE_STD_OPTIONAL == 1 || \
- (ABSL_OPTION_USE_STD_OPTIONAL == 2 && defined(ABSL_HAVE_STD_OPTIONAL))
-#define ABSL_USES_STD_OPTIONAL 1
-#else
-#error options.h is misconfigured.
-#endif
-
-// ABSL_USES_STD_VARIANT
-//
-// Indicates whether absl::variant is an alias for std::variant.
-#if !defined(ABSL_OPTION_USE_STD_VARIANT)
-#error options.h is misconfigured.
-#elif ABSL_OPTION_USE_STD_VARIANT == 0 || \
- (ABSL_OPTION_USE_STD_VARIANT == 2 && !defined(ABSL_HAVE_STD_VARIANT))
-#undef ABSL_USES_STD_VARIANT
-#elif ABSL_OPTION_USE_STD_VARIANT == 1 || \
- (ABSL_OPTION_USE_STD_VARIANT == 2 && defined(ABSL_HAVE_STD_VARIANT))
-#define ABSL_USES_STD_VARIANT 1
-#else
-#error options.h is misconfigured.
-#endif
-
-// ABSL_USES_STD_STRING_VIEW
-//
-// Indicates whether absl::string_view is an alias for std::string_view.
-#if !defined(ABSL_OPTION_USE_STD_STRING_VIEW)
-#error options.h is misconfigured.
-#elif ABSL_OPTION_USE_STD_STRING_VIEW == 0 || \
- (ABSL_OPTION_USE_STD_STRING_VIEW == 2 && \
- !defined(ABSL_HAVE_STD_STRING_VIEW))
-#undef ABSL_USES_STD_STRING_VIEW
-#elif ABSL_OPTION_USE_STD_STRING_VIEW == 1 || \
- (ABSL_OPTION_USE_STD_STRING_VIEW == 2 && \
- defined(ABSL_HAVE_STD_STRING_VIEW))
-#define ABSL_USES_STD_STRING_VIEW 1
-#else
-#error options.h is misconfigured.
-#endif
-
-// In debug mode, MSVC 2017's std::variant throws a EXCEPTION_ACCESS_VIOLATION
-// SEH exception from emplace for variant<SomeStruct> when constructing the
-// struct can throw. This defeats some of variant_test and
-// variant_exception_safety_test.
-#if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_DEBUG)
-#define ABSL_INTERNAL_MSVC_2017_DBG_MODE
-#endif
-
-// ABSL_INTERNAL_MANGLED_NS
-// ABSL_INTERNAL_MANGLED_BACKREFERENCE
-//
-// Internal macros for building up mangled names in our internal fork of CCTZ.
-// This implementation detail is only needed and provided for the MSVC build.
-//
-// These macros both expand to string literals. ABSL_INTERNAL_MANGLED_NS is
-// the mangled spelling of the `absl` namespace, and
-// ABSL_INTERNAL_MANGLED_BACKREFERENCE is a back-reference integer representing
-// the proper count to skip past the CCTZ fork namespace names. (This number
-// is one larger when there is an inline namespace name to skip.)
-#if defined(_MSC_VER)
-#if ABSL_OPTION_USE_INLINE_NAMESPACE == 0
-#define ABSL_INTERNAL_MANGLED_NS "absl"
-#define ABSL_INTERNAL_MANGLED_BACKREFERENCE "5"
-#else
-#define ABSL_INTERNAL_MANGLED_NS \
- ABSL_INTERNAL_TOKEN_STR(ABSL_OPTION_INLINE_NAMESPACE_NAME) "@absl"
-#define ABSL_INTERNAL_MANGLED_BACKREFERENCE "6"
-#endif
-#endif
-
-// ABSL_DLL
-//
-// When building Abseil as a DLL, this macro expands to `__declspec(dllexport)`
-// so we can annotate symbols appropriately as being exported. When used in
-// headers consuming a DLL, this macro expands to `__declspec(dllimport)` so
-// that consumers know the symbol is defined inside the DLL. In all other cases,
-// the macro expands to nothing.
-#if defined(_MSC_VER)
-#if defined(ABSL_BUILD_DLL)
-#define ABSL_DLL __declspec(dllexport)
-#elif defined(ABSL_CONSUME_DLL)
-#define ABSL_DLL __declspec(dllimport)
-#else
-#define ABSL_DLL
-#endif
-#else
-#define ABSL_DLL
-#endif // defined(_MSC_VER)
-
-// ABSL_HAVE_MEMORY_SANITIZER
-//
-// MemorySanitizer (MSan) is a detector of uninitialized reads. It consists of
-// a compiler instrumentation module and a run-time library.
-#ifdef ABSL_HAVE_MEMORY_SANITIZER
-#error "ABSL_HAVE_MEMORY_SANITIZER cannot be directly set."
-#elif !defined(__native_client__) && ABSL_HAVE_FEATURE(memory_sanitizer)
-#define ABSL_HAVE_MEMORY_SANITIZER 1
-#endif
-
-// ABSL_HAVE_THREAD_SANITIZER
-//
-// ThreadSanitizer (TSan) is a fast data race detector.
-#ifdef ABSL_HAVE_THREAD_SANITIZER
-#error "ABSL_HAVE_THREAD_SANITIZER cannot be directly set."
-#elif defined(__SANITIZE_THREAD__)
-#define ABSL_HAVE_THREAD_SANITIZER 1
-#elif ABSL_HAVE_FEATURE(thread_sanitizer)
-#define ABSL_HAVE_THREAD_SANITIZER 1
-#endif
-
-// ABSL_HAVE_ADDRESS_SANITIZER
-//
-// AddressSanitizer (ASan) is a fast memory error detector.
-#ifdef ABSL_HAVE_ADDRESS_SANITIZER
-#error "ABSL_HAVE_ADDRESS_SANITIZER cannot be directly set."
-#elif defined(__SANITIZE_ADDRESS__)
-#define ABSL_HAVE_ADDRESS_SANITIZER 1
-#elif ABSL_HAVE_FEATURE(address_sanitizer)
-#define ABSL_HAVE_ADDRESS_SANITIZER 1
-#endif
-
-// ABSL_HAVE_HWADDRESS_SANITIZER
-//
-// Hardware-Assisted AddressSanitizer (or HWASAN) is even faster than asan
-// memory error detector which can use CPU features like ARM TBI, Intel LAM or
-// AMD UAI.
-#ifdef ABSL_HAVE_HWADDRESS_SANITIZER
-#error "ABSL_HAVE_HWADDRESS_SANITIZER cannot be directly set."
-#elif defined(__SANITIZE_HWADDRESS__)
-#define ABSL_HAVE_HWADDRESS_SANITIZER 1
-#elif ABSL_HAVE_FEATURE(hwaddress_sanitizer)
-#define ABSL_HAVE_HWADDRESS_SANITIZER 1
-#endif
-
-// ABSL_HAVE_LEAK_SANITIZER
-//
-// LeakSanitizer (or lsan) is a detector of memory leaks.
-// https://clang.llvm.org/docs/LeakSanitizer.html
-// https://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer
-//
-// The macro ABSL_HAVE_LEAK_SANITIZER can be used to detect at compile-time
-// whether the LeakSanitizer is potentially available. However, just because the
-// LeakSanitizer is available does not mean it is active. Use the
-// always-available run-time interface in //absl/debugging/leak_check.h for
-// interacting with LeakSanitizer.
-#ifdef ABSL_HAVE_LEAK_SANITIZER
-#error "ABSL_HAVE_LEAK_SANITIZER cannot be directly set."
-#elif defined(LEAK_SANITIZER)
-// GCC provides no method for detecting the presense of the standalone
-// LeakSanitizer (-fsanitize=leak), so GCC users of -fsanitize=leak should also
-// use -DLEAK_SANITIZER.
-#define ABSL_HAVE_LEAK_SANITIZER 1
-// Clang standalone LeakSanitizer (-fsanitize=leak)
-#elif ABSL_HAVE_FEATURE(leak_sanitizer)
-#define ABSL_HAVE_LEAK_SANITIZER 1
-#elif defined(ABSL_HAVE_ADDRESS_SANITIZER)
-// GCC or Clang using the LeakSanitizer integrated into AddressSanitizer.
-#define ABSL_HAVE_LEAK_SANITIZER 1
-#endif
-
-// ABSL_HAVE_CLASS_TEMPLATE_ARGUMENT_DEDUCTION
-//
-// Class template argument deduction is a language feature added in C++17.
-#ifdef ABSL_HAVE_CLASS_TEMPLATE_ARGUMENT_DEDUCTION
-#error "ABSL_HAVE_CLASS_TEMPLATE_ARGUMENT_DEDUCTION cannot be directly set."
-#elif defined(__cpp_deduction_guides)
-#define ABSL_HAVE_CLASS_TEMPLATE_ARGUMENT_DEDUCTION 1
-#endif
-
-// ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL
-//
-// Prior to C++17, static constexpr variables defined in classes required a
-// separate definition outside of the class body, for example:
-//
-// class Foo {
-// static constexpr int kBar = 0;
-// };
-// constexpr int Foo::kBar;
-//
-// In C++17, these variables defined in classes are considered inline variables,
-// and the extra declaration is redundant. Since some compilers warn on the
-// extra declarations, ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL can be used
-// conditionally ignore them:
-//
-// #ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL
-// constexpr int Foo::kBar;
-// #endif
-#if defined(ABSL_INTERNAL_CPLUSPLUS_LANG) && \
- ABSL_INTERNAL_CPLUSPLUS_LANG < 201703L
-#define ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL 1
-#endif
-
-// `ABSL_INTERNAL_HAS_RTTI` determines whether abseil is being compiled with
-// RTTI support.
-#ifdef ABSL_INTERNAL_HAS_RTTI
-#error ABSL_INTERNAL_HAS_RTTI cannot be directly set
-#elif !defined(__GNUC__) || defined(__GXX_RTTI)
-#define ABSL_INTERNAL_HAS_RTTI 1
-#endif // !defined(__GNUC__) || defined(__GXX_RTTI)
-
-// ABSL_INTERNAL_HAVE_SSE is used for compile-time detection of SSE support.
-// See https://gcc.gnu.org/onlinedocs/gcc/x86-Options.html for an overview of
-// which architectures support the various x86 instruction sets.
-#ifdef ABSL_INTERNAL_HAVE_SSE
-#error ABSL_INTERNAL_HAVE_SSE cannot be directly set
-#elif defined(__SSE__)
-#define ABSL_INTERNAL_HAVE_SSE 1
-#elif defined(_M_X64) || (defined(_M_IX86_FP) && _M_IX86_FP >= 1)
-// MSVC only defines _M_IX86_FP for x86 32-bit code, and _M_IX86_FP >= 1
-// indicates that at least SSE was targeted with the /arch:SSE option.
-// All x86-64 processors support SSE, so support can be assumed.
-// https://docs.microsoft.com/en-us/cpp/preprocessor/predefined-macros
-#define ABSL_INTERNAL_HAVE_SSE 1
-#endif
-
-// ABSL_INTERNAL_HAVE_SSE2 is used for compile-time detection of SSE2 support.
-// See https://gcc.gnu.org/onlinedocs/gcc/x86-Options.html for an overview of
-// which architectures support the various x86 instruction sets.
-#ifdef ABSL_INTERNAL_HAVE_SSE2
-#error ABSL_INTERNAL_HAVE_SSE2 cannot be directly set
-#elif defined(__SSE2__)
-#define ABSL_INTERNAL_HAVE_SSE2 1
-#elif defined(_M_X64) || (defined(_M_IX86_FP) && _M_IX86_FP >= 2)
-// MSVC only defines _M_IX86_FP for x86 32-bit code, and _M_IX86_FP >= 2
-// indicates that at least SSE2 was targeted with the /arch:SSE2 option.
-// All x86-64 processors support SSE2, so support can be assumed.
-// https://docs.microsoft.com/en-us/cpp/preprocessor/predefined-macros
-#define ABSL_INTERNAL_HAVE_SSE2 1
-#endif
-
-// ABSL_INTERNAL_HAVE_SSSE3 is used for compile-time detection of SSSE3 support.
-// See https://gcc.gnu.org/onlinedocs/gcc/x86-Options.html for an overview of
-// which architectures support the various x86 instruction sets.
-//
-// MSVC does not have a mode that targets SSSE3 at compile-time. To use SSSE3
-// with MSVC requires either assuming that the code will only every run on CPUs
-// that support SSSE3, otherwise __cpuid() can be used to detect support at
-// runtime and fallback to a non-SSSE3 implementation when SSSE3 is unsupported
-// by the CPU.
-#ifdef ABSL_INTERNAL_HAVE_SSSE3
-#error ABSL_INTERNAL_HAVE_SSSE3 cannot be directly set
-#elif defined(__SSSE3__)
-#define ABSL_INTERNAL_HAVE_SSSE3 1
-#endif
-
-// ABSL_INTERNAL_HAVE_ARM_NEON is used for compile-time detection of NEON (ARM
-// SIMD).
-//
-// If __CUDA_ARCH__ is defined, then we are compiling CUDA code in device mode.
-// In device mode, NEON intrinsics are not available, regardless of host
-// platform.
-// https://llvm.org/docs/CompileCudaWithLLVM.html#detecting-clang-vs-nvcc-from-code
-#ifdef ABSL_INTERNAL_HAVE_ARM_NEON
-#error ABSL_INTERNAL_HAVE_ARM_NEON cannot be directly set
-#elif defined(__ARM_NEON) && !defined(__CUDA_ARCH__)
-#define ABSL_INTERNAL_HAVE_ARM_NEON 1
-#endif
-
-#endif // ABSL_BASE_CONFIG_H_
diff --git a/third_party/abseil-cpp/absl/base/config_test.cc b/third_party/abseil-cpp/absl/base/config_test.cc
deleted file mode 100644
index 7e0c033..0000000
--- a/third_party/abseil-cpp/absl/base/config_test.cc
+++ /dev/null
@@ -1,60 +0,0 @@
-// Copyright 2017 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/config.h"
-
-#include <cstdint>
-
-#include "gtest/gtest.h"
-#include "absl/synchronization/internal/thread_pool.h"
-
-namespace {
-
-TEST(ConfigTest, Endianness) {
- union {
- uint32_t value;
- uint8_t data[sizeof(uint32_t)];
- } number;
- number.data[0] = 0x00;
- number.data[1] = 0x01;
- number.data[2] = 0x02;
- number.data[3] = 0x03;
-#if defined(ABSL_IS_LITTLE_ENDIAN) && defined(ABSL_IS_BIG_ENDIAN)
-#error Both ABSL_IS_LITTLE_ENDIAN and ABSL_IS_BIG_ENDIAN are defined
-#elif defined(ABSL_IS_LITTLE_ENDIAN)
- EXPECT_EQ(UINT32_C(0x03020100), number.value);
-#elif defined(ABSL_IS_BIG_ENDIAN)
- EXPECT_EQ(UINT32_C(0x00010203), number.value);
-#else
-#error Unknown endianness
-#endif
-}
-
-#if defined(ABSL_HAVE_THREAD_LOCAL)
-TEST(ConfigTest, ThreadLocal) {
- static thread_local int mine_mine_mine = 16;
- EXPECT_EQ(16, mine_mine_mine);
- {
- absl::synchronization_internal::ThreadPool pool(1);
- pool.Schedule([&] {
- EXPECT_EQ(16, mine_mine_mine);
- mine_mine_mine = 32;
- EXPECT_EQ(32, mine_mine_mine);
- });
- }
- EXPECT_EQ(16, mine_mine_mine);
-}
-#endif
-
-} // namespace
diff --git a/third_party/abseil-cpp/absl/base/const_init.h b/third_party/abseil-cpp/absl/base/const_init.h
deleted file mode 100644
index 16520b6..0000000
--- a/third_party/abseil-cpp/absl/base/const_init.h
+++ /dev/null
@@ -1,76 +0,0 @@
-// Copyright 2017 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.
-//
-// -----------------------------------------------------------------------------
-// kConstInit
-// -----------------------------------------------------------------------------
-//
-// A constructor tag used to mark an object as safe for use as a global
-// variable, avoiding the usual lifetime issues that can affect globals.
-
-#ifndef ABSL_BASE_CONST_INIT_H_
-#define ABSL_BASE_CONST_INIT_H_
-
-#include "absl/base/config.h"
-
-// In general, objects with static storage duration (such as global variables)
-// can trigger tricky object lifetime situations. Attempting to access them
-// from the constructors or destructors of other global objects can result in
-// undefined behavior, unless their constructors and destructors are designed
-// with this issue in mind.
-//
-// The normal way to deal with this issue in C++11 is to use constant
-// initialization and trivial destructors.
-//
-// Constant initialization is guaranteed to occur before any other code
-// executes. Constructors that are declared 'constexpr' are eligible for
-// constant initialization. You can annotate a variable declaration with the
-// ABSL_CONST_INIT macro to express this intent. For compilers that support
-// it, this annotation will cause a compilation error for declarations that
-// aren't subject to constant initialization (perhaps because a runtime value
-// was passed as a constructor argument).
-//
-// On program shutdown, lifetime issues can be avoided on global objects by
-// ensuring that they contain trivial destructors. A class has a trivial
-// destructor unless it has a user-defined destructor, a virtual method or base
-// class, or a data member or base class with a non-trivial destructor of its
-// own. Objects with static storage duration and a trivial destructor are not
-// cleaned up on program shutdown, and are thus safe to access from other code
-// running during shutdown.
-//
-// For a few core Abseil classes, we make a best effort to allow for safe global
-// instances, even though these classes have non-trivial destructors. These
-// objects can be created with the absl::kConstInit tag. For example:
-// ABSL_CONST_INIT absl::Mutex global_mutex(absl::kConstInit);
-//
-// The line above declares a global variable of type absl::Mutex which can be
-// accessed at any point during startup or shutdown. global_mutex's destructor
-// will still run, but will not invalidate the object. Note that C++ specifies
-// that accessing an object after its destructor has run results in undefined
-// behavior, but this pattern works on the toolchains we support.
-//
-// The absl::kConstInit tag should only be used to define objects with static
-// or thread_local storage duration.
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-
-enum ConstInitType {
- kConstInit,
-};
-
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_BASE_CONST_INIT_H_
diff --git a/third_party/abseil-cpp/absl/base/dynamic_annotations.h b/third_party/abseil-cpp/absl/base/dynamic_annotations.h
deleted file mode 100644
index 1ebf1d1..0000000
--- a/third_party/abseil-cpp/absl/base/dynamic_annotations.h
+++ /dev/null
@@ -1,468 +0,0 @@
-// Copyright 2017 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.
-
-// This file defines dynamic annotations for use with dynamic analysis tool
-// such as valgrind, PIN, etc.
-//
-// Dynamic annotation is a source code annotation that affects the generated
-// code (that is, the annotation is not a comment). Each such annotation is
-// attached to a particular instruction and/or to a particular object (address)
-// in the program.
-//
-// The annotations that should be used by users are macros in all upper-case
-// (e.g., ABSL_ANNOTATE_THREAD_NAME).
-//
-// Actual implementation of these macros may differ depending on the dynamic
-// analysis tool being used.
-//
-// This file supports the following configurations:
-// - Dynamic Annotations enabled (with static thread-safety warnings disabled).
-// In this case, macros expand to functions implemented by Thread Sanitizer,
-// when building with TSan. When not provided an external implementation,
-// dynamic_annotations.cc provides no-op implementations.
-//
-// - Static Clang thread-safety warnings enabled.
-// When building with a Clang compiler that supports thread-safety warnings,
-// a subset of annotations can be statically-checked at compile-time. We
-// expand these macros to static-inline functions that can be analyzed for
-// thread-safety, but afterwards elided when building the final binary.
-//
-// - All annotations are disabled.
-// If neither Dynamic Annotations nor Clang thread-safety warnings are
-// enabled, then all annotation-macros expand to empty.
-
-#ifndef ABSL_BASE_DYNAMIC_ANNOTATIONS_H_
-#define ABSL_BASE_DYNAMIC_ANNOTATIONS_H_
-
-#include <stddef.h>
-
-#include "absl/base/attributes.h"
-#include "absl/base/config.h"
-#ifdef __cplusplus
-#include "absl/base/macros.h"
-#endif
-
-// -------------------------------------------------------------------------
-// Decide which features are enabled.
-
-#ifdef ABSL_HAVE_THREAD_SANITIZER
-
-#define ABSL_INTERNAL_RACE_ANNOTATIONS_ENABLED 1
-#define ABSL_INTERNAL_READS_ANNOTATIONS_ENABLED 1
-#define ABSL_INTERNAL_WRITES_ANNOTATIONS_ENABLED 1
-#define ABSL_INTERNAL_ANNOTALYSIS_ENABLED 0
-#define ABSL_INTERNAL_READS_WRITES_ANNOTATIONS_ENABLED 1
-
-#else
-
-#define ABSL_INTERNAL_RACE_ANNOTATIONS_ENABLED 0
-#define ABSL_INTERNAL_READS_ANNOTATIONS_ENABLED 0
-#define ABSL_INTERNAL_WRITES_ANNOTATIONS_ENABLED 0
-
-// Clang provides limited support for static thread-safety analysis through a
-// feature called Annotalysis. We configure macro-definitions according to
-// whether Annotalysis support is available. When running in opt-mode, GCC
-// will issue a warning, if these attributes are compiled. Only include them
-// when compiling using Clang.
-
-#if defined(__clang__)
-#define ABSL_INTERNAL_ANNOTALYSIS_ENABLED 1
-#if !defined(SWIG)
-#define ABSL_INTERNAL_IGNORE_READS_ATTRIBUTE_ENABLED 1
-#endif
-#else
-#define ABSL_INTERNAL_ANNOTALYSIS_ENABLED 0
-#endif
-
-// Read/write annotations are enabled in Annotalysis mode; disabled otherwise.
-#define ABSL_INTERNAL_READS_WRITES_ANNOTATIONS_ENABLED \
- ABSL_INTERNAL_ANNOTALYSIS_ENABLED
-
-#endif // ABSL_HAVE_THREAD_SANITIZER
-
-#ifdef __cplusplus
-#define ABSL_INTERNAL_BEGIN_EXTERN_C extern "C" {
-#define ABSL_INTERNAL_END_EXTERN_C } // extern "C"
-#define ABSL_INTERNAL_GLOBAL_SCOPED(F) ::F
-#define ABSL_INTERNAL_STATIC_INLINE inline
-#else
-#define ABSL_INTERNAL_BEGIN_EXTERN_C // empty
-#define ABSL_INTERNAL_END_EXTERN_C // empty
-#define ABSL_INTERNAL_GLOBAL_SCOPED(F) F
-#define ABSL_INTERNAL_STATIC_INLINE static inline
-#endif
-
-// -------------------------------------------------------------------------
-// Define race annotations.
-
-#if ABSL_INTERNAL_RACE_ANNOTATIONS_ENABLED == 1
-// Some of the symbols used in this section (e.g. AnnotateBenignRaceSized) are
-// defined by the compiler-based santizer implementation, not by the Abseil
-// library. Therefore they do not use ABSL_INTERNAL_C_SYMBOL.
-
-// -------------------------------------------------------------
-// Annotations that suppress errors. It is usually better to express the
-// program's synchronization using the other annotations, but these can be used
-// when all else fails.
-
-// Report that we may have a benign race at `pointer`, with size
-// "sizeof(*(pointer))". `pointer` must be a non-void* pointer. Insert at the
-// point where `pointer` has been allocated, preferably close to the point
-// where the race happens. See also ABSL_ANNOTATE_BENIGN_RACE_STATIC.
-#define ABSL_ANNOTATE_BENIGN_RACE(pointer, description) \
- ABSL_INTERNAL_GLOBAL_SCOPED(AnnotateBenignRaceSized) \
- (__FILE__, __LINE__, pointer, sizeof(*(pointer)), description)
-
-// Same as ABSL_ANNOTATE_BENIGN_RACE(`address`, `description`), but applies to
-// the memory range [`address`, `address`+`size`).
-#define ABSL_ANNOTATE_BENIGN_RACE_SIZED(address, size, description) \
- ABSL_INTERNAL_GLOBAL_SCOPED(AnnotateBenignRaceSized) \
- (__FILE__, __LINE__, address, size, description)
-
-// Enable (`enable`!=0) or disable (`enable`==0) race detection for all threads.
-// This annotation could be useful if you want to skip expensive race analysis
-// during some period of program execution, e.g. during initialization.
-#define ABSL_ANNOTATE_ENABLE_RACE_DETECTION(enable) \
- ABSL_INTERNAL_GLOBAL_SCOPED(AnnotateEnableRaceDetection) \
- (__FILE__, __LINE__, enable)
-
-// -------------------------------------------------------------
-// Annotations useful for debugging.
-
-// Report the current thread `name` to a race detector.
-#define ABSL_ANNOTATE_THREAD_NAME(name) \
- ABSL_INTERNAL_GLOBAL_SCOPED(AnnotateThreadName)(__FILE__, __LINE__, name)
-
-// -------------------------------------------------------------
-// Annotations useful when implementing locks. They are not normally needed by
-// modules that merely use locks. The `lock` argument is a pointer to the lock
-// object.
-
-// Report that a lock has been created at address `lock`.
-#define ABSL_ANNOTATE_RWLOCK_CREATE(lock) \
- ABSL_INTERNAL_GLOBAL_SCOPED(AnnotateRWLockCreate)(__FILE__, __LINE__, lock)
-
-// Report that a linker initialized lock has been created at address `lock`.
-#ifdef ABSL_HAVE_THREAD_SANITIZER
-#define ABSL_ANNOTATE_RWLOCK_CREATE_STATIC(lock) \
- ABSL_INTERNAL_GLOBAL_SCOPED(AnnotateRWLockCreateStatic) \
- (__FILE__, __LINE__, lock)
-#else
-#define ABSL_ANNOTATE_RWLOCK_CREATE_STATIC(lock) \
- ABSL_ANNOTATE_RWLOCK_CREATE(lock)
-#endif
-
-// Report that the lock at address `lock` is about to be destroyed.
-#define ABSL_ANNOTATE_RWLOCK_DESTROY(lock) \
- ABSL_INTERNAL_GLOBAL_SCOPED(AnnotateRWLockDestroy)(__FILE__, __LINE__, lock)
-
-// Report that the lock at address `lock` has been acquired.
-// `is_w`=1 for writer lock, `is_w`=0 for reader lock.
-#define ABSL_ANNOTATE_RWLOCK_ACQUIRED(lock, is_w) \
- ABSL_INTERNAL_GLOBAL_SCOPED(AnnotateRWLockAcquired) \
- (__FILE__, __LINE__, lock, is_w)
-
-// Report that the lock at address `lock` is about to be released.
-// `is_w`=1 for writer lock, `is_w`=0 for reader lock.
-#define ABSL_ANNOTATE_RWLOCK_RELEASED(lock, is_w) \
- ABSL_INTERNAL_GLOBAL_SCOPED(AnnotateRWLockReleased) \
- (__FILE__, __LINE__, lock, is_w)
-
-// Apply ABSL_ANNOTATE_BENIGN_RACE_SIZED to a static variable `static_var`.
-#define ABSL_ANNOTATE_BENIGN_RACE_STATIC(static_var, description) \
- namespace { \
- class static_var##_annotator { \
- public: \
- static_var##_annotator() { \
- ABSL_ANNOTATE_BENIGN_RACE_SIZED(&static_var, sizeof(static_var), \
- #static_var ": " description); \
- } \
- }; \
- static static_var##_annotator the##static_var##_annotator; \
- } // namespace
-
-// Function prototypes of annotations provided by the compiler-based sanitizer
-// implementation.
-ABSL_INTERNAL_BEGIN_EXTERN_C
-void AnnotateRWLockCreate(const char* file, int line,
- const volatile void* lock);
-void AnnotateRWLockCreateStatic(const char* file, int line,
- const volatile void* lock);
-void AnnotateRWLockDestroy(const char* file, int line,
- const volatile void* lock);
-void AnnotateRWLockAcquired(const char* file, int line,
- const volatile void* lock, long is_w); // NOLINT
-void AnnotateRWLockReleased(const char* file, int line,
- const volatile void* lock, long is_w); // NOLINT
-void AnnotateBenignRace(const char* file, int line,
- const volatile void* address, const char* description);
-void AnnotateBenignRaceSized(const char* file, int line,
- const volatile void* address, size_t size,
- const char* description);
-void AnnotateThreadName(const char* file, int line, const char* name);
-void AnnotateEnableRaceDetection(const char* file, int line, int enable);
-ABSL_INTERNAL_END_EXTERN_C
-
-#else // ABSL_INTERNAL_RACE_ANNOTATIONS_ENABLED == 0
-
-#define ABSL_ANNOTATE_RWLOCK_CREATE(lock) // empty
-#define ABSL_ANNOTATE_RWLOCK_CREATE_STATIC(lock) // empty
-#define ABSL_ANNOTATE_RWLOCK_DESTROY(lock) // empty
-#define ABSL_ANNOTATE_RWLOCK_ACQUIRED(lock, is_w) // empty
-#define ABSL_ANNOTATE_RWLOCK_RELEASED(lock, is_w) // empty
-#define ABSL_ANNOTATE_BENIGN_RACE(address, description) // empty
-#define ABSL_ANNOTATE_BENIGN_RACE_SIZED(address, size, description) // empty
-#define ABSL_ANNOTATE_THREAD_NAME(name) // empty
-#define ABSL_ANNOTATE_ENABLE_RACE_DETECTION(enable) // empty
-#define ABSL_ANNOTATE_BENIGN_RACE_STATIC(static_var, description) // empty
-
-#endif // ABSL_INTERNAL_RACE_ANNOTATIONS_ENABLED
-
-// -------------------------------------------------------------------------
-// Define memory annotations.
-
-#ifdef ABSL_HAVE_MEMORY_SANITIZER
-
-#include <sanitizer/msan_interface.h>
-
-#define ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(address, size) \
- __msan_unpoison(address, size)
-
-#define ABSL_ANNOTATE_MEMORY_IS_UNINITIALIZED(address, size) \
- __msan_allocated_memory(address, size)
-
-#else // !defined(ABSL_HAVE_MEMORY_SANITIZER)
-
-// TODO(rogeeff): remove this branch
-#ifdef ABSL_HAVE_THREAD_SANITIZER
-#define ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(address, size) \
- do { \
- (void)(address); \
- (void)(size); \
- } while (0)
-#define ABSL_ANNOTATE_MEMORY_IS_UNINITIALIZED(address, size) \
- do { \
- (void)(address); \
- (void)(size); \
- } while (0)
-#else
-
-#define ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(address, size) // empty
-#define ABSL_ANNOTATE_MEMORY_IS_UNINITIALIZED(address, size) // empty
-
-#endif
-
-#endif // ABSL_HAVE_MEMORY_SANITIZER
-
-// -------------------------------------------------------------------------
-// Define IGNORE_READS_BEGIN/_END attributes.
-
-#if defined(ABSL_INTERNAL_IGNORE_READS_ATTRIBUTE_ENABLED)
-
-#define ABSL_INTERNAL_IGNORE_READS_BEGIN_ATTRIBUTE \
- __attribute((exclusive_lock_function("*")))
-#define ABSL_INTERNAL_IGNORE_READS_END_ATTRIBUTE \
- __attribute((unlock_function("*")))
-
-#else // !defined(ABSL_INTERNAL_IGNORE_READS_ATTRIBUTE_ENABLED)
-
-#define ABSL_INTERNAL_IGNORE_READS_BEGIN_ATTRIBUTE // empty
-#define ABSL_INTERNAL_IGNORE_READS_END_ATTRIBUTE // empty
-
-#endif // defined(ABSL_INTERNAL_IGNORE_READS_ATTRIBUTE_ENABLED)
-
-// -------------------------------------------------------------------------
-// Define IGNORE_READS_BEGIN/_END annotations.
-
-#if ABSL_INTERNAL_READS_ANNOTATIONS_ENABLED == 1
-// Some of the symbols used in this section (e.g. AnnotateIgnoreReadsBegin) are
-// defined by the compiler-based implementation, not by the Abseil
-// library. Therefore they do not use ABSL_INTERNAL_C_SYMBOL.
-
-// Request the analysis tool to ignore all reads in the current thread until
-// ABSL_ANNOTATE_IGNORE_READS_END is called. Useful to ignore intentional racey
-// reads, while still checking other reads and all writes.
-// See also ABSL_ANNOTATE_UNPROTECTED_READ.
-#define ABSL_ANNOTATE_IGNORE_READS_BEGIN() \
- ABSL_INTERNAL_GLOBAL_SCOPED(AnnotateIgnoreReadsBegin) \
- (__FILE__, __LINE__)
-
-// Stop ignoring reads.
-#define ABSL_ANNOTATE_IGNORE_READS_END() \
- ABSL_INTERNAL_GLOBAL_SCOPED(AnnotateIgnoreReadsEnd) \
- (__FILE__, __LINE__)
-
-// Function prototypes of annotations provided by the compiler-based sanitizer
-// implementation.
-ABSL_INTERNAL_BEGIN_EXTERN_C
-void AnnotateIgnoreReadsBegin(const char* file, int line)
- ABSL_INTERNAL_IGNORE_READS_BEGIN_ATTRIBUTE;
-void AnnotateIgnoreReadsEnd(const char* file,
- int line) ABSL_INTERNAL_IGNORE_READS_END_ATTRIBUTE;
-ABSL_INTERNAL_END_EXTERN_C
-
-#elif defined(ABSL_INTERNAL_ANNOTALYSIS_ENABLED)
-
-// When Annotalysis is enabled without Dynamic Annotations, the use of
-// static-inline functions allows the annotations to be read at compile-time,
-// while still letting the compiler elide the functions from the final build.
-//
-// TODO(delesley) -- The exclusive lock here ignores writes as well, but
-// allows IGNORE_READS_AND_WRITES to work properly.
-
-#define ABSL_ANNOTATE_IGNORE_READS_BEGIN() \
- ABSL_INTERNAL_GLOBAL_SCOPED( \
- ABSL_INTERNAL_C_SYMBOL(AbslInternalAnnotateIgnoreReadsBegin)) \
- ()
-
-#define ABSL_ANNOTATE_IGNORE_READS_END() \
- ABSL_INTERNAL_GLOBAL_SCOPED( \
- ABSL_INTERNAL_C_SYMBOL(AbslInternalAnnotateIgnoreReadsEnd)) \
- ()
-
-ABSL_INTERNAL_STATIC_INLINE void ABSL_INTERNAL_C_SYMBOL(
- AbslInternalAnnotateIgnoreReadsBegin)()
- ABSL_INTERNAL_IGNORE_READS_BEGIN_ATTRIBUTE {}
-
-ABSL_INTERNAL_STATIC_INLINE void ABSL_INTERNAL_C_SYMBOL(
- AbslInternalAnnotateIgnoreReadsEnd)()
- ABSL_INTERNAL_IGNORE_READS_END_ATTRIBUTE {}
-
-#else
-
-#define ABSL_ANNOTATE_IGNORE_READS_BEGIN() // empty
-#define ABSL_ANNOTATE_IGNORE_READS_END() // empty
-
-#endif
-
-// -------------------------------------------------------------------------
-// Define IGNORE_WRITES_BEGIN/_END annotations.
-
-#if ABSL_INTERNAL_WRITES_ANNOTATIONS_ENABLED == 1
-
-// Similar to ABSL_ANNOTATE_IGNORE_READS_BEGIN, but ignore writes instead.
-#define ABSL_ANNOTATE_IGNORE_WRITES_BEGIN() \
- ABSL_INTERNAL_GLOBAL_SCOPED(AnnotateIgnoreWritesBegin)(__FILE__, __LINE__)
-
-// Stop ignoring writes.
-#define ABSL_ANNOTATE_IGNORE_WRITES_END() \
- ABSL_INTERNAL_GLOBAL_SCOPED(AnnotateIgnoreWritesEnd)(__FILE__, __LINE__)
-
-// Function prototypes of annotations provided by the compiler-based sanitizer
-// implementation.
-ABSL_INTERNAL_BEGIN_EXTERN_C
-void AnnotateIgnoreWritesBegin(const char* file, int line);
-void AnnotateIgnoreWritesEnd(const char* file, int line);
-ABSL_INTERNAL_END_EXTERN_C
-
-#else
-
-#define ABSL_ANNOTATE_IGNORE_WRITES_BEGIN() // empty
-#define ABSL_ANNOTATE_IGNORE_WRITES_END() // empty
-
-#endif
-
-// -------------------------------------------------------------------------
-// Define the ABSL_ANNOTATE_IGNORE_READS_AND_WRITES_* annotations using the more
-// primitive annotations defined above.
-//
-// Instead of doing
-// ABSL_ANNOTATE_IGNORE_READS_BEGIN();
-// ... = x;
-// ABSL_ANNOTATE_IGNORE_READS_END();
-// one can use
-// ... = ABSL_ANNOTATE_UNPROTECTED_READ(x);
-
-#if defined(ABSL_INTERNAL_READS_WRITES_ANNOTATIONS_ENABLED)
-
-// Start ignoring all memory accesses (both reads and writes).
-#define ABSL_ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN() \
- do { \
- ABSL_ANNOTATE_IGNORE_READS_BEGIN(); \
- ABSL_ANNOTATE_IGNORE_WRITES_BEGIN(); \
- } while (0)
-
-// Stop ignoring both reads and writes.
-#define ABSL_ANNOTATE_IGNORE_READS_AND_WRITES_END() \
- do { \
- ABSL_ANNOTATE_IGNORE_WRITES_END(); \
- ABSL_ANNOTATE_IGNORE_READS_END(); \
- } while (0)
-
-#ifdef __cplusplus
-// ABSL_ANNOTATE_UNPROTECTED_READ is the preferred way to annotate racey reads.
-#define ABSL_ANNOTATE_UNPROTECTED_READ(x) \
- absl::base_internal::AnnotateUnprotectedRead(x)
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-
-template <typename T>
-inline T AnnotateUnprotectedRead(const volatile T& x) { // NOLINT
- ABSL_ANNOTATE_IGNORE_READS_BEGIN();
- T res = x;
- ABSL_ANNOTATE_IGNORE_READS_END();
- return res;
-}
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-#endif
-
-#else
-
-#define ABSL_ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN() // empty
-#define ABSL_ANNOTATE_IGNORE_READS_AND_WRITES_END() // empty
-#define ABSL_ANNOTATE_UNPROTECTED_READ(x) (x)
-
-#endif
-
-// -------------------------------------------------------------------------
-// Address sanitizer annotations
-
-#ifdef ABSL_HAVE_ADDRESS_SANITIZER
-// Describe the current state of a contiguous container such as e.g.
-// std::vector or std::string. For more details see
-// sanitizer/common_interface_defs.h, which is provided by the compiler.
-#include <sanitizer/common_interface_defs.h>
-
-#define ABSL_ANNOTATE_CONTIGUOUS_CONTAINER(beg, end, old_mid, new_mid) \
- __sanitizer_annotate_contiguous_container(beg, end, old_mid, new_mid)
-#define ABSL_ADDRESS_SANITIZER_REDZONE(name) \
- struct { \
- alignas(8) char x[8]; \
- } name
-
-#else
-
-#define ABSL_ANNOTATE_CONTIGUOUS_CONTAINER(beg, end, old_mid, new_mid) // empty
-#define ABSL_ADDRESS_SANITIZER_REDZONE(name) static_assert(true, "")
-
-#endif // ABSL_HAVE_ADDRESS_SANITIZER
-
-// -------------------------------------------------------------------------
-// Undefine the macros intended only for this file.
-
-#undef ABSL_INTERNAL_RACE_ANNOTATIONS_ENABLED
-#undef ABSL_INTERNAL_READS_ANNOTATIONS_ENABLED
-#undef ABSL_INTERNAL_WRITES_ANNOTATIONS_ENABLED
-#undef ABSL_INTERNAL_ANNOTALYSIS_ENABLED
-#undef ABSL_INTERNAL_READS_WRITES_ANNOTATIONS_ENABLED
-#undef ABSL_INTERNAL_BEGIN_EXTERN_C
-#undef ABSL_INTERNAL_END_EXTERN_C
-#undef ABSL_INTERNAL_STATIC_INLINE
-
-#endif // ABSL_BASE_DYNAMIC_ANNOTATIONS_H_
diff --git a/third_party/abseil-cpp/absl/base/exception_safety_testing_test.cc b/third_party/abseil-cpp/absl/base/exception_safety_testing_test.cc
deleted file mode 100644
index a87fd6a..0000000
--- a/third_party/abseil-cpp/absl/base/exception_safety_testing_test.cc
+++ /dev/null
@@ -1,959 +0,0 @@
-// Copyright 2017 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/exception_safety_testing.h"
-
-#ifdef ABSL_HAVE_EXCEPTIONS
-
-#include <cstddef>
-#include <exception>
-#include <iostream>
-#include <list>
-#include <type_traits>
-#include <vector>
-
-#include "gtest/gtest-spi.h"
-#include "gtest/gtest.h"
-#include "absl/memory/memory.h"
-
-namespace testing {
-
-namespace {
-
-using ::testing::exceptions_internal::SetCountdown;
-using ::testing::exceptions_internal::TestException;
-using ::testing::exceptions_internal::UnsetCountdown;
-
-// EXPECT_NO_THROW can't inspect the thrown inspection in general.
-template <typename F>
-void ExpectNoThrow(const F& f) {
- try {
- f();
- } catch (const TestException& e) {
- ADD_FAILURE() << "Unexpected exception thrown from " << e.what();
- }
-}
-
-TEST(ThrowingValueTest, Throws) {
- SetCountdown();
- EXPECT_THROW(ThrowingValue<> bomb, TestException);
-
- // It's not guaranteed that every operator only throws *once*. The default
- // ctor only throws once, though, so use it to make sure we only throw when
- // the countdown hits 0
- SetCountdown(2);
- ExpectNoThrow([]() { ThrowingValue<> bomb; });
- ExpectNoThrow([]() { ThrowingValue<> bomb; });
- EXPECT_THROW(ThrowingValue<> bomb, TestException);
-
- UnsetCountdown();
-}
-
-// Tests that an operation throws when the countdown is at 0, doesn't throw when
-// the countdown doesn't hit 0, and doesn't modify the state of the
-// ThrowingValue if it throws
-template <typename F>
-void TestOp(const F& f) {
- ExpectNoThrow(f);
-
- SetCountdown();
- EXPECT_THROW(f(), TestException);
- UnsetCountdown();
-}
-
-TEST(ThrowingValueTest, ThrowingCtors) {
- ThrowingValue<> bomb;
-
- TestOp([]() { ThrowingValue<> bomb(1); });
- TestOp([&]() { ThrowingValue<> bomb1 = bomb; });
- TestOp([&]() { ThrowingValue<> bomb1 = std::move(bomb); });
-}
-
-TEST(ThrowingValueTest, ThrowingAssignment) {
- ThrowingValue<> bomb, bomb1;
-
- TestOp([&]() { bomb = bomb1; });
- TestOp([&]() { bomb = std::move(bomb1); });
-
- // Test that when assignment throws, the assignment should fail (lhs != rhs)
- // and strong guarantee fails (lhs != lhs_copy).
- {
- ThrowingValue<> lhs(39), rhs(42);
- ThrowingValue<> lhs_copy(lhs);
- SetCountdown();
- EXPECT_THROW(lhs = rhs, TestException);
- UnsetCountdown();
- EXPECT_NE(lhs, rhs);
- EXPECT_NE(lhs_copy, lhs);
- }
- {
- ThrowingValue<> lhs(39), rhs(42);
- ThrowingValue<> lhs_copy(lhs), rhs_copy(rhs);
- SetCountdown();
- EXPECT_THROW(lhs = std::move(rhs), TestException);
- UnsetCountdown();
- EXPECT_NE(lhs, rhs_copy);
- EXPECT_NE(lhs_copy, lhs);
- }
-}
-
-TEST(ThrowingValueTest, ThrowingComparisons) {
- ThrowingValue<> bomb1, bomb2;
- TestOp([&]() { return bomb1 == bomb2; });
- TestOp([&]() { return bomb1 != bomb2; });
- TestOp([&]() { return bomb1 < bomb2; });
- TestOp([&]() { return bomb1 <= bomb2; });
- TestOp([&]() { return bomb1 > bomb2; });
- TestOp([&]() { return bomb1 >= bomb2; });
-}
-
-TEST(ThrowingValueTest, ThrowingArithmeticOps) {
- ThrowingValue<> bomb1(1), bomb2(2);
-
- TestOp([&bomb1]() { +bomb1; });
- TestOp([&bomb1]() { -bomb1; });
- TestOp([&bomb1]() { ++bomb1; });
- TestOp([&bomb1]() { bomb1++; });
- TestOp([&bomb1]() { --bomb1; });
- TestOp([&bomb1]() { bomb1--; });
-
- TestOp([&]() { bomb1 + bomb2; });
- TestOp([&]() { bomb1 - bomb2; });
- TestOp([&]() { bomb1* bomb2; });
- TestOp([&]() { bomb1 / bomb2; });
- TestOp([&]() { bomb1 << 1; });
- TestOp([&]() { bomb1 >> 1; });
-}
-
-TEST(ThrowingValueTest, ThrowingLogicalOps) {
- ThrowingValue<> bomb1, bomb2;
-
- TestOp([&bomb1]() { !bomb1; });
- TestOp([&]() { bomb1&& bomb2; });
- TestOp([&]() { bomb1 || bomb2; });
-}
-
-TEST(ThrowingValueTest, ThrowingBitwiseOps) {
- ThrowingValue<> bomb1, bomb2;
-
- TestOp([&bomb1]() { ~bomb1; });
- TestOp([&]() { bomb1& bomb2; });
- TestOp([&]() { bomb1 | bomb2; });
- TestOp([&]() { bomb1 ^ bomb2; });
-}
-
-TEST(ThrowingValueTest, ThrowingCompoundAssignmentOps) {
- ThrowingValue<> bomb1(1), bomb2(2);
-
- TestOp([&]() { bomb1 += bomb2; });
- TestOp([&]() { bomb1 -= bomb2; });
- TestOp([&]() { bomb1 *= bomb2; });
- TestOp([&]() { bomb1 /= bomb2; });
- TestOp([&]() { bomb1 %= bomb2; });
- TestOp([&]() { bomb1 &= bomb2; });
- TestOp([&]() { bomb1 |= bomb2; });
- TestOp([&]() { bomb1 ^= bomb2; });
- TestOp([&]() { bomb1 *= bomb2; });
-}
-
-TEST(ThrowingValueTest, ThrowingStreamOps) {
- ThrowingValue<> bomb;
-
- TestOp([&]() {
- std::istringstream stream;
- stream >> bomb;
- });
- TestOp([&]() {
- std::stringstream stream;
- stream << bomb;
- });
-}
-
-// Tests the operator<< of ThrowingValue by forcing ConstructorTracker to emit
-// a nonfatal failure that contains the string representation of the Thrower
-TEST(ThrowingValueTest, StreamOpsOutput) {
- using ::testing::TypeSpec;
- exceptions_internal::ConstructorTracker ct(exceptions_internal::countdown);
-
- // Test default spec list (kEverythingThrows)
- EXPECT_NONFATAL_FAILURE(
- {
- using Thrower = ThrowingValue<TypeSpec{}>;
- auto thrower = Thrower(123);
- thrower.~Thrower();
- },
- "ThrowingValue<>(123)");
-
- // Test with one item in spec list (kNoThrowCopy)
- EXPECT_NONFATAL_FAILURE(
- {
- using Thrower = ThrowingValue<TypeSpec::kNoThrowCopy>;
- auto thrower = Thrower(234);
- thrower.~Thrower();
- },
- "ThrowingValue<kNoThrowCopy>(234)");
-
- // Test with multiple items in spec list (kNoThrowMove, kNoThrowNew)
- EXPECT_NONFATAL_FAILURE(
- {
- using Thrower =
- ThrowingValue<TypeSpec::kNoThrowMove | TypeSpec::kNoThrowNew>;
- auto thrower = Thrower(345);
- thrower.~Thrower();
- },
- "ThrowingValue<kNoThrowMove | kNoThrowNew>(345)");
-
- // Test with all items in spec list (kNoThrowCopy, kNoThrowMove, kNoThrowNew)
- EXPECT_NONFATAL_FAILURE(
- {
- using Thrower = ThrowingValue<static_cast<TypeSpec>(-1)>;
- auto thrower = Thrower(456);
- thrower.~Thrower();
- },
- "ThrowingValue<kNoThrowCopy | kNoThrowMove | kNoThrowNew>(456)");
-}
-
-template <typename F>
-void TestAllocatingOp(const F& f) {
- ExpectNoThrow(f);
-
- SetCountdown();
- EXPECT_THROW(f(), exceptions_internal::TestBadAllocException);
- UnsetCountdown();
-}
-
-TEST(ThrowingValueTest, ThrowingAllocatingOps) {
- // make_unique calls unqualified operator new, so these exercise the
- // ThrowingValue overloads.
- TestAllocatingOp([]() { return absl::make_unique<ThrowingValue<>>(1); });
- TestAllocatingOp([]() { return absl::make_unique<ThrowingValue<>[]>(2); });
-}
-
-TEST(ThrowingValueTest, NonThrowingMoveCtor) {
- ThrowingValue<TypeSpec::kNoThrowMove> nothrow_ctor;
-
- SetCountdown();
- ExpectNoThrow([¬hrow_ctor]() {
- ThrowingValue<TypeSpec::kNoThrowMove> nothrow1 = std::move(nothrow_ctor);
- });
- UnsetCountdown();
-}
-
-TEST(ThrowingValueTest, NonThrowingMoveAssign) {
- ThrowingValue<TypeSpec::kNoThrowMove> nothrow_assign1, nothrow_assign2;
-
- SetCountdown();
- ExpectNoThrow([¬hrow_assign1, ¬hrow_assign2]() {
- nothrow_assign1 = std::move(nothrow_assign2);
- });
- UnsetCountdown();
-}
-
-TEST(ThrowingValueTest, ThrowingCopyCtor) {
- ThrowingValue<> tv;
-
- TestOp([&]() { ThrowingValue<> tv_copy(tv); });
-}
-
-TEST(ThrowingValueTest, ThrowingCopyAssign) {
- ThrowingValue<> tv1, tv2;
-
- TestOp([&]() { tv1 = tv2; });
-}
-
-TEST(ThrowingValueTest, NonThrowingCopyCtor) {
- ThrowingValue<TypeSpec::kNoThrowCopy> nothrow_ctor;
-
- SetCountdown();
- ExpectNoThrow([¬hrow_ctor]() {
- ThrowingValue<TypeSpec::kNoThrowCopy> nothrow1(nothrow_ctor);
- });
- UnsetCountdown();
-}
-
-TEST(ThrowingValueTest, NonThrowingCopyAssign) {
- ThrowingValue<TypeSpec::kNoThrowCopy> nothrow_assign1, nothrow_assign2;
-
- SetCountdown();
- ExpectNoThrow([¬hrow_assign1, ¬hrow_assign2]() {
- nothrow_assign1 = nothrow_assign2;
- });
- UnsetCountdown();
-}
-
-TEST(ThrowingValueTest, ThrowingSwap) {
- ThrowingValue<> bomb1, bomb2;
- TestOp([&]() { std::swap(bomb1, bomb2); });
-}
-
-TEST(ThrowingValueTest, NonThrowingSwap) {
- ThrowingValue<TypeSpec::kNoThrowMove> bomb1, bomb2;
- ExpectNoThrow([&]() { std::swap(bomb1, bomb2); });
-}
-
-TEST(ThrowingValueTest, NonThrowingAllocation) {
- ThrowingValue<TypeSpec::kNoThrowNew>* allocated;
- ThrowingValue<TypeSpec::kNoThrowNew>* array;
-
- ExpectNoThrow([&allocated]() {
- allocated = new ThrowingValue<TypeSpec::kNoThrowNew>(1);
- delete allocated;
- });
- ExpectNoThrow([&array]() {
- array = new ThrowingValue<TypeSpec::kNoThrowNew>[2];
- delete[] array;
- });
-}
-
-TEST(ThrowingValueTest, NonThrowingDelete) {
- auto* allocated = new ThrowingValue<>(1);
- auto* array = new ThrowingValue<>[2];
-
- SetCountdown();
- ExpectNoThrow([allocated]() { delete allocated; });
- SetCountdown();
- ExpectNoThrow([array]() { delete[] array; });
-
- UnsetCountdown();
-}
-
-TEST(ThrowingValueTest, NonThrowingPlacementDelete) {
- constexpr int kArrayLen = 2;
- // We intentionally create extra space to store the tag allocated by placement
- // new[].
- constexpr int kStorageLen = 4;
-
- alignas(ThrowingValue<>) unsigned char buf[sizeof(ThrowingValue<>)];
- alignas(ThrowingValue<>) unsigned char
- array_buf[sizeof(ThrowingValue<>[kStorageLen])];
- auto* placed = new (&buf) ThrowingValue<>(1);
- auto placed_array = new (&array_buf) ThrowingValue<>[kArrayLen];
-
- SetCountdown();
- ExpectNoThrow([placed, &buf]() {
- placed->~ThrowingValue<>();
- ThrowingValue<>::operator delete(placed, &buf);
- });
-
- SetCountdown();
- ExpectNoThrow([&, placed_array]() {
- for (int i = 0; i < kArrayLen; ++i) placed_array[i].~ThrowingValue<>();
- ThrowingValue<>::operator delete[](placed_array, &array_buf);
- });
-
- UnsetCountdown();
-}
-
-TEST(ThrowingValueTest, NonThrowingDestructor) {
- auto* allocated = new ThrowingValue<>();
-
- SetCountdown();
- ExpectNoThrow([allocated]() { delete allocated; });
- UnsetCountdown();
-}
-
-TEST(ThrowingBoolTest, ThrowingBool) {
- ThrowingBool t = true;
-
- // Test that it's contextually convertible to bool
- if (t) { // NOLINT(whitespace/empty_if_body)
- }
- EXPECT_TRUE(t);
-
- TestOp([&]() { (void)!t; });
-}
-
-TEST(ThrowingAllocatorTest, MemoryManagement) {
- // Just exercise the memory management capabilities under LSan to make sure we
- // don't leak.
- ThrowingAllocator<int> int_alloc;
- int* ip = int_alloc.allocate(1);
- int_alloc.deallocate(ip, 1);
- int* i_array = int_alloc.allocate(2);
- int_alloc.deallocate(i_array, 2);
-
- ThrowingAllocator<ThrowingValue<>> tv_alloc;
- ThrowingValue<>* ptr = tv_alloc.allocate(1);
- tv_alloc.deallocate(ptr, 1);
- ThrowingValue<>* tv_array = tv_alloc.allocate(2);
- tv_alloc.deallocate(tv_array, 2);
-}
-
-TEST(ThrowingAllocatorTest, CallsGlobalNew) {
- ThrowingAllocator<ThrowingValue<>, AllocSpec::kNoThrowAllocate> nothrow_alloc;
- ThrowingValue<>* ptr;
-
- SetCountdown();
- // This will only throw if ThrowingValue::new is called.
- ExpectNoThrow([&]() { ptr = nothrow_alloc.allocate(1); });
- nothrow_alloc.deallocate(ptr, 1);
-
- UnsetCountdown();
-}
-
-TEST(ThrowingAllocatorTest, ThrowingConstructors) {
- ThrowingAllocator<int> int_alloc;
- int* ip = nullptr;
-
- SetCountdown();
- EXPECT_THROW(ip = int_alloc.allocate(1), TestException);
- ExpectNoThrow([&]() { ip = int_alloc.allocate(1); });
-
- *ip = 1;
- SetCountdown();
- EXPECT_THROW(int_alloc.construct(ip, 2), TestException);
- EXPECT_EQ(*ip, 1);
- int_alloc.deallocate(ip, 1);
-
- UnsetCountdown();
-}
-
-TEST(ThrowingAllocatorTest, NonThrowingConstruction) {
- {
- ThrowingAllocator<int, AllocSpec::kNoThrowAllocate> int_alloc;
- int* ip = nullptr;
-
- SetCountdown();
- ExpectNoThrow([&]() { ip = int_alloc.allocate(1); });
-
- SetCountdown();
- ExpectNoThrow([&]() { int_alloc.construct(ip, 2); });
-
- EXPECT_EQ(*ip, 2);
- int_alloc.deallocate(ip, 1);
-
- UnsetCountdown();
- }
-
- {
- ThrowingAllocator<int> int_alloc;
- int* ip = nullptr;
- ExpectNoThrow([&]() { ip = int_alloc.allocate(1); });
- ExpectNoThrow([&]() { int_alloc.construct(ip, 2); });
- EXPECT_EQ(*ip, 2);
- int_alloc.deallocate(ip, 1);
- }
-
- {
- ThrowingAllocator<ThrowingValue<>, AllocSpec::kNoThrowAllocate>
- nothrow_alloc;
- ThrowingValue<>* ptr;
-
- SetCountdown();
- ExpectNoThrow([&]() { ptr = nothrow_alloc.allocate(1); });
-
- SetCountdown();
- ExpectNoThrow(
- [&]() { nothrow_alloc.construct(ptr, 2, testing::nothrow_ctor); });
-
- EXPECT_EQ(ptr->Get(), 2);
- nothrow_alloc.destroy(ptr);
- nothrow_alloc.deallocate(ptr, 1);
-
- UnsetCountdown();
- }
-
- {
- ThrowingAllocator<int> a;
-
- SetCountdown();
- ExpectNoThrow([&]() { ThrowingAllocator<double> a1 = a; });
-
- SetCountdown();
- ExpectNoThrow([&]() { ThrowingAllocator<double> a1 = std::move(a); });
-
- UnsetCountdown();
- }
-}
-
-TEST(ThrowingAllocatorTest, ThrowingAllocatorConstruction) {
- ThrowingAllocator<int> a;
- TestOp([]() { ThrowingAllocator<int> a; });
- TestOp([&]() { a.select_on_container_copy_construction(); });
-}
-
-TEST(ThrowingAllocatorTest, State) {
- ThrowingAllocator<int> a1, a2;
- EXPECT_NE(a1, a2);
-
- auto a3 = a1;
- EXPECT_EQ(a3, a1);
- int* ip = a1.allocate(1);
- EXPECT_EQ(a3, a1);
- a3.deallocate(ip, 1);
- EXPECT_EQ(a3, a1);
-}
-
-TEST(ThrowingAllocatorTest, InVector) {
- std::vector<ThrowingValue<>, ThrowingAllocator<ThrowingValue<>>> v;
- for (int i = 0; i < 20; ++i) v.push_back({});
- for (int i = 0; i < 20; ++i) v.pop_back();
-}
-
-TEST(ThrowingAllocatorTest, InList) {
- std::list<ThrowingValue<>, ThrowingAllocator<ThrowingValue<>>> l;
- for (int i = 0; i < 20; ++i) l.push_back({});
- for (int i = 0; i < 20; ++i) l.pop_back();
- for (int i = 0; i < 20; ++i) l.push_front({});
- for (int i = 0; i < 20; ++i) l.pop_front();
-}
-
-template <typename TesterInstance, typename = void>
-struct NullaryTestValidator : public std::false_type {};
-
-template <typename TesterInstance>
-struct NullaryTestValidator<
- TesterInstance,
- absl::void_t<decltype(std::declval<TesterInstance>().Test())>>
- : public std::true_type {};
-
-template <typename TesterInstance>
-bool HasNullaryTest(const TesterInstance&) {
- return NullaryTestValidator<TesterInstance>::value;
-}
-
-void DummyOp(void*) {}
-
-template <typename TesterInstance, typename = void>
-struct UnaryTestValidator : public std::false_type {};
-
-template <typename TesterInstance>
-struct UnaryTestValidator<
- TesterInstance,
- absl::void_t<decltype(std::declval<TesterInstance>().Test(DummyOp))>>
- : public std::true_type {};
-
-template <typename TesterInstance>
-bool HasUnaryTest(const TesterInstance&) {
- return UnaryTestValidator<TesterInstance>::value;
-}
-
-TEST(ExceptionSafetyTesterTest, IncompleteTypesAreNotTestable) {
- using T = exceptions_internal::UninitializedT;
- auto op = [](T* t) {};
- auto inv = [](T*) { return testing::AssertionSuccess(); };
- auto fac = []() { return absl::make_unique<T>(); };
-
- // Test that providing operation and inveriants still does not allow for the
- // the invocation of .Test() and .Test(op) because it lacks a factory
- auto without_fac =
- testing::MakeExceptionSafetyTester().WithOperation(op).WithContracts(
- inv, testing::strong_guarantee);
- EXPECT_FALSE(HasNullaryTest(without_fac));
- EXPECT_FALSE(HasUnaryTest(without_fac));
-
- // Test that providing contracts and factory allows the invocation of
- // .Test(op) but does not allow for .Test() because it lacks an operation
- auto without_op = testing::MakeExceptionSafetyTester()
- .WithContracts(inv, testing::strong_guarantee)
- .WithFactory(fac);
- EXPECT_FALSE(HasNullaryTest(without_op));
- EXPECT_TRUE(HasUnaryTest(without_op));
-
- // Test that providing operation and factory still does not allow for the
- // the invocation of .Test() and .Test(op) because it lacks contracts
- auto without_inv =
- testing::MakeExceptionSafetyTester().WithOperation(op).WithFactory(fac);
- EXPECT_FALSE(HasNullaryTest(without_inv));
- EXPECT_FALSE(HasUnaryTest(without_inv));
-}
-
-struct ExampleStruct {};
-
-std::unique_ptr<ExampleStruct> ExampleFunctionFactory() {
- return absl::make_unique<ExampleStruct>();
-}
-
-void ExampleFunctionOperation(ExampleStruct*) {}
-
-testing::AssertionResult ExampleFunctionContract(ExampleStruct*) {
- return testing::AssertionSuccess();
-}
-
-struct {
- std::unique_ptr<ExampleStruct> operator()() const {
- return ExampleFunctionFactory();
- }
-} example_struct_factory;
-
-struct {
- void operator()(ExampleStruct*) const {}
-} example_struct_operation;
-
-struct {
- testing::AssertionResult operator()(ExampleStruct* example_struct) const {
- return ExampleFunctionContract(example_struct);
- }
-} example_struct_contract;
-
-auto example_lambda_factory = []() { return ExampleFunctionFactory(); };
-
-auto example_lambda_operation = [](ExampleStruct*) {};
-
-auto example_lambda_contract = [](ExampleStruct* example_struct) {
- return ExampleFunctionContract(example_struct);
-};
-
-// Testing that function references, pointers, structs with operator() and
-// lambdas can all be used with ExceptionSafetyTester
-TEST(ExceptionSafetyTesterTest, MixedFunctionTypes) {
- // function reference
- EXPECT_TRUE(testing::MakeExceptionSafetyTester()
- .WithFactory(ExampleFunctionFactory)
- .WithOperation(ExampleFunctionOperation)
- .WithContracts(ExampleFunctionContract)
- .Test());
-
- // function pointer
- EXPECT_TRUE(testing::MakeExceptionSafetyTester()
- .WithFactory(&ExampleFunctionFactory)
- .WithOperation(&ExampleFunctionOperation)
- .WithContracts(&ExampleFunctionContract)
- .Test());
-
- // struct
- EXPECT_TRUE(testing::MakeExceptionSafetyTester()
- .WithFactory(example_struct_factory)
- .WithOperation(example_struct_operation)
- .WithContracts(example_struct_contract)
- .Test());
-
- // lambda
- EXPECT_TRUE(testing::MakeExceptionSafetyTester()
- .WithFactory(example_lambda_factory)
- .WithOperation(example_lambda_operation)
- .WithContracts(example_lambda_contract)
- .Test());
-}
-
-struct NonNegative {
- bool operator==(const NonNegative& other) const { return i == other.i; }
- int i;
-};
-
-testing::AssertionResult CheckNonNegativeInvariants(NonNegative* g) {
- if (g->i >= 0) {
- return testing::AssertionSuccess();
- }
- return testing::AssertionFailure()
- << "i should be non-negative but is " << g->i;
-}
-
-struct {
- template <typename T>
- void operator()(T* t) const {
- (*t)();
- }
-} invoker;
-
-auto tester =
- testing::MakeExceptionSafetyTester().WithOperation(invoker).WithContracts(
- CheckNonNegativeInvariants);
-auto strong_tester = tester.WithContracts(testing::strong_guarantee);
-
-struct FailsBasicGuarantee : public NonNegative {
- void operator()() {
- --i;
- ThrowingValue<> bomb;
- ++i;
- }
-};
-
-TEST(ExceptionCheckTest, BasicGuaranteeFailure) {
- EXPECT_FALSE(tester.WithInitialValue(FailsBasicGuarantee{}).Test());
-}
-
-struct FollowsBasicGuarantee : public NonNegative {
- void operator()() {
- ++i;
- ThrowingValue<> bomb;
- }
-};
-
-TEST(ExceptionCheckTest, BasicGuarantee) {
- EXPECT_TRUE(tester.WithInitialValue(FollowsBasicGuarantee{}).Test());
-}
-
-TEST(ExceptionCheckTest, StrongGuaranteeFailure) {
- EXPECT_FALSE(strong_tester.WithInitialValue(FailsBasicGuarantee{}).Test());
- EXPECT_FALSE(strong_tester.WithInitialValue(FollowsBasicGuarantee{}).Test());
-}
-
-struct BasicGuaranteeWithExtraContracts : public NonNegative {
- // After operator(), i is incremented. If operator() throws, i is set to 9999
- void operator()() {
- int old_i = i;
- i = kExceptionSentinel;
- ThrowingValue<> bomb;
- i = ++old_i;
- }
-
- static constexpr int kExceptionSentinel = 9999;
-};
-
-#ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL
-constexpr int BasicGuaranteeWithExtraContracts::kExceptionSentinel;
-#endif
-
-TEST(ExceptionCheckTest, BasicGuaranteeWithExtraContracts) {
- auto tester_with_val =
- tester.WithInitialValue(BasicGuaranteeWithExtraContracts{});
- EXPECT_TRUE(tester_with_val.Test());
- EXPECT_TRUE(
- tester_with_val
- .WithContracts([](BasicGuaranteeWithExtraContracts* o) {
- if (o->i == BasicGuaranteeWithExtraContracts::kExceptionSentinel) {
- return testing::AssertionSuccess();
- }
- return testing::AssertionFailure()
- << "i should be "
- << BasicGuaranteeWithExtraContracts::kExceptionSentinel
- << ", but is " << o->i;
- })
- .Test());
-}
-
-struct FollowsStrongGuarantee : public NonNegative {
- void operator()() { ThrowingValue<> bomb; }
-};
-
-TEST(ExceptionCheckTest, StrongGuarantee) {
- EXPECT_TRUE(tester.WithInitialValue(FollowsStrongGuarantee{}).Test());
- EXPECT_TRUE(strong_tester.WithInitialValue(FollowsStrongGuarantee{}).Test());
-}
-
-struct HasReset : public NonNegative {
- void operator()() {
- i = -1;
- ThrowingValue<> bomb;
- i = 1;
- }
-
- void reset() { i = 0; }
-};
-
-testing::AssertionResult CheckHasResetContracts(HasReset* h) {
- h->reset();
- return testing::AssertionResult(h->i == 0);
-}
-
-TEST(ExceptionCheckTest, ModifyingChecker) {
- auto set_to_1000 = [](FollowsBasicGuarantee* g) {
- g->i = 1000;
- return testing::AssertionSuccess();
- };
- auto is_1000 = [](FollowsBasicGuarantee* g) {
- return testing::AssertionResult(g->i == 1000);
- };
- auto increment = [](FollowsStrongGuarantee* g) {
- ++g->i;
- return testing::AssertionSuccess();
- };
-
- EXPECT_FALSE(tester.WithInitialValue(FollowsBasicGuarantee{})
- .WithContracts(set_to_1000, is_1000)
- .Test());
- EXPECT_TRUE(strong_tester.WithInitialValue(FollowsStrongGuarantee{})
- .WithContracts(increment)
- .Test());
- EXPECT_TRUE(testing::MakeExceptionSafetyTester()
- .WithInitialValue(HasReset{})
- .WithContracts(CheckHasResetContracts)
- .Test(invoker));
-}
-
-TEST(ExceptionSafetyTesterTest, ResetsCountdown) {
- auto test =
- testing::MakeExceptionSafetyTester()
- .WithInitialValue(ThrowingValue<>())
- .WithContracts([](ThrowingValue<>*) { return AssertionSuccess(); })
- .WithOperation([](ThrowingValue<>*) {});
- ASSERT_TRUE(test.Test());
- // If the countdown isn't reset because there were no exceptions thrown, then
- // this will fail with a termination from an unhandled exception
- EXPECT_TRUE(test.Test());
-}
-
-struct NonCopyable : public NonNegative {
- NonCopyable(const NonCopyable&) = delete;
- NonCopyable() : NonNegative{0} {}
-
- void operator()() { ThrowingValue<> bomb; }
-};
-
-TEST(ExceptionCheckTest, NonCopyable) {
- auto factory = []() { return absl::make_unique<NonCopyable>(); };
- EXPECT_TRUE(tester.WithFactory(factory).Test());
- EXPECT_TRUE(strong_tester.WithFactory(factory).Test());
-}
-
-struct NonEqualityComparable : public NonNegative {
- void operator()() { ThrowingValue<> bomb; }
-
- void ModifyOnThrow() {
- ++i;
- ThrowingValue<> bomb;
- static_cast<void>(bomb);
- --i;
- }
-};
-
-TEST(ExceptionCheckTest, NonEqualityComparable) {
- auto nec_is_strong = [](NonEqualityComparable* nec) {
- return testing::AssertionResult(nec->i == NonEqualityComparable().i);
- };
- auto strong_nec_tester = tester.WithInitialValue(NonEqualityComparable{})
- .WithContracts(nec_is_strong);
-
- EXPECT_TRUE(strong_nec_tester.Test());
- EXPECT_FALSE(strong_nec_tester.Test(
- [](NonEqualityComparable* n) { n->ModifyOnThrow(); }));
-}
-
-template <typename T>
-struct ExhaustivenessTester {
- void operator()() {
- successes |= 1;
- T b1;
- static_cast<void>(b1);
- successes |= (1 << 1);
- T b2;
- static_cast<void>(b2);
- successes |= (1 << 2);
- T b3;
- static_cast<void>(b3);
- successes |= (1 << 3);
- }
-
- bool operator==(const ExhaustivenessTester<ThrowingValue<>>&) const {
- return true;
- }
-
- static unsigned char successes;
-};
-
-struct {
- template <typename T>
- testing::AssertionResult operator()(ExhaustivenessTester<T>*) const {
- return testing::AssertionSuccess();
- }
-} CheckExhaustivenessTesterContracts;
-
-template <typename T>
-unsigned char ExhaustivenessTester<T>::successes = 0;
-
-TEST(ExceptionCheckTest, Exhaustiveness) {
- auto exhaust_tester = testing::MakeExceptionSafetyTester()
- .WithContracts(CheckExhaustivenessTesterContracts)
- .WithOperation(invoker);
-
- EXPECT_TRUE(
- exhaust_tester.WithInitialValue(ExhaustivenessTester<int>{}).Test());
- EXPECT_EQ(ExhaustivenessTester<int>::successes, 0xF);
-
- EXPECT_TRUE(
- exhaust_tester.WithInitialValue(ExhaustivenessTester<ThrowingValue<>>{})
- .WithContracts(testing::strong_guarantee)
- .Test());
- EXPECT_EQ(ExhaustivenessTester<ThrowingValue<>>::successes, 0xF);
-}
-
-struct LeaksIfCtorThrows : private exceptions_internal::TrackedObject {
- LeaksIfCtorThrows() : TrackedObject(ABSL_PRETTY_FUNCTION) {
- ++counter;
- ThrowingValue<> v;
- static_cast<void>(v);
- --counter;
- }
- LeaksIfCtorThrows(const LeaksIfCtorThrows&) noexcept
- : TrackedObject(ABSL_PRETTY_FUNCTION) {}
- static int counter;
-};
-int LeaksIfCtorThrows::counter = 0;
-
-TEST(ExceptionCheckTest, TestLeakyCtor) {
- testing::TestThrowingCtor<LeaksIfCtorThrows>();
- EXPECT_EQ(LeaksIfCtorThrows::counter, 1);
- LeaksIfCtorThrows::counter = 0;
-}
-
-struct Tracked : private exceptions_internal::TrackedObject {
- Tracked() : TrackedObject(ABSL_PRETTY_FUNCTION) {}
-};
-
-TEST(ConstructorTrackerTest, CreatedBefore) {
- Tracked a, b, c;
- exceptions_internal::ConstructorTracker ct(exceptions_internal::countdown);
-}
-
-TEST(ConstructorTrackerTest, CreatedAfter) {
- exceptions_internal::ConstructorTracker ct(exceptions_internal::countdown);
- Tracked a, b, c;
-}
-
-TEST(ConstructorTrackerTest, NotDestroyedAfter) {
- alignas(Tracked) unsigned char storage[sizeof(Tracked)];
- EXPECT_NONFATAL_FAILURE(
- {
- exceptions_internal::ConstructorTracker ct(
- exceptions_internal::countdown);
- new (&storage) Tracked();
- },
- "not destroyed");
-}
-
-TEST(ConstructorTrackerTest, DestroyedTwice) {
- exceptions_internal::ConstructorTracker ct(exceptions_internal::countdown);
- EXPECT_NONFATAL_FAILURE(
- {
- Tracked t;
- t.~Tracked();
- },
- "re-destroyed");
-}
-
-TEST(ConstructorTrackerTest, ConstructedTwice) {
- exceptions_internal::ConstructorTracker ct(exceptions_internal::countdown);
- alignas(Tracked) unsigned char storage[sizeof(Tracked)];
- EXPECT_NONFATAL_FAILURE(
- {
- new (&storage) Tracked();
- new (&storage) Tracked();
- reinterpret_cast<Tracked*>(&storage)->~Tracked();
- },
- "re-constructed");
-}
-
-TEST(ThrowingValueTraitsTest, RelationalOperators) {
- ThrowingValue<> a, b;
- EXPECT_TRUE((std::is_convertible<decltype(a == b), bool>::value));
- EXPECT_TRUE((std::is_convertible<decltype(a != b), bool>::value));
- EXPECT_TRUE((std::is_convertible<decltype(a < b), bool>::value));
- EXPECT_TRUE((std::is_convertible<decltype(a <= b), bool>::value));
- EXPECT_TRUE((std::is_convertible<decltype(a > b), bool>::value));
- EXPECT_TRUE((std::is_convertible<decltype(a >= b), bool>::value));
-}
-
-TEST(ThrowingAllocatorTraitsTest, Assignablility) {
- EXPECT_TRUE(absl::is_move_assignable<ThrowingAllocator<int>>::value);
- EXPECT_TRUE(absl::is_copy_assignable<ThrowingAllocator<int>>::value);
- EXPECT_TRUE(std::is_nothrow_move_assignable<ThrowingAllocator<int>>::value);
- EXPECT_TRUE(std::is_nothrow_copy_assignable<ThrowingAllocator<int>>::value);
-}
-
-} // namespace
-
-} // namespace testing
-
-#endif // ABSL_HAVE_EXCEPTIONS
diff --git a/third_party/abseil-cpp/absl/base/inline_variable_test.cc b/third_party/abseil-cpp/absl/base/inline_variable_test.cc
deleted file mode 100644
index 37a40e1..0000000
--- a/third_party/abseil-cpp/absl/base/inline_variable_test.cc
+++ /dev/null
@@ -1,64 +0,0 @@
-// Copyright 2017 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 <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,
- "");
-}
-
-} // namespace
-} // namespace inline_variable_testing_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/base/inline_variable_test_a.cc b/third_party/abseil-cpp/absl/base/inline_variable_test_a.cc
deleted file mode 100644
index f96a58d..0000000
--- a/third_party/abseil-cpp/absl/base/inline_variable_test_a.cc
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright 2017 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/inline_variable_testing.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace inline_variable_testing_internal {
-
-const Foo& get_foo_a() { return inline_variable_foo; }
-
-const int& get_int_a() { return inline_variable_int; }
-
-} // namespace inline_variable_testing_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/base/inline_variable_test_b.cc b/third_party/abseil-cpp/absl/base/inline_variable_test_b.cc
deleted file mode 100644
index 038adc3..0000000
--- a/third_party/abseil-cpp/absl/base/inline_variable_test_b.cc
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright 2017 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/inline_variable_testing.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace inline_variable_testing_internal {
-
-const Foo& get_foo_b() { return inline_variable_foo; }
-
-const int& get_int_b() { return inline_variable_int; }
-
-} // namespace inline_variable_testing_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/base/internal/atomic_hook.h b/third_party/abseil-cpp/absl/base/internal/atomic_hook.h
deleted file mode 100644
index ae21cd7..0000000
--- a/third_party/abseil-cpp/absl/base/internal/atomic_hook.h
+++ /dev/null
@@ -1,200 +0,0 @@
-// Copyright 2017 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_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;
-
-// To workaround AtomicHook not being constant-initializable on some platforms,
-// prefer to annotate instances with `ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES`
-// instead of `ABSL_CONST_INIT`.
-#if ABSL_HAVE_WORKING_CONSTEXPR_STATIC_INIT
-#define ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES ABSL_CONST_INIT
-#else
-#define ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES
-#endif
-
-// `AtomicHook` is a helper class, templatized on a raw function pointer type,
-// for implementing Abseil customization hooks. It is a callable object that
-// dispatches to the registered hook. Objects of type `AtomicHook` must have
-// static or thread storage duration.
-//
-// A default constructed object performs a no-op (and returns a default
-// constructed object) if no hook has been registered.
-//
-// Hooks can be pre-registered via constant initialization, for example:
-//
-// ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES static AtomicHook<void(*)()>
-// my_hook(DefaultAction);
-//
-// and then changed at runtime via a call to `Store()`.
-//
-// Reads and writes guarantee memory_order_acquire/memory_order_release
-// semantics.
-template <typename ReturnType, typename... Args>
-class AtomicHook<ReturnType (*)(Args...)> {
- public:
- using FnPtr = ReturnType (*)(Args...);
-
- // Constructs an object that by default performs a no-op (and
- // returns a default constructed object) when no hook as been registered.
- constexpr AtomicHook() : AtomicHook(DummyFunction) {}
-
- // Constructs an object that by default dispatches to/returns the
- // pre-registered default_fn when no hook has been registered at runtime.
-#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
- // As of January 2020, on all known versions of MSVC this constructor runs in
- // the global constructor sequence. If `Store()` is called by a dynamic
- // initializer, we want to preserve the value, even if this constructor runs
- // after the call to `Store()`. If not, `hook_` will be
- // zero-initialized by the linker and we have no need to set it.
- // https://developercommunity.visualstudio.com/content/problem/336946/class-with-constexpr-constructor-not-using-static.html
- explicit constexpr AtomicHook(FnPtr default_fn)
- : /* hook_(deliberately omitted), */ default_fn_(default_fn) {
- static_assert(kUninitialized == 0, "here we rely on zero-initialization");
- }
-#endif
-
- // Stores the provided function pointer as the value for this hook.
- //
- // This is intended to be called once. Multiple calls are legal only if the
- // same function pointer is provided for each call. The store is implemented
- // as a memory_order_release operation, and read accesses are implemented as
- // memory_order_acquire.
- void Store(FnPtr fn) {
- bool success = DoStore(fn);
- static_cast<void>(success);
- assert(success);
- }
-
- // Invokes the registered callback. If no callback has yet been registered, a
- // default-constructed object of the appropriate type is returned instead.
- template <typename... CallArgs>
- ReturnType operator()(CallArgs&&... args) const {
- return DoLoad()(std::forward<CallArgs>(args)...);
- }
-
- // Returns the registered callback, or nullptr if none has been registered.
- // Useful if client code needs to conditionalize behavior based on whether a
- // callback was registered.
- //
- // Note that atomic_hook.Load()() and atomic_hook() have different semantics:
- // operator()() will perform a no-op if no callback was registered, while
- // Load()() will dereference a null function pointer. Prefer operator()() to
- // Load()() unless you must conditionalize behavior on whether a hook was
- // registered.
- FnPtr Load() const {
- FnPtr ptr = DoLoad();
- return (ptr == DummyFunction) ? nullptr : ptr;
- }
-
- private:
- static ReturnType DummyFunction(Args...) {
- return ReturnType();
- }
-
- // Current versions of MSVC (as of September 2017) have a broken
- // implementation of std::atomic<T*>: Its constructor attempts to do the
- // equivalent of a reinterpret_cast in a constexpr context, which is not
- // allowed.
- //
- // This causes an issue when building with LLVM under Windows. To avoid this,
- // we use a less-efficient, intptr_t-based implementation on Windows.
-#if ABSL_HAVE_WORKING_ATOMIC_POINTER
- // Return the stored value, or DummyFunction if no value has been stored.
- FnPtr DoLoad() const { return hook_.load(std::memory_order_acquire); }
-
- // Store the given value. Returns false if a different value was already
- // stored to this object.
- 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 // !ABSL_HAVE_WORKING_ATOMIC_POINTER
- // Use a sentinel value unlikely to be the address of an actual function.
- 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
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_BASE_INTERNAL_ATOMIC_HOOK_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/atomic_hook_test.cc b/third_party/abseil-cpp/absl/base/internal/atomic_hook_test.cc
deleted file mode 100644
index e577a8f..0000000
--- a/third_party/abseil-cpp/absl/base/internal/atomic_hook_test.cc
+++ /dev/null
@@ -1,97 +0,0 @@
-// Copyright 2018 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/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;
-
- // Test the default DummyFunction.
- EXPECT_TRUE(hook.Load() == nullptr);
- EXPECT_EQ(value, 0);
- hook(1);
- EXPECT_EQ(value, 0);
-
- // Test a stored hook.
- hook.Store(TestHook);
- EXPECT_TRUE(hook.Load() == TestHook);
- EXPECT_EQ(value, 0);
- hook(1);
- EXPECT_EQ(value, 1);
-
- // Calling Store() with the same hook should not crash.
- hook.Store(TestHook);
- EXPECT_TRUE(hook.Load() == TestHook);
- EXPECT_EQ(value, 1);
- hook(2);
- EXPECT_EQ(value, 2);
-}
-
-TEST(AtomicHookTest, WithDefaultFunction) {
- // Set the default value to TestHook at compile-time.
- ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES static absl::base_internal::AtomicHook<
- void (*)(int)>
- hook(TestHook);
- value = 0;
-
- // Test the default value is TestHook.
- EXPECT_TRUE(hook.Load() == TestHook);
- EXPECT_EQ(value, 0);
- hook(1);
- EXPECT_EQ(value, 1);
-
- // Calling Store() with the same hook should not crash.
- 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) {
- // MSVC 14.2 doesn't do constexpr static init correctly; in particular it
- // tends to sequence static init (i.e. defaults) of `AtomicHook` objects
- // after their dynamic init (i.e. overrides), overwriting whatever value was
- // written during dynamic init. This regression test validates the fix.
- // https://developercommunity.visualstudio.com/content/problem/336946/class-with-constexpr-constructor-not-using-static.html
- 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));
-}
-
-} // namespace
diff --git a/third_party/abseil-cpp/absl/base/internal/atomic_hook_test_helper.cc b/third_party/abseil-cpp/absl/base/internal/atomic_hook_test_helper.cc
deleted file mode 100644
index 537d47c..0000000
--- a/third_party/abseil-cpp/absl/base/internal/atomic_hook_test_helper.cc
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright 2017 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/atomic_hook_test_helper.h"
-
-#include "absl/base/attributes.h"
-#include "absl/base/internal/atomic_hook.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace atomic_hook_internal {
-
-ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES absl::base_internal::AtomicHook<VoidF>
- func(DefaultFunc);
-ABSL_CONST_INIT int default_func_calls = 0;
-void DefaultFunc() { default_func_calls++; }
-void RegisterFunc(VoidF f) { func.Store(f); }
-
-} // namespace atomic_hook_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/base/internal/atomic_hook_test_helper.h b/third_party/abseil-cpp/absl/base/internal/atomic_hook_test_helper.h
deleted file mode 100644
index c72015e..0000000
--- a/third_party/abseil-cpp/absl/base/internal/atomic_hook_test_helper.h
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright 2017 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_ATOMIC_HOOK_TEST_HELPER_H_
-#define ABSL_BASE_INTERNAL_ATOMIC_HOOK_TEST_HELPER_H_
-
-#include "absl/base/internal/atomic_hook.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace atomic_hook_internal {
-
-using VoidF = void (*)();
-extern absl::base_internal::AtomicHook<VoidF> func;
-extern int default_func_calls;
-void DefaultFunc();
-void RegisterFunc(VoidF func);
-
-} // namespace atomic_hook_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_BASE_INTERNAL_ATOMIC_HOOK_TEST_HELPER_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/cmake_thread_test.cc b/third_party/abseil-cpp/absl/base/internal/cmake_thread_test.cc
deleted file mode 100644
index f70bb24..0000000
--- a/third_party/abseil-cpp/absl/base/internal/cmake_thread_test.cc
+++ /dev/null
@@ -1,22 +0,0 @@
-// Copyright 2018 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 <iostream>
-#include "absl/base/internal/thread_identity.h"
-
-int main() {
- auto* tid = absl::base_internal::CurrentThreadIdentityIfPresent();
- // Make sure the above call can't be optimized out
- std::cout << (void*)tid << std::endl;
-}
diff --git a/third_party/abseil-cpp/absl/base/internal/cycleclock.cc b/third_party/abseil-cpp/absl/base/internal/cycleclock.cc
deleted file mode 100644
index 902e3f5..0000000
--- a/third_party/abseil-cpp/absl/base/internal/cycleclock.cc
+++ /dev/null
@@ -1,77 +0,0 @@
-// Copyright 2017 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.
-
-// The implementation of CycleClock::Frequency.
-//
-// NOTE: only i386 and x86_64 have been well tested.
-// PPC, sparc, alpha, and ia64 are based on
-// http://peter.kuscsik.com/wordpress/?p=14
-// with modifications by m3b. See also
-// https://setisvn.ssl.berkeley.edu/svn/lib/fftw-3.0.1/kernel/cycle.h
-
-#include "absl/base/internal/cycleclock.h"
-
-#include <atomic>
-#include <chrono> // NOLINT(build/c++11)
-
-#include "absl/base/attributes.h"
-#include "absl/base/config.h"
-#include "absl/base/internal/unscaledcycleclock.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-
-#if ABSL_USE_UNSCALED_CYCLECLOCK
-
-#ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL
-constexpr int32_t CycleClock::kShift;
-constexpr double CycleClock::kFrequencyScale;
-#endif
-
-ABSL_CONST_INIT std::atomic<CycleClockSourceFunc>
- CycleClock::cycle_clock_source_{nullptr};
-
-void CycleClockSource::Register(CycleClockSourceFunc source) {
- // Corresponds to the load(std::memory_order_acquire) in LoadCycleClockSource.
- CycleClock::cycle_clock_source_.store(source, std::memory_order_release);
-}
-
-#ifdef _WIN32
-int64_t CycleClock::Now() {
- auto fn = LoadCycleClockSource();
- if (fn == nullptr) {
- return base_internal::UnscaledCycleClock::Now() >> kShift;
- }
- return fn() >> kShift;
-}
-#endif
-
-#else
-
-int64_t CycleClock::Now() {
- return std::chrono::duration_cast<std::chrono::nanoseconds>(
- std::chrono::steady_clock::now().time_since_epoch())
- .count();
-}
-
-double CycleClock::Frequency() {
- return 1e9;
-}
-
-#endif
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/base/internal/cycleclock.h b/third_party/abseil-cpp/absl/base/internal/cycleclock.h
deleted file mode 100644
index cbfdf57..0000000
--- a/third_party/abseil-cpp/absl/base/internal/cycleclock.h
+++ /dev/null
@@ -1,144 +0,0 @@
-//
-// Copyright 2017 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.
-//
-
-// -----------------------------------------------------------------------------
-// File: cycleclock.h
-// -----------------------------------------------------------------------------
-//
-// This header file defines a `CycleClock`, which yields the value and frequency
-// of a cycle counter that increments at a rate that is approximately constant.
-//
-// NOTE:
-//
-// The cycle counter frequency is not necessarily related to the core clock
-// frequency and should not be treated as such. That is, `CycleClock` cycles are
-// not necessarily "CPU cycles" and code should not rely on that behavior, even
-// if experimentally observed.
-//
-// An arbitrary offset may have been added to the counter at power on.
-//
-// On some platforms, the rate and offset of the counter may differ
-// slightly when read from different CPUs of a multiprocessor. Usually,
-// we try to ensure that the operating system adjusts values periodically
-// so that values agree approximately. If you need stronger guarantees,
-// consider using alternate interfaces.
-//
-// The CPU is not required to maintain the ordering of a cycle counter read
-// with respect to surrounding instructions.
-
-#ifndef ABSL_BASE_INTERNAL_CYCLECLOCK_H_
-#define ABSL_BASE_INTERNAL_CYCLECLOCK_H_
-
-#include <atomic>
-#include <cstdint>
-
-#include "absl/base/attributes.h"
-#include "absl/base/config.h"
-#include "absl/base/internal/cycleclock_config.h"
-#include "absl/base/internal/unscaledcycleclock.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-
-using CycleClockSourceFunc = int64_t (*)();
-
-// -----------------------------------------------------------------------------
-// CycleClock
-// -----------------------------------------------------------------------------
-class CycleClock {
- public:
- // CycleClock::Now()
- //
- // Returns the value of a cycle counter that counts at a rate that is
- // approximately constant.
- static int64_t Now();
-
- // CycleClock::Frequency()
- //
- // Returns the amount by which `CycleClock::Now()` increases per second. Note
- // that this value may not necessarily match the core CPU clock frequency.
- static double Frequency();
-
- private:
-#if ABSL_USE_UNSCALED_CYCLECLOCK
- static CycleClockSourceFunc LoadCycleClockSource();
-
- static constexpr int32_t kShift = kCycleClockShift;
- static constexpr double kFrequencyScale = kCycleClockFrequencyScale;
-
- ABSL_CONST_INIT static std::atomic<CycleClockSourceFunc> cycle_clock_source_;
-#endif // ABSL_USE_UNSCALED_CYCLECLOC
-
- CycleClock() = delete; // no instances
- CycleClock(const CycleClock&) = delete;
- CycleClock& operator=(const CycleClock&) = delete;
-
- friend class CycleClockSource;
-};
-
-class CycleClockSource {
- private:
- // CycleClockSource::Register()
- //
- // Register a function that provides an alternate source for the unscaled CPU
- // cycle count value. The source function must be async signal safe, must not
- // call CycleClock::Now(), and must have a frequency that matches that of the
- // unscaled clock used by CycleClock. A nullptr value resets CycleClock to use
- // the default source.
- static void Register(CycleClockSourceFunc source);
-};
-
-#if ABSL_USE_UNSCALED_CYCLECLOCK
-
-inline CycleClockSourceFunc CycleClock::LoadCycleClockSource() {
-#if !defined(__x86_64__)
- // Optimize for the common case (no callback) by first doing a relaxed load;
- // this is significantly faster on non-x86 platforms.
- if (cycle_clock_source_.load(std::memory_order_relaxed) == nullptr) {
- return nullptr;
- }
-#endif // !defined(__x86_64__)
-
- // This corresponds to the store(std::memory_order_release) in
- // CycleClockSource::Register, and makes sure that any updates made prior to
- // registering the callback are visible to this thread before the callback
- // is invoked.
- return cycle_clock_source_.load(std::memory_order_acquire);
-}
-
-// Accessing globals in inlined code in Window DLLs is problematic.
-#ifndef _WIN32
-inline int64_t CycleClock::Now() {
- auto fn = LoadCycleClockSource();
- if (fn == nullptr) {
- return base_internal::UnscaledCycleClock::Now() >> kShift;
- }
- return fn() >> kShift;
-}
-#endif
-
-inline double CycleClock::Frequency() {
- return kFrequencyScale * base_internal::UnscaledCycleClock::Frequency();
-}
-
-#endif // ABSL_USE_UNSCALED_CYCLECLOCK
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_BASE_INTERNAL_CYCLECLOCK_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/cycleclock_config.h b/third_party/abseil-cpp/absl/base/internal/cycleclock_config.h
deleted file mode 100644
index 191112b..0000000
--- a/third_party/abseil-cpp/absl/base/internal/cycleclock_config.h
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright 2022 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_CYCLECLOCK_CONFIG_H_
-#define ABSL_BASE_INTERNAL_CYCLECLOCK_CONFIG_H_
-
-#include <cstdint>
-
-#include "absl/base/config.h"
-#include "absl/base/internal/inline_variable.h"
-#include "absl/base/internal/unscaledcycleclock_config.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-
-#if ABSL_USE_UNSCALED_CYCLECLOCK
-#ifdef NDEBUG
-#ifdef ABSL_INTERNAL_UNSCALED_CYCLECLOCK_FREQUENCY_IS_CPU_FREQUENCY
-// Not debug mode and the UnscaledCycleClock frequency is the CPU
-// frequency. Scale the CycleClock to prevent overflow if someone
-// tries to represent the time as cycles since the Unix epoch.
-ABSL_INTERNAL_INLINE_CONSTEXPR(int32_t, kCycleClockShift, 1);
-#else
-// Not debug mode and the UnscaledCycleClock isn't operating at the
-// raw CPU frequency. There is no need to do any scaling, so don't
-// needlessly sacrifice precision.
-ABSL_INTERNAL_INLINE_CONSTEXPR(int32_t, kCycleClockShift, 0);
-#endif
-#else // NDEBUG
-// In debug mode use a different shift to discourage depending on a
-// particular shift value.
-ABSL_INTERNAL_INLINE_CONSTEXPR(int32_t, kCycleClockShift, 2);
-#endif // NDEBUG
-
-ABSL_INTERNAL_INLINE_CONSTEXPR(double, kCycleClockFrequencyScale,
- 1.0 / (1 << kCycleClockShift));
-#endif // ABSL_USE_UNSCALED_CYCLECLOC
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_BASE_INTERNAL_CYCLECLOCK_CONFIG_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/direct_mmap.h b/third_party/abseil-cpp/absl/base/internal/direct_mmap.h
deleted file mode 100644
index 815b8d2..0000000
--- a/third_party/abseil-cpp/absl/base/internal/direct_mmap.h
+++ /dev/null
@@ -1,170 +0,0 @@
-// Copyright 2017 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.
-//
-// Functions for directly invoking mmap() via syscall, avoiding the case where
-// mmap() has been locally overridden.
-
-#ifndef ABSL_BASE_INTERNAL_DIRECT_MMAP_H_
-#define ABSL_BASE_INTERNAL_DIRECT_MMAP_H_
-
-#include "absl/base/config.h"
-
-#ifdef ABSL_HAVE_MMAP
-
-#include <sys/mman.h>
-
-#ifdef __linux__
-
-#include <sys/types.h>
-#ifdef __BIONIC__
-#include <sys/syscall.h>
-#else
-#include <syscall.h>
-#endif
-
-#include <linux/unistd.h>
-#include <unistd.h>
-#include <cerrno>
-#include <cstdarg>
-#include <cstdint>
-
-#ifdef __mips__
-// Include definitions of the ABI currently in use.
-#if defined(__BIONIC__) || !defined(__GLIBC__)
-// Android doesn't have sgidefs.h, but does have asm/sgidefs.h, which has the
-// definitions we need.
-#include <asm/sgidefs.h>
-#else
-#include <sgidefs.h>
-#endif // __BIONIC__ || !__GLIBC__
-#endif // __mips__
-
-// SYS_mmap and SYS_munmap are not defined in Android.
-#ifdef __BIONIC__
-extern "C" void* __mmap2(void*, size_t, int, int, int, size_t);
-#if defined(__NR_mmap) && !defined(SYS_mmap)
-#define SYS_mmap __NR_mmap
-#endif
-#ifndef SYS_munmap
-#define SYS_munmap __NR_munmap
-#endif
-#endif // __BIONIC__
-
-#if defined(__NR_mmap2) && !defined(SYS_mmap2)
-#define SYS_mmap2 __NR_mmap2
-#endif
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-
-// Platform specific logic extracted from
-// https://chromium.googlesource.com/linux-syscall-support/+/master/linux_syscall_support.h
-inline void* DirectMmap(void* start, size_t length, int prot, int flags, int fd,
- off64_t offset) noexcept {
-#if defined(__i386__) || defined(__ARM_ARCH_3__) || defined(__ARM_EABI__) || \
- defined(__m68k__) || defined(__sh__) || \
- (defined(__hppa__) && !defined(__LP64__)) || \
- (defined(__mips__) && _MIPS_SIM == _MIPS_SIM_ABI32) || \
- (defined(__PPC__) && !defined(__PPC64__)) || \
- (defined(__riscv) && __riscv_xlen == 32) || \
- (defined(__s390__) && !defined(__s390x__)) || \
- (defined(__sparc__) && !defined(__arch64__))
- // On these architectures, implement mmap with mmap2.
- static int pagesize = 0;
- if (pagesize == 0) {
-#if defined(__wasm__) || defined(__asmjs__)
- pagesize = getpagesize();
-#else
- pagesize = sysconf(_SC_PAGESIZE);
-#endif
- }
- if (offset < 0 || offset % pagesize != 0) {
- errno = EINVAL;
- return MAP_FAILED;
- }
-#ifdef __BIONIC__
- // SYS_mmap2 has problems on Android API level <= 16.
- // Workaround by invoking __mmap2() instead.
- return __mmap2(start, length, prot, flags, fd,
- static_cast<size_t>(offset / pagesize));
-#else
- return reinterpret_cast<void*>(
- syscall(SYS_mmap2, start, length, prot, flags, fd,
- static_cast<off_t>(offset / pagesize)));
-#endif
-#elif defined(__s390x__)
- // On s390x, mmap() arguments are passed in memory.
- unsigned long buf[6] = {reinterpret_cast<unsigned long>(start), // NOLINT
- static_cast<unsigned long>(length), // NOLINT
- static_cast<unsigned long>(prot), // NOLINT
- static_cast<unsigned long>(flags), // NOLINT
- static_cast<unsigned long>(fd), // NOLINT
- static_cast<unsigned long>(offset)}; // NOLINT
- return reinterpret_cast<void*>(syscall(SYS_mmap, buf));
-#elif defined(__x86_64__)
-// The x32 ABI has 32 bit longs, but the syscall interface is 64 bit.
-// We need to explicitly cast to an unsigned 64 bit type to avoid implicit
-// sign extension. We can't cast pointers directly because those are
-// 32 bits, and gcc will dump ugly warnings about casting from a pointer
-// to an integer of a different size. We also need to make sure __off64_t
-// isn't truncated to 32-bits under x32.
-#define MMAP_SYSCALL_ARG(x) ((uint64_t)(uintptr_t)(x))
- return reinterpret_cast<void*>(
- syscall(SYS_mmap, MMAP_SYSCALL_ARG(start), MMAP_SYSCALL_ARG(length),
- MMAP_SYSCALL_ARG(prot), MMAP_SYSCALL_ARG(flags),
- MMAP_SYSCALL_ARG(fd), static_cast<uint64_t>(offset)));
-#undef MMAP_SYSCALL_ARG
-#else // Remaining 64-bit aritectures.
- static_assert(sizeof(unsigned long) == 8, "Platform is not 64-bit");
- return reinterpret_cast<void*>(
- syscall(SYS_mmap, start, length, prot, flags, fd, offset));
-#endif
-}
-
-inline int DirectMunmap(void* start, size_t length) {
- return static_cast<int>(syscall(SYS_munmap, start, length));
-}
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#else // !__linux__
-
-// For non-linux platforms where we have mmap, just dispatch directly to the
-// actual mmap()/munmap() methods.
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-
-inline void* DirectMmap(void* start, size_t length, int prot, int flags, int fd,
- off_t offset) {
- return mmap(start, length, prot, flags, fd, offset);
-}
-
-inline int DirectMunmap(void* start, size_t length) {
- return munmap(start, length);
-}
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // __linux__
-
-#endif // ABSL_HAVE_MMAP
-
-#endif // ABSL_BASE_INTERNAL_DIRECT_MMAP_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/endian.h b/third_party/abseil-cpp/absl/base/internal/endian.h
deleted file mode 100644
index 50747d7..0000000
--- a/third_party/abseil-cpp/absl/base/internal/endian.h
+++ /dev/null
@@ -1,282 +0,0 @@
-// Copyright 2017 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_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/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
-
-// Portable definitions for htonl (host-to-network) and friends on little-endian
-// architectures.
-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
-
-// Portable definitions for htonl (host-to-network) etc on big-endian
-// architectures. These definitions are simpler since the host byte order is the
-// same as network byte order.
-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 // byte order
-
-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); }
-
-// Utilities to convert numbers between the current hosts's native byte
-// order and little-endian byte order
-//
-// Load/Store methods are alignment safe
-namespace little_endian {
-// Conversion functions.
-#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 /* ENDIAN */
-
-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)));
-}
-
-// Functions to do unaligned loads and stores in little-endian order.
-inline uint16_t Load16(const void *p) {
- return ToHost16(ABSL_INTERNAL_UNALIGNED_LOAD16(p));
-}
-
-inline void Store16(void *p, uint16_t v) {
- ABSL_INTERNAL_UNALIGNED_STORE16(p, FromHost16(v));
-}
-
-inline uint32_t Load32(const void *p) {
- return ToHost32(ABSL_INTERNAL_UNALIGNED_LOAD32(p));
-}
-
-inline void Store32(void *p, uint32_t v) {
- ABSL_INTERNAL_UNALIGNED_STORE32(p, FromHost32(v));
-}
-
-inline uint64_t Load64(const void *p) {
- return ToHost64(ABSL_INTERNAL_UNALIGNED_LOAD64(p));
-}
-
-inline void Store64(void *p, uint64_t v) {
- ABSL_INTERNAL_UNALIGNED_STORE64(p, FromHost64(v));
-}
-
-} // namespace little_endian
-
-// Utilities to convert numbers between the current hosts's native byte
-// order and big-endian byte order (same as network byte order)
-//
-// Load/Store methods are alignment safe
-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 /* ENDIAN */
-
-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)));
-}
-
-// Functions to do unaligned loads and stores in big-endian order.
-inline uint16_t Load16(const void *p) {
- return ToHost16(ABSL_INTERNAL_UNALIGNED_LOAD16(p));
-}
-
-inline void Store16(void *p, uint16_t v) {
- ABSL_INTERNAL_UNALIGNED_STORE16(p, FromHost16(v));
-}
-
-inline uint32_t Load32(const void *p) {
- return ToHost32(ABSL_INTERNAL_UNALIGNED_LOAD32(p));
-}
-
-inline void Store32(void *p, uint32_t v) {
- ABSL_INTERNAL_UNALIGNED_STORE32(p, FromHost32(v));
-}
-
-inline uint64_t Load64(const void *p) {
- return ToHost64(ABSL_INTERNAL_UNALIGNED_LOAD64(p));
-}
-
-inline void Store64(void *p, uint64_t v) {
- ABSL_INTERNAL_UNALIGNED_STORE64(p, FromHost64(v));
-}
-
-} // namespace big_endian
-
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_BASE_INTERNAL_ENDIAN_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/endian_test.cc b/third_party/abseil-cpp/absl/base/internal/endian_test.cc
deleted file mode 100644
index a1691b1..0000000
--- a/third_party/abseil-cpp/absl/base/internal/endian_test.cc
+++ /dev/null
@@ -1,263 +0,0 @@
-// Copyright 2017 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/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:
- // Suppresses invalid "not all control paths return a value" on MSVC
- return {};
- }
-}
-
-template <typename T, typename ByteSwapper>
-static void GBSwapHelper(const std::vector<T>& host_values_to_test,
- const ByteSwapper& byte_swapper) {
- // Test byte_swapper against a manual byte swap.
- 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) {
- // Test that absl::ghtonl compiles correctly
- 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);
-
- // Test that htonll and ntohll are each others' inverse functions on a
- // somewhat assorted batch of numbers. 37 is chosen to not be anything
- // particularly nice base 2.
- 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) {
- // Check little_endian uint16_t.
- uint64_t comp = little_endian::FromHost16(k16Value);
- EXPECT_EQ(comp, k16ValueLE);
- comp = little_endian::ToHost16(k16ValueLE);
- EXPECT_EQ(comp, k16Value);
-
- // Check little_endian uint32_t.
- comp = little_endian::FromHost32(k32Value);
- EXPECT_EQ(comp, k32ValueLE);
- comp = little_endian::ToHost32(k32ValueLE);
- EXPECT_EQ(comp, k32Value);
-
- // Check little_endian uint64_t.
- comp = little_endian::FromHost64(k64Value);
- EXPECT_EQ(comp, k64ValueLE);
- comp = little_endian::ToHost64(k64ValueLE);
- EXPECT_EQ(comp, k64Value);
-
- // Check little-endian Load and store functions.
- 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) {
- // Check big-endian Load and store functions.
- 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);
-}
-
-} // namespace
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/base/internal/errno_saver.h b/third_party/abseil-cpp/absl/base/internal/errno_saver.h
deleted file mode 100644
index 251de51..0000000
--- a/third_party/abseil-cpp/absl/base/internal/errno_saver.h
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright 2017 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_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 {
-
-// `ErrnoSaver` captures the value of `errno` upon construction and restores it
-// upon deletion. It is used in low-level code and must be super fast. Do not
-// add instrumentation, even in debug modes.
-class ErrnoSaver {
- public:
- ErrnoSaver() : saved_errno_(errno) {}
- ~ErrnoSaver() { errno = saved_errno_; }
- int operator()() const { return saved_errno_; }
-
- private:
- const int saved_errno_;
-};
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_BASE_INTERNAL_ERRNO_SAVER_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/errno_saver_test.cc b/third_party/abseil-cpp/absl/base/internal/errno_saver_test.cc
deleted file mode 100644
index e9b742c..0000000
--- a/third_party/abseil-cpp/absl/base/internal/errno_saver_test.cc
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright 2018 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/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}));
-}
-} // namespace
diff --git a/third_party/abseil-cpp/absl/base/internal/exception_safety_testing.cc b/third_party/abseil-cpp/absl/base/internal/exception_safety_testing.cc
deleted file mode 100644
index 6ccac41..0000000
--- a/third_party/abseil-cpp/absl/base/internal/exception_safety_testing.cc
+++ /dev/null
@@ -1,79 +0,0 @@
-// Copyright 2017 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/exception_safety_testing.h"
-
-#ifdef ABSL_HAVE_EXCEPTIONS
-
-#include "gtest/gtest.h"
-#include "absl/meta/type_traits.h"
-
-namespace testing {
-
-exceptions_internal::NoThrowTag nothrow_ctor;
-
-exceptions_internal::StrongGuaranteeTagType strong_guarantee;
-
-exceptions_internal::ExceptionSafetyTestBuilder<> MakeExceptionSafetyTester() {
- return {};
-}
-
-namespace exceptions_internal {
-
-int countdown = -1;
-
-ConstructorTracker* ConstructorTracker::current_tracker_instance_ = nullptr;
-
-void MaybeThrow(absl::string_view msg, bool throw_bad_alloc) {
- if (countdown-- == 0) {
- if (throw_bad_alloc) throw TestBadAllocException(msg);
- throw TestException(msg);
- }
-}
-
-testing::AssertionResult FailureMessage(const TestException& e,
- int countdown) noexcept {
- return testing::AssertionFailure() << "Exception thrown from " << e.what();
-}
-
-std::string GetSpecString(TypeSpec spec) {
- std::string out;
- absl::string_view sep;
- const auto append = [&](absl::string_view s) {
- absl::StrAppend(&out, sep, s);
- sep = " | ";
- };
- if (static_cast<bool>(TypeSpec::kNoThrowCopy & spec)) {
- append("kNoThrowCopy");
- }
- if (static_cast<bool>(TypeSpec::kNoThrowMove & spec)) {
- append("kNoThrowMove");
- }
- if (static_cast<bool>(TypeSpec::kNoThrowNew & spec)) {
- append("kNoThrowNew");
- }
- return out;
-}
-
-std::string GetSpecString(AllocSpec spec) {
- return static_cast<bool>(AllocSpec::kNoThrowAllocate & spec)
- ? "kNoThrowAllocate"
- : "";
-}
-
-} // namespace exceptions_internal
-
-} // namespace testing
-
-#endif // ABSL_HAVE_EXCEPTIONS
diff --git a/third_party/abseil-cpp/absl/base/internal/exception_safety_testing.h b/third_party/abseil-cpp/absl/base/internal/exception_safety_testing.h
deleted file mode 100644
index 77a5aec..0000000
--- a/third_party/abseil-cpp/absl/base/internal/exception_safety_testing.h
+++ /dev/null
@@ -1,1109 +0,0 @@
-// Copyright 2017 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.
-
-// Utilities for testing exception-safety
-
-#ifndef ABSL_BASE_INTERNAL_EXCEPTION_SAFETY_TESTING_H_
-#define ABSL_BASE_INTERNAL_EXCEPTION_SAFETY_TESTING_H_
-
-#include "absl/base/config.h"
-
-#ifdef ABSL_HAVE_EXCEPTIONS
-
-#include <cstddef>
-#include <cstdint>
-#include <functional>
-#include <initializer_list>
-#include <iosfwd>
-#include <string>
-#include <tuple>
-#include <unordered_map>
-
-#include "gtest/gtest.h"
-#include "absl/base/internal/pretty_function.h"
-#include "absl/memory/memory.h"
-#include "absl/meta/type_traits.h"
-#include "absl/strings/string_view.h"
-#include "absl/strings/substitute.h"
-#include "absl/utility/utility.h"
-
-namespace testing {
-
-enum class TypeSpec;
-enum class AllocSpec;
-
-constexpr TypeSpec operator|(TypeSpec a, TypeSpec b) {
- using T = absl::underlying_type_t<TypeSpec>;
- return static_cast<TypeSpec>(static_cast<T>(a) | static_cast<T>(b));
-}
-
-constexpr TypeSpec operator&(TypeSpec a, TypeSpec b) {
- using T = absl::underlying_type_t<TypeSpec>;
- return static_cast<TypeSpec>(static_cast<T>(a) & static_cast<T>(b));
-}
-
-constexpr AllocSpec operator|(AllocSpec a, AllocSpec b) {
- using T = absl::underlying_type_t<AllocSpec>;
- return static_cast<AllocSpec>(static_cast<T>(a) | static_cast<T>(b));
-}
-
-constexpr AllocSpec operator&(AllocSpec a, AllocSpec b) {
- using T = absl::underlying_type_t<AllocSpec>;
- return static_cast<AllocSpec>(static_cast<T>(a) & static_cast<T>(b));
-}
-
-namespace exceptions_internal {
-
-std::string GetSpecString(TypeSpec);
-std::string GetSpecString(AllocSpec);
-
-struct NoThrowTag {};
-struct StrongGuaranteeTagType {};
-
-// A simple exception class. We throw this so that test code can catch
-// exceptions specifically thrown by ThrowingValue.
-class TestException {
- public:
- explicit TestException(absl::string_view msg) : msg_(msg) {}
- virtual ~TestException() {}
- virtual const char* what() const noexcept { return msg_.c_str(); }
-
- private:
- std::string msg_;
-};
-
-// TestBadAllocException exists because allocation functions must throw an
-// exception which can be caught by a handler of std::bad_alloc. We use a child
-// class of std::bad_alloc so we can customise the error message, and also
-// derive from TestException so we don't accidentally end up catching an actual
-// bad_alloc exception in TestExceptionSafety.
-class TestBadAllocException : public std::bad_alloc, public TestException {
- public:
- explicit TestBadAllocException(absl::string_view msg) : TestException(msg) {}
- using TestException::what;
-};
-
-extern int countdown;
-
-// Allows the countdown variable to be set manually (defaulting to the initial
-// value of 0)
-inline void SetCountdown(int i = 0) { countdown = i; }
-// Sets the countdown to the terminal value -1
-inline void UnsetCountdown() { SetCountdown(-1); }
-
-void MaybeThrow(absl::string_view msg, bool throw_bad_alloc = false);
-
-testing::AssertionResult FailureMessage(const TestException& e,
- int countdown) noexcept;
-
-struct TrackedAddress {
- bool is_alive;
- std::string description;
-};
-
-// Inspects the constructions and destructions of anything inheriting from
-// TrackedObject. This allows us to safely "leak" TrackedObjects, as
-// ConstructorTracker will destroy everything left over in its destructor.
-class ConstructorTracker {
- public:
- explicit ConstructorTracker(int count) : countdown_(count) {
- assert(current_tracker_instance_ == nullptr);
- current_tracker_instance_ = this;
- }
-
- ~ConstructorTracker() {
- assert(current_tracker_instance_ == this);
- current_tracker_instance_ = nullptr;
-
- for (auto& it : address_map_) {
- void* address = it.first;
- TrackedAddress& tracked_address = it.second;
- if (tracked_address.is_alive) {
- ADD_FAILURE() << ErrorMessage(address, tracked_address.description,
- countdown_, "Object was not destroyed.");
- }
- }
- }
-
- static void ObjectConstructed(void* address, std::string description) {
- if (!CurrentlyTracking()) return;
-
- TrackedAddress& tracked_address =
- current_tracker_instance_->address_map_[address];
- if (tracked_address.is_alive) {
- ADD_FAILURE() << ErrorMessage(
- address, tracked_address.description,
- current_tracker_instance_->countdown_,
- "Object was re-constructed. Current object was constructed by " +
- description);
- }
- tracked_address = {true, std::move(description)};
- }
-
- static void ObjectDestructed(void* address) {
- if (!CurrentlyTracking()) return;
-
- auto it = current_tracker_instance_->address_map_.find(address);
- // Not tracked. Ignore.
- if (it == current_tracker_instance_->address_map_.end()) return;
-
- TrackedAddress& tracked_address = it->second;
- if (!tracked_address.is_alive) {
- ADD_FAILURE() << ErrorMessage(address, tracked_address.description,
- current_tracker_instance_->countdown_,
- "Object was re-destroyed.");
- }
- tracked_address.is_alive = false;
- }
-
- private:
- static bool CurrentlyTracking() {
- return current_tracker_instance_ != nullptr;
- }
-
- static std::string ErrorMessage(void* address,
- const std::string& address_description,
- int countdown,
- const std::string& error_description) {
- return absl::Substitute(
- "With coundtown at $0:\n"
- " $1\n"
- " Object originally constructed by $2\n"
- " Object address: $3\n",
- countdown, error_description, address_description, address);
- }
-
- std::unordered_map<void*, TrackedAddress> address_map_;
- int countdown_;
-
- static ConstructorTracker* current_tracker_instance_;
-};
-
-class TrackedObject {
- public:
- TrackedObject(const TrackedObject&) = delete;
- TrackedObject(TrackedObject&&) = delete;
-
- protected:
- explicit TrackedObject(std::string description) {
- ConstructorTracker::ObjectConstructed(this, std::move(description));
- }
-
- ~TrackedObject() noexcept { ConstructorTracker::ObjectDestructed(this); }
-};
-} // namespace exceptions_internal
-
-extern exceptions_internal::NoThrowTag nothrow_ctor;
-
-extern exceptions_internal::StrongGuaranteeTagType strong_guarantee;
-
-// A test class which is convertible to bool. The conversion can be
-// instrumented to throw at a controlled time.
-class ThrowingBool {
- public:
- ThrowingBool(bool b) noexcept : b_(b) {} // NOLINT(runtime/explicit)
- operator bool() const { // NOLINT
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- return b_;
- }
-
- private:
- bool b_;
-};
-
-/*
- * Configuration enum for the ThrowingValue type that defines behavior for the
- * lifetime of the instance. Use testing::nothrow_ctor to prevent the integer
- * constructor from throwing.
- *
- * kEverythingThrows: Every operation can throw an exception
- * kNoThrowCopy: Copy construction and copy assignment will not throw
- * kNoThrowMove: Move construction and move assignment will not throw
- * kNoThrowNew: Overloaded operators new and new[] will not throw
- */
-enum class TypeSpec {
- kEverythingThrows = 0,
- kNoThrowCopy = 1,
- kNoThrowMove = 1 << 1,
- kNoThrowNew = 1 << 2,
-};
-
-/*
- * A testing class instrumented to throw an exception at a controlled time.
- *
- * ThrowingValue implements a slightly relaxed version of the Regular concept --
- * that is it's a value type with the expected semantics. It also implements
- * arithmetic operations. It doesn't implement member and pointer operators
- * like operator-> or operator[].
- *
- * ThrowingValue can be instrumented to have certain operations be noexcept by
- * using compile-time bitfield template arguments. That is, to make an
- * ThrowingValue which has noexcept move construction/assignment and noexcept
- * copy construction/assignment, use the following:
- * ThrowingValue<testing::kNoThrowMove | testing::kNoThrowCopy> my_thrwr{val};
- */
-template <TypeSpec Spec = TypeSpec::kEverythingThrows>
-class ThrowingValue : private exceptions_internal::TrackedObject {
- static constexpr bool IsSpecified(TypeSpec spec) {
- return static_cast<bool>(Spec & spec);
- }
-
- static constexpr int kDefaultValue = 0;
- static constexpr int kBadValue = 938550620;
-
- public:
- ThrowingValue() : TrackedObject(GetInstanceString(kDefaultValue)) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- dummy_ = kDefaultValue;
- }
-
- ThrowingValue(const ThrowingValue& other) noexcept(
- IsSpecified(TypeSpec::kNoThrowCopy))
- : TrackedObject(GetInstanceString(other.dummy_)) {
- if (!IsSpecified(TypeSpec::kNoThrowCopy)) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- }
- dummy_ = other.dummy_;
- }
-
- ThrowingValue(ThrowingValue&& other) noexcept(
- IsSpecified(TypeSpec::kNoThrowMove))
- : TrackedObject(GetInstanceString(other.dummy_)) {
- if (!IsSpecified(TypeSpec::kNoThrowMove)) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- }
- dummy_ = other.dummy_;
- }
-
- explicit ThrowingValue(int i) : TrackedObject(GetInstanceString(i)) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- dummy_ = i;
- }
-
- ThrowingValue(int i, exceptions_internal::NoThrowTag) noexcept
- : TrackedObject(GetInstanceString(i)), dummy_(i) {}
-
- // absl expects nothrow destructors
- ~ThrowingValue() noexcept = default;
-
- ThrowingValue& operator=(const ThrowingValue& other) noexcept(
- IsSpecified(TypeSpec::kNoThrowCopy)) {
- dummy_ = kBadValue;
- if (!IsSpecified(TypeSpec::kNoThrowCopy)) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- }
- dummy_ = other.dummy_;
- return *this;
- }
-
- ThrowingValue& operator=(ThrowingValue&& other) noexcept(
- IsSpecified(TypeSpec::kNoThrowMove)) {
- dummy_ = kBadValue;
- if (!IsSpecified(TypeSpec::kNoThrowMove)) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- }
- dummy_ = other.dummy_;
- return *this;
- }
-
- // Arithmetic Operators
- ThrowingValue operator+(const ThrowingValue& other) const {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- return ThrowingValue(dummy_ + other.dummy_, nothrow_ctor);
- }
-
- ThrowingValue operator+() const {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- return ThrowingValue(dummy_, nothrow_ctor);
- }
-
- ThrowingValue operator-(const ThrowingValue& other) const {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- return ThrowingValue(dummy_ - other.dummy_, nothrow_ctor);
- }
-
- ThrowingValue operator-() const {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- return ThrowingValue(-dummy_, nothrow_ctor);
- }
-
- ThrowingValue& operator++() {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- ++dummy_;
- return *this;
- }
-
- ThrowingValue operator++(int) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- auto out = ThrowingValue(dummy_, nothrow_ctor);
- ++dummy_;
- return out;
- }
-
- ThrowingValue& operator--() {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- --dummy_;
- return *this;
- }
-
- ThrowingValue operator--(int) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- auto out = ThrowingValue(dummy_, nothrow_ctor);
- --dummy_;
- return out;
- }
-
- ThrowingValue operator*(const ThrowingValue& other) const {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- return ThrowingValue(dummy_ * other.dummy_, nothrow_ctor);
- }
-
- ThrowingValue operator/(const ThrowingValue& other) const {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- return ThrowingValue(dummy_ / other.dummy_, nothrow_ctor);
- }
-
- ThrowingValue operator%(const ThrowingValue& other) const {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- return ThrowingValue(dummy_ % other.dummy_, nothrow_ctor);
- }
-
- ThrowingValue operator<<(int shift) const {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- return ThrowingValue(dummy_ << shift, nothrow_ctor);
- }
-
- ThrowingValue operator>>(int shift) const {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- return ThrowingValue(dummy_ >> shift, nothrow_ctor);
- }
-
- // Comparison Operators
- // NOTE: We use `ThrowingBool` instead of `bool` because most STL
- // types/containers requires T to be convertible to bool.
- friend ThrowingBool operator==(const ThrowingValue& a,
- const ThrowingValue& b) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- return a.dummy_ == b.dummy_;
- }
- friend ThrowingBool operator!=(const ThrowingValue& a,
- const ThrowingValue& b) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- return a.dummy_ != b.dummy_;
- }
- friend ThrowingBool operator<(const ThrowingValue& a,
- const ThrowingValue& b) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- return a.dummy_ < b.dummy_;
- }
- friend ThrowingBool operator<=(const ThrowingValue& a,
- const ThrowingValue& b) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- return a.dummy_ <= b.dummy_;
- }
- friend ThrowingBool operator>(const ThrowingValue& a,
- const ThrowingValue& b) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- return a.dummy_ > b.dummy_;
- }
- friend ThrowingBool operator>=(const ThrowingValue& a,
- const ThrowingValue& b) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- return a.dummy_ >= b.dummy_;
- }
-
- // Logical Operators
- ThrowingBool operator!() const {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- return !dummy_;
- }
-
- ThrowingBool operator&&(const ThrowingValue& other) const {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- return dummy_ && other.dummy_;
- }
-
- ThrowingBool operator||(const ThrowingValue& other) const {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- return dummy_ || other.dummy_;
- }
-
- // Bitwise Logical Operators
- ThrowingValue operator~() const {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- return ThrowingValue(~dummy_, nothrow_ctor);
- }
-
- ThrowingValue operator&(const ThrowingValue& other) const {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- return ThrowingValue(dummy_ & other.dummy_, nothrow_ctor);
- }
-
- ThrowingValue operator|(const ThrowingValue& other) const {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- return ThrowingValue(dummy_ | other.dummy_, nothrow_ctor);
- }
-
- ThrowingValue operator^(const ThrowingValue& other) const {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- return ThrowingValue(dummy_ ^ other.dummy_, nothrow_ctor);
- }
-
- // Compound Assignment operators
- ThrowingValue& operator+=(const ThrowingValue& other) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- dummy_ += other.dummy_;
- return *this;
- }
-
- ThrowingValue& operator-=(const ThrowingValue& other) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- dummy_ -= other.dummy_;
- return *this;
- }
-
- ThrowingValue& operator*=(const ThrowingValue& other) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- dummy_ *= other.dummy_;
- return *this;
- }
-
- ThrowingValue& operator/=(const ThrowingValue& other) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- dummy_ /= other.dummy_;
- return *this;
- }
-
- ThrowingValue& operator%=(const ThrowingValue& other) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- dummy_ %= other.dummy_;
- return *this;
- }
-
- ThrowingValue& operator&=(const ThrowingValue& other) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- dummy_ &= other.dummy_;
- return *this;
- }
-
- ThrowingValue& operator|=(const ThrowingValue& other) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- dummy_ |= other.dummy_;
- return *this;
- }
-
- ThrowingValue& operator^=(const ThrowingValue& other) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- dummy_ ^= other.dummy_;
- return *this;
- }
-
- ThrowingValue& operator<<=(int shift) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- dummy_ <<= shift;
- return *this;
- }
-
- ThrowingValue& operator>>=(int shift) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- dummy_ >>= shift;
- return *this;
- }
-
- // Pointer operators
- void operator&() const = delete; // NOLINT(runtime/operator)
-
- // Stream operators
- friend std::ostream& operator<<(std::ostream& os, const ThrowingValue& tv) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- return os << GetInstanceString(tv.dummy_);
- }
-
- friend std::istream& operator>>(std::istream& is, const ThrowingValue&) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- return is;
- }
-
- // Memory management operators
- static void* operator new(size_t s) noexcept(
- IsSpecified(TypeSpec::kNoThrowNew)) {
- if (!IsSpecified(TypeSpec::kNoThrowNew)) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION, true);
- }
- return ::operator new(s);
- }
-
- static void* operator new[](size_t s) noexcept(
- IsSpecified(TypeSpec::kNoThrowNew)) {
- if (!IsSpecified(TypeSpec::kNoThrowNew)) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION, true);
- }
- return ::operator new[](s);
- }
-
- template <typename... Args>
- static void* operator new(size_t s, Args&&... args) noexcept(
- IsSpecified(TypeSpec::kNoThrowNew)) {
- if (!IsSpecified(TypeSpec::kNoThrowNew)) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION, true);
- }
- return ::operator new(s, std::forward<Args>(args)...);
- }
-
- template <typename... Args>
- static void* operator new[](size_t s, Args&&... args) noexcept(
- IsSpecified(TypeSpec::kNoThrowNew)) {
- if (!IsSpecified(TypeSpec::kNoThrowNew)) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION, true);
- }
- return ::operator new[](s, std::forward<Args>(args)...);
- }
-
- // Abseil doesn't support throwing overloaded operator delete. These are
- // provided so a throwing operator-new can clean up after itself.
- void operator delete(void* p) noexcept { ::operator delete(p); }
-
- template <typename... Args>
- void operator delete(void* p, Args&&... args) noexcept {
- ::operator delete(p, std::forward<Args>(args)...);
- }
-
- void operator delete[](void* p) noexcept { return ::operator delete[](p); }
-
- template <typename... Args>
- void operator delete[](void* p, Args&&... args) noexcept {
- return ::operator delete[](p, std::forward<Args>(args)...);
- }
-
- // Non-standard access to the actual contained value. No need for this to
- // throw.
- int& Get() noexcept { return dummy_; }
- const int& Get() const noexcept { return dummy_; }
-
- private:
- static std::string GetInstanceString(int dummy) {
- return absl::StrCat("ThrowingValue<",
- exceptions_internal::GetSpecString(Spec), ">(", dummy,
- ")");
- }
-
- int dummy_;
-};
-// While not having to do with exceptions, explicitly delete comma operator, to
-// make sure we don't use it on user-supplied types.
-template <TypeSpec Spec, typename T>
-void operator,(const ThrowingValue<Spec>&, T&&) = delete;
-template <TypeSpec Spec, typename T>
-void operator,(T&&, const ThrowingValue<Spec>&) = delete;
-
-/*
- * Configuration enum for the ThrowingAllocator type that defines behavior for
- * the lifetime of the instance.
- *
- * kEverythingThrows: Calls to the member functions may throw
- * kNoThrowAllocate: Calls to the member functions will not throw
- */
-enum class AllocSpec {
- kEverythingThrows = 0,
- kNoThrowAllocate = 1,
-};
-
-/*
- * An allocator type which is instrumented to throw at a controlled time, or not
- * to throw, using AllocSpec. The supported settings are the default of every
- * function which is allowed to throw in a conforming allocator possibly
- * throwing, or nothing throws, in line with the ABSL_ALLOCATOR_THROWS
- * configuration macro.
- */
-template <typename T, AllocSpec Spec = AllocSpec::kEverythingThrows>
-class ThrowingAllocator : private exceptions_internal::TrackedObject {
- static constexpr bool IsSpecified(AllocSpec spec) {
- return static_cast<bool>(Spec & spec);
- }
-
- public:
- using pointer = T*;
- using const_pointer = const T*;
- using reference = T&;
- using const_reference = const T&;
- using void_pointer = void*;
- using const_void_pointer = const void*;
- using value_type = T;
- using size_type = size_t;
- using difference_type = ptrdiff_t;
-
- using is_nothrow =
- std::integral_constant<bool, Spec == AllocSpec::kNoThrowAllocate>;
- using propagate_on_container_copy_assignment = std::true_type;
- using propagate_on_container_move_assignment = std::true_type;
- using propagate_on_container_swap = std::true_type;
- using is_always_equal = std::false_type;
-
- ThrowingAllocator() : TrackedObject(GetInstanceString(next_id_)) {
- exceptions_internal::MaybeThrow(ABSL_PRETTY_FUNCTION);
- dummy_ = std::make_shared<const int>(next_id_++);
- }
-
- template <typename U>
- ThrowingAllocator(const ThrowingAllocator<U, Spec>& other) noexcept // NOLINT
- : TrackedObject(GetInstanceString(*other.State())),
- dummy_(other.State()) {}
-
- // According to C++11 standard [17.6.3.5], Table 28, the move/copy ctors of
- // allocator shall not exit via an exception, thus they are marked noexcept.
- ThrowingAllocator(const ThrowingAllocator& other) noexcept
- : TrackedObject(GetInstanceString(*other.State())),
- dummy_(other.State()) {}
-
- template <typename U>
- ThrowingAllocator(ThrowingAllocator<U, Spec>&& other) noexcept // NOLINT
- : TrackedObject(GetInstanceString(*other.State())),
- dummy_(std::move(other.State())) {}
-
- ThrowingAllocator(ThrowingAllocator&& other) noexcept
- : TrackedObject(GetInstanceString(*other.State())),
- dummy_(std::move(other.State())) {}
-
- ~ThrowingAllocator() noexcept = default;
-
- ThrowingAllocator& operator=(const ThrowingAllocator& other) noexcept {
- dummy_ = other.State();
- return *this;
- }
-
- template <typename U>
- ThrowingAllocator& operator=(
- const ThrowingAllocator<U, Spec>& other) noexcept {
- dummy_ = other.State();
- return *this;
- }
-
- template <typename U>
- ThrowingAllocator& operator=(ThrowingAllocator<U, Spec>&& other) noexcept {
- dummy_ = std::move(other.State());
- return *this;
- }
-
- template <typename U>
- struct rebind {
- using other = ThrowingAllocator<U, Spec>;
- };
-
- pointer allocate(size_type n) noexcept(
- IsSpecified(AllocSpec::kNoThrowAllocate)) {
- ReadStateAndMaybeThrow(ABSL_PRETTY_FUNCTION);
- return static_cast<pointer>(::operator new(n * sizeof(T)));
- }
-
- pointer allocate(size_type n, const_void_pointer) noexcept(
- IsSpecified(AllocSpec::kNoThrowAllocate)) {
- return allocate(n);
- }
-
- void deallocate(pointer ptr, size_type) noexcept {
- ReadState();
- ::operator delete(static_cast<void*>(ptr));
- }
-
- template <typename U, typename... Args>
- void construct(U* ptr, Args&&... args) noexcept(
- IsSpecified(AllocSpec::kNoThrowAllocate)) {
- ReadStateAndMaybeThrow(ABSL_PRETTY_FUNCTION);
- ::new (static_cast<void*>(ptr)) U(std::forward<Args>(args)...);
- }
-
- template <typename U>
- void destroy(U* p) noexcept {
- ReadState();
- p->~U();
- }
-
- size_type max_size() const noexcept {
- return (std::numeric_limits<difference_type>::max)() / sizeof(value_type);
- }
-
- ThrowingAllocator select_on_container_copy_construction() noexcept(
- IsSpecified(AllocSpec::kNoThrowAllocate)) {
- ReadStateAndMaybeThrow(ABSL_PRETTY_FUNCTION);
- return *this;
- }
-
- template <typename U>
- bool operator==(const ThrowingAllocator<U, Spec>& other) const noexcept {
- return dummy_ == other.dummy_;
- }
-
- template <typename U>
- bool operator!=(const ThrowingAllocator<U, Spec>& other) const noexcept {
- return dummy_ != other.dummy_;
- }
-
- template <typename, AllocSpec>
- friend class ThrowingAllocator;
-
- private:
- static std::string GetInstanceString(int dummy) {
- return absl::StrCat("ThrowingAllocator<",
- exceptions_internal::GetSpecString(Spec), ">(", dummy,
- ")");
- }
-
- const std::shared_ptr<const int>& State() const { return dummy_; }
- std::shared_ptr<const int>& State() { return dummy_; }
-
- void ReadState() {
- // we know that this will never be true, but the compiler doesn't, so this
- // should safely force a read of the value.
- if (*dummy_ < 0) std::abort();
- }
-
- void ReadStateAndMaybeThrow(absl::string_view msg) const {
- if (!IsSpecified(AllocSpec::kNoThrowAllocate)) {
- exceptions_internal::MaybeThrow(
- absl::Substitute("Allocator id $0 threw from $1", *dummy_, msg));
- }
- }
-
- static int next_id_;
- std::shared_ptr<const int> dummy_;
-};
-
-template <typename T, AllocSpec Spec>
-int ThrowingAllocator<T, Spec>::next_id_ = 0;
-
-// Tests for resource leaks by attempting to construct a T using args repeatedly
-// until successful, using the countdown method. Side effects can then be
-// tested for resource leaks.
-template <typename T, typename... Args>
-void TestThrowingCtor(Args&&... args) {
- struct Cleanup {
- ~Cleanup() { exceptions_internal::UnsetCountdown(); }
- } c;
- for (int count = 0;; ++count) {
- exceptions_internal::ConstructorTracker ct(count);
- exceptions_internal::SetCountdown(count);
- try {
- T temp(std::forward<Args>(args)...);
- static_cast<void>(temp);
- break;
- } catch (const exceptions_internal::TestException&) {
- }
- }
-}
-
-// Tests the nothrow guarantee of the provided nullary operation. If the an
-// exception is thrown, the result will be AssertionFailure(). Otherwise, it
-// will be AssertionSuccess().
-template <typename Operation>
-testing::AssertionResult TestNothrowOp(const Operation& operation) {
- struct Cleanup {
- Cleanup() { exceptions_internal::SetCountdown(); }
- ~Cleanup() { exceptions_internal::UnsetCountdown(); }
- } c;
- try {
- operation();
- return testing::AssertionSuccess();
- } catch (const exceptions_internal::TestException&) {
- return testing::AssertionFailure()
- << "TestException thrown during call to operation() when nothrow "
- "guarantee was expected.";
- } catch (...) {
- return testing::AssertionFailure()
- << "Unknown exception thrown during call to operation() when "
- "nothrow guarantee was expected.";
- }
-}
-
-namespace exceptions_internal {
-
-// Dummy struct for ExceptionSafetyTestBuilder<> partial state.
-struct UninitializedT {};
-
-template <typename T>
-class DefaultFactory {
- public:
- explicit DefaultFactory(const T& t) : t_(t) {}
- std::unique_ptr<T> operator()() const { return absl::make_unique<T>(t_); }
-
- private:
- T t_;
-};
-
-template <size_t LazyContractsCount, typename LazyFactory,
- typename LazyOperation>
-using EnableIfTestable = typename absl::enable_if_t<
- LazyContractsCount != 0 &&
- !std::is_same<LazyFactory, UninitializedT>::value &&
- !std::is_same<LazyOperation, UninitializedT>::value>;
-
-template <typename Factory = UninitializedT,
- typename Operation = UninitializedT, typename... Contracts>
-class ExceptionSafetyTestBuilder;
-
-} // namespace exceptions_internal
-
-/*
- * Constructs an empty ExceptionSafetyTestBuilder. All
- * ExceptionSafetyTestBuilder objects are immutable and all With[thing] mutation
- * methods return new instances of ExceptionSafetyTestBuilder.
- *
- * In order to test a T for exception safety, a factory for that T, a testable
- * operation, and at least one contract callback returning an assertion
- * result must be applied using the respective methods.
- */
-exceptions_internal::ExceptionSafetyTestBuilder<> MakeExceptionSafetyTester();
-
-namespace exceptions_internal {
-template <typename T>
-struct IsUniquePtr : std::false_type {};
-
-template <typename T, typename D>
-struct IsUniquePtr<std::unique_ptr<T, D>> : std::true_type {};
-
-template <typename Factory>
-struct FactoryPtrTypeHelper {
- using type = decltype(std::declval<const Factory&>()());
-
- static_assert(IsUniquePtr<type>::value, "Factories must return a unique_ptr");
-};
-
-template <typename Factory>
-using FactoryPtrType = typename FactoryPtrTypeHelper<Factory>::type;
-
-template <typename Factory>
-using FactoryElementType = typename FactoryPtrType<Factory>::element_type;
-
-template <typename T>
-class ExceptionSafetyTest {
- using Factory = std::function<std::unique_ptr<T>()>;
- using Operation = std::function<void(T*)>;
- using Contract = std::function<AssertionResult(T*)>;
-
- public:
- template <typename... Contracts>
- explicit ExceptionSafetyTest(const Factory& f, const Operation& op,
- const Contracts&... contracts)
- : factory_(f), operation_(op), contracts_{WrapContract(contracts)...} {}
-
- AssertionResult Test() const {
- for (int count = 0;; ++count) {
- exceptions_internal::ConstructorTracker ct(count);
-
- for (const auto& contract : contracts_) {
- auto t_ptr = factory_();
- try {
- SetCountdown(count);
- operation_(t_ptr.get());
- // Unset for the case that the operation throws no exceptions, which
- // would leave the countdown set and break the *next* exception safety
- // test after this one.
- UnsetCountdown();
- return AssertionSuccess();
- } catch (const exceptions_internal::TestException& e) {
- if (!contract(t_ptr.get())) {
- return AssertionFailure() << e.what() << " failed contract check";
- }
- }
- }
- }
- }
-
- private:
- template <typename ContractFn>
- Contract WrapContract(const ContractFn& contract) {
- return [contract](T* t_ptr) { return AssertionResult(contract(t_ptr)); };
- }
-
- Contract WrapContract(StrongGuaranteeTagType) {
- return [this](T* t_ptr) { return AssertionResult(*factory_() == *t_ptr); };
- }
-
- Factory factory_;
- Operation operation_;
- std::vector<Contract> contracts_;
-};
-
-/*
- * Builds a tester object that tests if performing a operation on a T follows
- * exception safety guarantees. Verification is done via contract assertion
- * callbacks applied to T instances post-throw.
- *
- * Template parameters for ExceptionSafetyTestBuilder:
- *
- * - Factory: The factory object (passed in via tester.WithFactory(...) or
- * tester.WithInitialValue(...)) must be invocable with the signature
- * `std::unique_ptr<T> operator()() const` where T is the type being tested.
- * It is used for reliably creating identical T instances to test on.
- *
- * - Operation: The operation object (passsed in via tester.WithOperation(...)
- * or tester.Test(...)) must be invocable with the signature
- * `void operator()(T*) const` where T is the type being tested. It is used
- * for performing steps on a T instance that may throw and that need to be
- * checked for exception safety. Each call to the operation will receive a
- * fresh T instance so it's free to modify and destroy the T instances as it
- * pleases.
- *
- * - Contracts...: The contract assertion callback objects (passed in via
- * tester.WithContracts(...)) must be invocable with the signature
- * `testing::AssertionResult operator()(T*) const` where T is the type being
- * tested. Contract assertion callbacks are provided T instances post-throw.
- * They must return testing::AssertionSuccess when the type contracts of the
- * provided T instance hold. If the type contracts of the T instance do not
- * hold, they must return testing::AssertionFailure. Execution order of
- * Contracts... is unspecified. They will each individually get a fresh T
- * instance so they are free to modify and destroy the T instances as they
- * please.
- */
-template <typename Factory, typename Operation, typename... Contracts>
-class ExceptionSafetyTestBuilder {
- public:
- /*
- * Returns a new ExceptionSafetyTestBuilder with an included T factory based
- * on the provided T instance. The existing factory will not be included in
- * the newly created tester instance. The created factory returns a new T
- * instance by copy-constructing the provided const T& t.
- *
- * Preconditions for tester.WithInitialValue(const T& t):
- *
- * - The const T& t object must be copy-constructible where T is the type
- * being tested. For non-copy-constructible objects, use the method
- * tester.WithFactory(...).
- */
- template <typename T>
- ExceptionSafetyTestBuilder<DefaultFactory<T>, Operation, Contracts...>
- WithInitialValue(const T& t) const {
- return WithFactory(DefaultFactory<T>(t));
- }
-
- /*
- * Returns a new ExceptionSafetyTestBuilder with the provided T factory
- * included. The existing factory will not be included in the newly-created
- * tester instance. This method is intended for use with types lacking a copy
- * constructor. Types that can be copy-constructed should instead use the
- * method tester.WithInitialValue(...).
- */
- template <typename NewFactory>
- ExceptionSafetyTestBuilder<absl::decay_t<NewFactory>, Operation, Contracts...>
- WithFactory(const NewFactory& new_factory) const {
- return {new_factory, operation_, contracts_};
- }
-
- /*
- * Returns a new ExceptionSafetyTestBuilder with the provided testable
- * operation included. The existing operation will not be included in the
- * newly created tester.
- */
- template <typename NewOperation>
- ExceptionSafetyTestBuilder<Factory, absl::decay_t<NewOperation>, Contracts...>
- WithOperation(const NewOperation& new_operation) const {
- return {factory_, new_operation, contracts_};
- }
-
- /*
- * Returns a new ExceptionSafetyTestBuilder with the provided MoreContracts...
- * combined with the Contracts... that were already included in the instance
- * on which the method was called. Contracts... cannot be removed or replaced
- * once added to an ExceptionSafetyTestBuilder instance. A fresh object must
- * be created in order to get an empty Contracts... list.
- *
- * In addition to passing in custom contract assertion callbacks, this method
- * accepts `testing::strong_guarantee` as an argument which checks T instances
- * post-throw against freshly created T instances via operator== to verify
- * that any state changes made during the execution of the operation were
- * properly rolled back.
- */
- template <typename... MoreContracts>
- ExceptionSafetyTestBuilder<Factory, Operation, Contracts...,
- absl::decay_t<MoreContracts>...>
- WithContracts(const MoreContracts&... more_contracts) const {
- return {
- factory_, operation_,
- std::tuple_cat(contracts_, std::tuple<absl::decay_t<MoreContracts>...>(
- more_contracts...))};
- }
-
- /*
- * Returns a testing::AssertionResult that is the reduced result of the
- * exception safety algorithm. The algorithm short circuits and returns
- * AssertionFailure after the first contract callback returns an
- * AssertionFailure. Otherwise, if all contract callbacks return an
- * AssertionSuccess, the reduced result is AssertionSuccess.
- *
- * The passed-in testable operation will not be saved in a new tester instance
- * nor will it modify/replace the existing tester instance. This is useful
- * when each operation being tested is unique and does not need to be reused.
- *
- * Preconditions for tester.Test(const NewOperation& new_operation):
- *
- * - May only be called after at least one contract assertion callback and a
- * factory or initial value have been provided.
- */
- template <
- typename NewOperation,
- typename = EnableIfTestable<sizeof...(Contracts), Factory, NewOperation>>
- testing::AssertionResult Test(const NewOperation& new_operation) const {
- return TestImpl(new_operation, absl::index_sequence_for<Contracts...>());
- }
-
- /*
- * Returns a testing::AssertionResult that is the reduced result of the
- * exception safety algorithm. The algorithm short circuits and returns
- * AssertionFailure after the first contract callback returns an
- * AssertionFailure. Otherwise, if all contract callbacks return an
- * AssertionSuccess, the reduced result is AssertionSuccess.
- *
- * Preconditions for tester.Test():
- *
- * - May only be called after at least one contract assertion callback, a
- * factory or initial value and a testable operation have been provided.
- */
- template <
- typename LazyOperation = Operation,
- typename = EnableIfTestable<sizeof...(Contracts), Factory, LazyOperation>>
- testing::AssertionResult Test() const {
- return Test(operation_);
- }
-
- private:
- template <typename, typename, typename...>
- friend class ExceptionSafetyTestBuilder;
-
- friend ExceptionSafetyTestBuilder<> testing::MakeExceptionSafetyTester();
-
- ExceptionSafetyTestBuilder() {}
-
- ExceptionSafetyTestBuilder(const Factory& f, const Operation& o,
- const std::tuple<Contracts...>& i)
- : factory_(f), operation_(o), contracts_(i) {}
-
- template <typename SelectedOperation, size_t... Indices>
- testing::AssertionResult TestImpl(SelectedOperation selected_operation,
- absl::index_sequence<Indices...>) const {
- return ExceptionSafetyTest<FactoryElementType<Factory>>(
- factory_, selected_operation, std::get<Indices>(contracts_)...)
- .Test();
- }
-
- Factory factory_;
- Operation operation_;
- std::tuple<Contracts...> contracts_;
-};
-
-} // namespace exceptions_internal
-
-} // namespace testing
-
-#endif // ABSL_HAVE_EXCEPTIONS
-
-#endif // ABSL_BASE_INTERNAL_EXCEPTION_SAFETY_TESTING_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/exception_testing.h b/third_party/abseil-cpp/absl/base/internal/exception_testing.h
deleted file mode 100644
index 01b5465..0000000
--- a/third_party/abseil-cpp/absl/base/internal/exception_testing.h
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright 2017 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.
-
-// Testing utilities for ABSL types which throw exceptions.
-
-#ifndef ABSL_BASE_INTERNAL_EXCEPTION_TESTING_H_
-#define ABSL_BASE_INTERNAL_EXCEPTION_TESTING_H_
-
-#include "gtest/gtest.h"
-#include "absl/base/config.h"
-
-// ABSL_BASE_INTERNAL_EXPECT_FAIL tests either for a specified thrown exception
-// if exceptions are enabled, or for death with a specified text in the error
-// message
-#ifdef ABSL_HAVE_EXCEPTIONS
-
-#define ABSL_BASE_INTERNAL_EXPECT_FAIL(expr, exception_t, text) \
- EXPECT_THROW(expr, exception_t)
-
-#elif defined(__ANDROID__)
-// Android asserts do not log anywhere that gtest can currently inspect.
-// So we expect exit, but cannot match the message.
-#define ABSL_BASE_INTERNAL_EXPECT_FAIL(expr, exception_t, text) \
- EXPECT_DEATH(expr, ".*")
-#else
-#define ABSL_BASE_INTERNAL_EXPECT_FAIL(expr, exception_t, text) \
- EXPECT_DEATH_IF_SUPPORTED(expr, text)
-
-#endif
-
-#endif // ABSL_BASE_INTERNAL_EXCEPTION_TESTING_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/fast_type_id.h b/third_party/abseil-cpp/absl/base/internal/fast_type_id.h
deleted file mode 100644
index a547b3a..0000000
--- a/third_party/abseil-cpp/absl/base/internal/fast_type_id.h
+++ /dev/null
@@ -1,50 +0,0 @@
-//
-// 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;
-};
-
-#ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL
-template <typename Type>
-constexpr char FastTypeTag<Type>::dummy_var;
-#endif
-
-// 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_
diff --git a/third_party/abseil-cpp/absl/base/internal/fast_type_id_test.cc b/third_party/abseil-cpp/absl/base/internal/fast_type_id_test.cc
deleted file mode 100644
index 16f3c14..0000000
--- a/third_party/abseil-cpp/absl/base/internal/fast_type_id_test.cc
+++ /dev/null
@@ -1,123 +0,0 @@
-// 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
diff --git a/third_party/abseil-cpp/absl/base/internal/hide_ptr.h b/third_party/abseil-cpp/absl/base/internal/hide_ptr.h
deleted file mode 100644
index 1dba809..0000000
--- a/third_party/abseil-cpp/absl/base/internal/hide_ptr.h
+++ /dev/null
@@ -1,51 +0,0 @@
-// Copyright 2018 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_HIDE_PTR_H_
-#define ABSL_BASE_INTERNAL_HIDE_PTR_H_
-
-#include <cstdint>
-
-#include "absl/base/config.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-
-// Arbitrary value with high bits set. Xor'ing with it is unlikely
-// to map one valid pointer to another valid pointer.
-constexpr uintptr_t HideMask() {
- return (uintptr_t{0xF03A5F7BU} << (sizeof(uintptr_t) - 4) * 8) | 0xF03A5F7BU;
-}
-
-// Hide a pointer from the leak checker. For internal use only.
-// Differs from absl::IgnoreLeak(ptr) in that absl::IgnoreLeak(ptr) causes ptr
-// and all objects reachable from ptr to be ignored by the leak checker.
-template <class T>
-inline uintptr_t HidePtr(T* ptr) {
- return reinterpret_cast<uintptr_t>(ptr) ^ HideMask();
-}
-
-// Return a pointer that has been hidden from the leak checker.
-// For internal use only.
-template <class T>
-inline T* UnhidePtr(uintptr_t hidden) {
- return reinterpret_cast<T*>(hidden ^ HideMask());
-}
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_BASE_INTERNAL_HIDE_PTR_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/identity.h b/third_party/abseil-cpp/absl/base/internal/identity.h
deleted file mode 100644
index a3154ed..0000000
--- a/third_party/abseil-cpp/absl/base/internal/identity.h
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright 2017 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_IDENTITY_H_
-#define ABSL_BASE_INTERNAL_IDENTITY_H_
-
-#include "absl/base/config.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace internal {
-
-template <typename T>
-struct identity {
- typedef T type;
-};
-
-template <typename T>
-using identity_t = typename identity<T>::type;
-
-} // namespace internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_BASE_INTERNAL_IDENTITY_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/inline_variable.h b/third_party/abseil-cpp/absl/base/internal/inline_variable.h
deleted file mode 100644
index df933fa..0000000
--- a/third_party/abseil-cpp/absl/base/internal/inline_variable.h
+++ /dev/null
@@ -1,107 +0,0 @@
-// Copyright 2017 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_INLINE_VARIABLE_H_
-#define ABSL_BASE_INTERNAL_INLINE_VARIABLE_H_
-
-#include <type_traits>
-
-#include "absl/base/internal/identity.h"
-
-// File:
-// This file define a macro that allows the creation of or emulation of C++17
-// inline variables based on whether or not the feature is supported.
-
-////////////////////////////////////////////////////////////////////////////////
-// Macro: ABSL_INTERNAL_INLINE_CONSTEXPR(type, name, init)
-//
-// Description:
-// Expands to the equivalent of an inline constexpr instance of the specified
-// `type` and `name`, initialized to the value `init`. If the compiler being
-// used is detected as supporting actual inline variables as a language
-// feature, then the macro expands to an actual inline variable definition.
-//
-// Requires:
-// `type` is a type that is usable in an extern variable declaration.
-//
-// Requires: `name` is a valid identifier
-//
-// Requires:
-// `init` is an expression that can be used in the following definition:
-// constexpr type name = init;
-//
-// Usage:
-//
-// // Equivalent to: `inline constexpr size_t variant_npos = -1;`
-// ABSL_INTERNAL_INLINE_CONSTEXPR(size_t, variant_npos, -1);
-//
-// Differences in implementation:
-// For a direct, language-level inline variable, decltype(name) will be the
-// type that was specified along with const qualification, whereas for
-// emulated inline variables, decltype(name) may be different (in practice
-// it will likely be a reference type).
-////////////////////////////////////////////////////////////////////////////////
-
-#ifdef __cpp_inline_variables
-
-// Clang's -Wmissing-variable-declarations option erroneously warned that
-// inline constexpr objects need to be pre-declared. This has now been fixed,
-// but we will need to support this workaround for people building with older
-// versions of clang.
-//
-// Bug: https://bugs.llvm.org/show_bug.cgi?id=35862
-//
-// Note:
-// identity_t is used here so that the const and name are in the
-// appropriate place for pointer types, reference types, function pointer
-// types, etc..
-#if defined(__clang__)
-#define ABSL_INTERNAL_EXTERN_DECL(type, name) \
- extern const ::absl::internal::identity_t<type> name;
-#else // Otherwise, just define the macro to do nothing.
-#define ABSL_INTERNAL_EXTERN_DECL(type, name)
-#endif // defined(__clang__)
-
-// See above comment at top of file for details.
-#define ABSL_INTERNAL_INLINE_CONSTEXPR(type, name, init) \
- ABSL_INTERNAL_EXTERN_DECL(type, name) \
- inline constexpr ::absl::internal::identity_t<type> name = init
-
-#else
-
-// See above comment at top of file for details.
-//
-// Note:
-// identity_t is used here so that the const and name are in the
-// appropriate place for pointer types, reference types, function pointer
-// types, etc..
-#define ABSL_INTERNAL_INLINE_CONSTEXPR(var_type, name, init) \
- template <class /*AbslInternalDummy*/ = void> \
- struct AbslInternalInlineVariableHolder##name { \
- static constexpr ::absl::internal::identity_t<var_type> kInstance = init; \
- }; \
- \
- template <class AbslInternalDummy> \
- constexpr ::absl::internal::identity_t<var_type> \
- AbslInternalInlineVariableHolder##name<AbslInternalDummy>::kInstance; \
- \
- static constexpr const ::absl::internal::identity_t<var_type>& \
- name = /* NOLINT */ \
- AbslInternalInlineVariableHolder##name<>::kInstance; \
- static_assert(sizeof(void (*)(decltype(name))) != 0, \
- "Silence unused variable warnings.")
-
-#endif // __cpp_inline_variables
-
-#endif // ABSL_BASE_INTERNAL_INLINE_VARIABLE_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/inline_variable_testing.h b/third_party/abseil-cpp/absl/base/internal/inline_variable_testing.h
deleted file mode 100644
index f3c8145..0000000
--- a/third_party/abseil-cpp/absl/base/internal/inline_variable_testing.h
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright 2017 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_INLINE_VARIABLE_TESTING_H_
-#define ABSL_BASE_INTERNAL_INLINE_VARIABLE_TESTING_H_
-
-#include "absl/base/internal/inline_variable.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace inline_variable_testing_internal {
-
-struct Foo {
- int value = 5;
-};
-
-ABSL_INTERNAL_INLINE_CONSTEXPR(Foo, inline_variable_foo, {});
-ABSL_INTERNAL_INLINE_CONSTEXPR(Foo, other_inline_variable_foo, {});
-
-ABSL_INTERNAL_INLINE_CONSTEXPR(int, inline_variable_int, 5);
-ABSL_INTERNAL_INLINE_CONSTEXPR(int, other_inline_variable_int, 5);
-
-ABSL_INTERNAL_INLINE_CONSTEXPR(void(*)(), inline_variable_fun_ptr, nullptr);
-
-const Foo& get_foo_a();
-const Foo& get_foo_b();
-
-const int& get_int_a();
-const int& get_int_b();
-
-} // namespace inline_variable_testing_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_BASE_INTERNAL_INLINE_VARIABLE_TESTING_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/invoke.h b/third_party/abseil-cpp/absl/base/internal/invoke.h
deleted file mode 100644
index 643c2a4..0000000
--- a/third_party/abseil-cpp/absl/base/internal/invoke.h
+++ /dev/null
@@ -1,241 +0,0 @@
-// Copyright 2017 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.
-//
-// absl::base_internal::invoke(f, args...) is an implementation of
-// INVOKE(f, args...) from section [func.require] of the C++ standard.
-// When compiled as C++17 and later versions, it is implemented as an alias of
-// std::invoke.
-//
-// [func.require]
-// Define INVOKE (f, t1, t2, ..., tN) as follows:
-// 1. (t1.*f)(t2, ..., tN) when f is a pointer to a member function of a class T
-// and t1 is an object of type T or a reference to an object of type T or a
-// reference to an object of a type derived from T;
-// 2. ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
-// class T and t1 is not one of the types described in the previous item;
-// 3. t1.*f when N == 1 and f is a pointer to member data of a class T and t1 is
-// an object of type T or a reference to an object of type T or a reference
-// to an object of a type derived from T;
-// 4. (*t1).*f when N == 1 and f is a pointer to member data of a class T and t1
-// is not one of the types described in the previous item;
-// 5. f(t1, t2, ..., tN) in all other cases.
-//
-// The implementation is SFINAE-friendly: substitution failure within invoke()
-// isn't an error.
-
-#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;
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#else // ABSL_INTERNAL_CPLUSPLUS_LANG >= 201703L
-
-#include <algorithm>
-#include <type_traits>
-#include <utility>
-
-#include "absl/meta/type_traits.h"
-
-// The following code is internal implementation detail. See the comment at the
-// top of this file for the API documentation.
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-
-// The five classes below each implement one of the clauses from the definition
-// of INVOKE. The inner class template Accept<F, Args...> checks whether the
-// clause is applicable; static function template Invoke(f, args...) does the
-// invocation.
-//
-// By separating the clause selection logic from invocation we make sure that
-// Invoke() does exactly what the standard says.
-
-template <typename Derived>
-struct StrippedAccept {
- template <typename... Args>
- struct Accept : Derived::template AcceptImpl<typename std::remove_cv<
- typename std::remove_reference<Args>::type>::type...> {};
-};
-
-// (t1.*f)(t2, ..., tN) when f is a pointer to a member function of a class T
-// and t1 is an object of type T or a reference to an object of type T or a
-// reference to an object of a type derived from T.
-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) {
-// Ignore bogus GCC warnings on this line.
-// See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=101436 for similar example.
-#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
- }
-};
-
-// ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
-// class T and t1 is not one of the types described in the previous item.
-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)...);
- }
-};
-
-// t1.*f when N == 1 and f is a pointer to member data of a class T and t1 is
-// an object of type T or a reference to an object of type T or a reference
-// to an object of a type derived from T.
-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);
- }
-};
-
-// (*t1).*f when N == 1 and f is a pointer to member data of a class T and t1
-// is not one of the types described in the previous item.
-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);
- }
-};
-
-// f(t1, t2, ..., tN) in all other cases.
-struct Callable {
- // Callable doesn't have Accept because it's the last clause that gets picked
- // when none of the previous clauses are applicable.
- 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)...);
- }
-};
-
-// Resolves to the first matching clause.
-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;
-};
-
-// The result type of Invoke<F, Args...>.
-template <typename F, typename... Args>
-using invoke_result_t = decltype(Invoker<F, Args...>::type::Invoke(
- std::declval<F>(), std::declval<Args>()...));
-
-// Invoke(f, args...) is an implementation of INVOKE(f, args...) from section
-// [func.require] of the C++ standard.
-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> {};
-
-// Type trait whose member `value` is true if invoking `F` with `Args` is valid,
-// and either the return type is convertible to `R`, or `R` is void.
-// C++11-compatible version of `std::is_invocable_r`.
-template <typename R, typename F, typename... Args>
-using is_invocable_r = IsInvocableRImpl<void, R, F, Args...>;
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_INTERNAL_CPLUSPLUS_LANG >= 201703L
-
-#endif // ABSL_BASE_INTERNAL_INVOKE_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/low_level_alloc.cc b/third_party/abseil-cpp/absl/base/internal/low_level_alloc.cc
deleted file mode 100644
index 662167b..0000000
--- a/third_party/abseil-cpp/absl/base/internal/low_level_alloc.cc
+++ /dev/null
@@ -1,620 +0,0 @@
-// Copyright 2017 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.
-
-// A low-level allocator that can be used by other low-level
-// modules without introducing dependency cycles.
-// This allocator is slow and wasteful of memory;
-// it should not be used when performance is key.
-
-#include "absl/base/internal/low_level_alloc.h"
-
-#include <type_traits>
-
-#include "absl/base/call_once.h"
-#include "absl/base/config.h"
-#include "absl/base/internal/direct_mmap.h"
-#include "absl/base/internal/scheduling_mode.h"
-#include "absl/base/macros.h"
-#include "absl/base/thread_annotations.h"
-
-// LowLevelAlloc requires that the platform support low-level
-// allocation of virtual memory. Platforms lacking this cannot use
-// LowLevelAlloc.
-#ifndef ABSL_LOW_LEVEL_ALLOC_MISSING
-
-#ifndef _WIN32
-#include <pthread.h>
-#include <signal.h>
-#include <sys/mman.h>
-#include <unistd.h>
-#else
-#include <windows.h>
-#endif
-
-#include <string.h>
-#include <algorithm>
-#include <atomic>
-#include <cerrno>
-#include <cstddef>
-#include <new> // for placement-new
-
-#include "absl/base/dynamic_annotations.h"
-#include "absl/base/internal/raw_logging.h"
-#include "absl/base/internal/spinlock.h"
-
-// MAP_ANONYMOUS
-#if defined(__APPLE__)
-// For mmap, Linux defines both MAP_ANONYMOUS and MAP_ANON and says MAP_ANON is
-// deprecated. In Darwin, MAP_ANON is all there is.
-#if !defined MAP_ANONYMOUS
-#define MAP_ANONYMOUS MAP_ANON
-#endif // !MAP_ANONYMOUS
-#endif // __APPLE__
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-
-// A first-fit allocator with amortized logarithmic free() time.
-
-// ---------------------------------------------------------------------------
-static const int kMaxLevel = 30;
-
-namespace {
-// This struct describes one allocated block, or one free block.
-struct AllocList {
- struct Header {
- // Size of entire region, including this field. Must be
- // first. Valid in both allocated and unallocated blocks.
- uintptr_t size;
-
- // kMagicAllocated or kMagicUnallocated xor this.
- uintptr_t magic;
-
- // Pointer to parent arena.
- LowLevelAlloc::Arena *arena;
-
- // Aligns regions to 0 mod 2*sizeof(void*).
- void *dummy_for_alignment;
- } header;
-
- // Next two fields: in unallocated blocks: freelist skiplist data
- // in allocated blocks: overlaps with client data
-
- // Levels in skiplist used.
- int levels;
-
- // Actually has levels elements. The AllocList node may not have room
- // for all kMaxLevel entries. See max_fit in LLA_SkiplistLevels().
- AllocList *next[kMaxLevel];
-};
-} // namespace
-
-// ---------------------------------------------------------------------------
-// A trivial skiplist implementation. This is used to keep the freelist
-// in address order while taking only logarithmic time per insert and delete.
-
-// An integer approximation of log2(size/base)
-// Requires size >= base.
-static int IntLog2(size_t size, size_t base) {
- int result = 0;
- for (size_t i = size; i > base; i >>= 1) { // i == floor(size/2**result)
- result++;
- }
- // floor(size / 2**result) <= base < floor(size / 2**(result-1))
- // => log2(size/(base+1)) <= result < 1+log2(size/base)
- // => result ~= log2(size/base)
- return result;
-}
-
-// Return a random integer n: p(n)=1/(2**n) if 1 <= n; p(n)=0 if n < 1.
-static int Random(uint32_t *state) {
- uint32_t r = *state;
- int result = 1;
- while ((((r = r*1103515245 + 12345) >> 30) & 1) == 0) {
- result++;
- }
- *state = r;
- return result;
-}
-
-// Return a number of skiplist levels for a node of size bytes, where
-// base is the minimum node size. Compute level=log2(size / base)+n
-// where n is 1 if random is false and otherwise a random number generated with
-// the standard distribution for a skiplist: See Random() above.
-// Bigger nodes tend to have more skiplist levels due to the log2(size / base)
-// term, so first-fit searches touch fewer nodes. "level" is clipped so
-// level<kMaxLevel and next[level-1] will fit in the node.
-// 0 < LLA_SkiplistLevels(x,y,false) <= LLA_SkiplistLevels(x,y,true) < kMaxLevel
-static int LLA_SkiplistLevels(size_t size, size_t base, uint32_t *random) {
- // max_fit is the maximum number of levels that will fit in a node for the
- // given size. We can't return more than max_fit, no matter what the
- // random number generator says.
- size_t max_fit = (size - offsetof(AllocList, next)) / sizeof(AllocList *);
- int level = IntLog2(size, base) + (random != nullptr ? Random(random) : 1);
- if (static_cast<size_t>(level) > max_fit) level = static_cast<int>(max_fit);
- if (level > kMaxLevel-1) level = kMaxLevel - 1;
- ABSL_RAW_CHECK(level >= 1, "block not big enough for even one level");
- return level;
-}
-
-// Return "atleast", the first element of AllocList *head s.t. *atleast >= *e.
-// For 0 <= i < head->levels, set prev[i] to "no_greater", where no_greater
-// points to the last element at level i in the AllocList less than *e, or is
-// head if no such element exists.
-static AllocList *LLA_SkiplistSearch(AllocList *head,
- AllocList *e, AllocList **prev) {
- AllocList *p = head;
- for (int level = head->levels - 1; level >= 0; level--) {
- for (AllocList *n; (n = p->next[level]) != nullptr && n < e; p = n) {
- }
- prev[level] = p;
- }
- return (head->levels == 0) ? nullptr : prev[0]->next[0];
-}
-
-// Insert element *e into AllocList *head. Set prev[] as LLA_SkiplistSearch.
-// Requires that e->levels be previously set by the caller (using
-// LLA_SkiplistLevels())
-static void LLA_SkiplistInsert(AllocList *head, AllocList *e,
- AllocList **prev) {
- LLA_SkiplistSearch(head, e, prev);
- for (; head->levels < e->levels; head->levels++) { // extend prev pointers
- prev[head->levels] = head; // to all *e's levels
- }
- for (int i = 0; i != e->levels; i++) { // add element to list
- e->next[i] = prev[i]->next[i];
- prev[i]->next[i] = e;
- }
-}
-
-// Remove element *e from AllocList *head. Set prev[] as LLA_SkiplistSearch().
-// Requires that e->levels be previous set by the caller (using
-// LLA_SkiplistLevels())
-static void LLA_SkiplistDelete(AllocList *head, AllocList *e,
- AllocList **prev) {
- AllocList *found = LLA_SkiplistSearch(head, e, prev);
- ABSL_RAW_CHECK(e == found, "element not in freelist");
- for (int i = 0; i != e->levels && prev[i]->next[i] == e; i++) {
- prev[i]->next[i] = e->next[i];
- }
- while (head->levels > 0 && head->next[head->levels - 1] == nullptr) {
- head->levels--; // reduce head->levels if level unused
- }
-}
-
-// ---------------------------------------------------------------------------
-// Arena implementation
-
-// Metadata for an LowLevelAlloc arena instance.
-struct LowLevelAlloc::Arena {
- // Constructs an arena with the given LowLevelAlloc flags.
- explicit Arena(uint32_t flags_value);
-
- base_internal::SpinLock mu;
- // Head of free list, sorted by address
- AllocList freelist ABSL_GUARDED_BY(mu);
- // Count of allocated blocks
- int32_t allocation_count ABSL_GUARDED_BY(mu);
- // flags passed to NewArena
- const uint32_t flags;
- // Result of sysconf(_SC_PAGESIZE)
- const size_t pagesize;
- // Lowest power of two >= max(16, sizeof(AllocList))
- const size_t round_up;
- // Smallest allocation block size
- const size_t min_size;
- // PRNG state
- uint32_t random ABSL_GUARDED_BY(mu);
-};
-
-namespace {
-// Static storage space for the lazily-constructed, default global arena
-// instances. We require this space because the whole point of LowLevelAlloc
-// is to avoid relying on malloc/new.
-alignas(LowLevelAlloc::Arena) unsigned char default_arena_storage[sizeof(
- LowLevelAlloc::Arena)];
-alignas(LowLevelAlloc::Arena) unsigned char unhooked_arena_storage[sizeof(
- LowLevelAlloc::Arena)];
-#ifndef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING
-alignas(
- LowLevelAlloc::Arena) unsigned char unhooked_async_sig_safe_arena_storage
- [sizeof(LowLevelAlloc::Arena)];
-#endif
-
-// We must use LowLevelCallOnce here to construct the global arenas, rather than
-// using function-level statics, to avoid recursively invoking the scheduler.
-absl::once_flag create_globals_once;
-
-void CreateGlobalArenas() {
- new (&default_arena_storage)
- LowLevelAlloc::Arena(LowLevelAlloc::kCallMallocHook);
- new (&unhooked_arena_storage) LowLevelAlloc::Arena(0);
-#ifndef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING
- new (&unhooked_async_sig_safe_arena_storage)
- LowLevelAlloc::Arena(LowLevelAlloc::kAsyncSignalSafe);
-#endif
-}
-
-// Returns a global arena that does not call into hooks. Used by NewArena()
-// when kCallMallocHook is not set.
-LowLevelAlloc::Arena* UnhookedArena() {
- base_internal::LowLevelCallOnce(&create_globals_once, CreateGlobalArenas);
- return reinterpret_cast<LowLevelAlloc::Arena*>(&unhooked_arena_storage);
-}
-
-#ifndef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING
-// Returns a global arena that is async-signal safe. Used by NewArena() when
-// kAsyncSignalSafe is set.
-LowLevelAlloc::Arena *UnhookedAsyncSigSafeArena() {
- base_internal::LowLevelCallOnce(&create_globals_once, CreateGlobalArenas);
- return reinterpret_cast<LowLevelAlloc::Arena *>(
- &unhooked_async_sig_safe_arena_storage);
-}
-#endif
-
-} // namespace
-
-// Returns the default arena, as used by LowLevelAlloc::Alloc() and friends.
-LowLevelAlloc::Arena *LowLevelAlloc::DefaultArena() {
- base_internal::LowLevelCallOnce(&create_globals_once, CreateGlobalArenas);
- return reinterpret_cast<LowLevelAlloc::Arena*>(&default_arena_storage);
-}
-
-// magic numbers to identify allocated and unallocated blocks
-static const uintptr_t kMagicAllocated = 0x4c833e95U;
-static const uintptr_t kMagicUnallocated = ~kMagicAllocated;
-
-namespace {
-class ABSL_SCOPED_LOCKABLE ArenaLock {
- public:
- explicit ArenaLock(LowLevelAlloc::Arena *arena)
- ABSL_EXCLUSIVE_LOCK_FUNCTION(arena->mu)
- : arena_(arena) {
-#ifndef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING
- if ((arena->flags & LowLevelAlloc::kAsyncSignalSafe) != 0) {
- sigset_t all;
- sigfillset(&all);
- mask_valid_ = pthread_sigmask(SIG_BLOCK, &all, &mask_) == 0;
- }
-#endif
- arena_->mu.Lock();
- }
- ~ArenaLock() { ABSL_RAW_CHECK(left_, "haven't left Arena region"); }
- void Leave() ABSL_UNLOCK_FUNCTION() {
- arena_->mu.Unlock();
-#ifndef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING
- if (mask_valid_) {
- const int err = pthread_sigmask(SIG_SETMASK, &mask_, nullptr);
- if (err != 0) {
- ABSL_RAW_LOG(FATAL, "pthread_sigmask failed: %d", err);
- }
- }
-#endif
- left_ = true;
- }
-
- private:
- bool left_ = false; // whether left region
-#ifndef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING
- bool mask_valid_ = false;
- sigset_t mask_; // old mask of blocked signals
-#endif
- LowLevelAlloc::Arena *arena_;
- ArenaLock(const ArenaLock &) = delete;
- ArenaLock &operator=(const ArenaLock &) = delete;
-};
-} // namespace
-
-// create an appropriate magic number for an object at "ptr"
-// "magic" should be kMagicAllocated or kMagicUnallocated
-inline static uintptr_t Magic(uintptr_t magic, AllocList::Header *ptr) {
- return magic ^ reinterpret_cast<uintptr_t>(ptr);
-}
-
-namespace {
-size_t GetPageSize() {
-#ifdef _WIN32
- SYSTEM_INFO system_info;
- GetSystemInfo(&system_info);
- return std::max(system_info.dwPageSize, system_info.dwAllocationGranularity);
-#elif defined(__wasm__) || defined(__asmjs__)
- return getpagesize();
-#else
- return static_cast<size_t>(sysconf(_SC_PAGESIZE));
-#endif
-}
-
-size_t RoundedUpBlockSize() {
- // Round up block sizes to a power of two close to the header size.
- size_t round_up = 16;
- while (round_up < sizeof(AllocList::Header)) {
- round_up += round_up;
- }
- return round_up;
-}
-
-} // namespace
-
-LowLevelAlloc::Arena::Arena(uint32_t flags_value)
- : mu(base_internal::SCHEDULE_KERNEL_ONLY),
- allocation_count(0),
- flags(flags_value),
- pagesize(GetPageSize()),
- round_up(RoundedUpBlockSize()),
- min_size(2 * round_up),
- random(0) {
- freelist.header.size = 0;
- freelist.header.magic =
- Magic(kMagicUnallocated, &freelist.header);
- freelist.header.arena = this;
- freelist.levels = 0;
- memset(freelist.next, 0, sizeof(freelist.next));
-}
-
-// L < meta_data_arena->mu
-LowLevelAlloc::Arena *LowLevelAlloc::NewArena(uint32_t flags) {
- Arena *meta_data_arena = DefaultArena();
-#ifndef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING
- if ((flags & LowLevelAlloc::kAsyncSignalSafe) != 0) {
- meta_data_arena = UnhookedAsyncSigSafeArena();
- } else // NOLINT(readability/braces)
-#endif
- if ((flags & LowLevelAlloc::kCallMallocHook) == 0) {
- meta_data_arena = UnhookedArena();
- }
- Arena *result =
- new (AllocWithArena(sizeof (*result), meta_data_arena)) Arena(flags);
- return result;
-}
-
-// L < arena->mu, L < arena->arena->mu
-bool LowLevelAlloc::DeleteArena(Arena *arena) {
- ABSL_RAW_CHECK(
- arena != nullptr && arena != DefaultArena() && arena != UnhookedArena(),
- "may not delete default arena");
- ArenaLock section(arena);
- if (arena->allocation_count != 0) {
- section.Leave();
- return false;
- }
- while (arena->freelist.next[0] != nullptr) {
- AllocList *region = arena->freelist.next[0];
- size_t size = region->header.size;
- arena->freelist.next[0] = region->next[0];
- ABSL_RAW_CHECK(
- region->header.magic == Magic(kMagicUnallocated, ®ion->header),
- "bad magic number in DeleteArena()");
- ABSL_RAW_CHECK(region->header.arena == arena,
- "bad arena pointer in DeleteArena()");
- ABSL_RAW_CHECK(size % arena->pagesize == 0,
- "empty arena has non-page-aligned block size");
- ABSL_RAW_CHECK(reinterpret_cast<uintptr_t>(region) % arena->pagesize == 0,
- "empty arena has non-page-aligned block");
- int munmap_result;
-#ifdef _WIN32
- munmap_result = VirtualFree(region, 0, MEM_RELEASE);
- ABSL_RAW_CHECK(munmap_result != 0,
- "LowLevelAlloc::DeleteArena: VitualFree failed");
-#else
-#ifndef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING
- if ((arena->flags & LowLevelAlloc::kAsyncSignalSafe) == 0) {
- munmap_result = munmap(region, size);
- } else {
- munmap_result = base_internal::DirectMunmap(region, size);
- }
-#else
- munmap_result = munmap(region, size);
-#endif // ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING
- if (munmap_result != 0) {
- ABSL_RAW_LOG(FATAL, "LowLevelAlloc::DeleteArena: munmap failed: %d",
- errno);
- }
-#endif // _WIN32
- }
- section.Leave();
- arena->~Arena();
- Free(arena);
- return true;
-}
-
-// ---------------------------------------------------------------------------
-
-// Addition, checking for overflow. The intent is to die if an external client
-// manages to push through a request that would cause arithmetic to fail.
-static inline uintptr_t CheckedAdd(uintptr_t a, uintptr_t b) {
- uintptr_t sum = a + b;
- ABSL_RAW_CHECK(sum >= a, "LowLevelAlloc arithmetic overflow");
- return sum;
-}
-
-// Return value rounded up to next multiple of align.
-// align must be a power of two.
-static inline uintptr_t RoundUp(uintptr_t addr, uintptr_t align) {
- return CheckedAdd(addr, align - 1) & ~(align - 1);
-}
-
-// Equivalent to "return prev->next[i]" but with sanity checking
-// that the freelist is in the correct order, that it
-// consists of regions marked "unallocated", and that no two regions
-// are adjacent in memory (they should have been coalesced).
-// L >= arena->mu
-static AllocList *Next(int i, AllocList *prev, LowLevelAlloc::Arena *arena) {
- ABSL_RAW_CHECK(i < prev->levels, "too few levels in Next()");
- AllocList *next = prev->next[i];
- if (next != nullptr) {
- ABSL_RAW_CHECK(
- next->header.magic == Magic(kMagicUnallocated, &next->header),
- "bad magic number in Next()");
- ABSL_RAW_CHECK(next->header.arena == arena, "bad arena pointer in Next()");
- if (prev != &arena->freelist) {
- ABSL_RAW_CHECK(prev < next, "unordered freelist");
- ABSL_RAW_CHECK(reinterpret_cast<char *>(prev) + prev->header.size <
- reinterpret_cast<char *>(next),
- "malformed freelist");
- }
- }
- return next;
-}
-
-// Coalesce list item "a" with its successor if they are adjacent.
-static void Coalesce(AllocList *a) {
- AllocList *n = a->next[0];
- if (n != nullptr && reinterpret_cast<char *>(a) + a->header.size ==
- reinterpret_cast<char *>(n)) {
- LowLevelAlloc::Arena *arena = a->header.arena;
- a->header.size += n->header.size;
- n->header.magic = 0;
- n->header.arena = nullptr;
- AllocList *prev[kMaxLevel];
- LLA_SkiplistDelete(&arena->freelist, n, prev);
- LLA_SkiplistDelete(&arena->freelist, a, prev);
- a->levels = LLA_SkiplistLevels(a->header.size, arena->min_size,
- &arena->random);
- LLA_SkiplistInsert(&arena->freelist, a, prev);
- }
-}
-
-// Adds block at location "v" to the free list
-// L >= arena->mu
-static void AddToFreelist(void *v, LowLevelAlloc::Arena *arena) {
- AllocList *f = reinterpret_cast<AllocList *>(
- reinterpret_cast<char *>(v) - sizeof (f->header));
- ABSL_RAW_CHECK(f->header.magic == Magic(kMagicAllocated, &f->header),
- "bad magic number in AddToFreelist()");
- ABSL_RAW_CHECK(f->header.arena == arena,
- "bad arena pointer in AddToFreelist()");
- f->levels = LLA_SkiplistLevels(f->header.size, arena->min_size,
- &arena->random);
- AllocList *prev[kMaxLevel];
- LLA_SkiplistInsert(&arena->freelist, f, prev);
- f->header.magic = Magic(kMagicUnallocated, &f->header);
- Coalesce(f); // maybe coalesce with successor
- Coalesce(prev[0]); // maybe coalesce with predecessor
-}
-
-// Frees storage allocated by LowLevelAlloc::Alloc().
-// L < arena->mu
-void LowLevelAlloc::Free(void *v) {
- if (v != nullptr) {
- AllocList *f = reinterpret_cast<AllocList *>(
- reinterpret_cast<char *>(v) - sizeof (f->header));
- LowLevelAlloc::Arena *arena = f->header.arena;
- ArenaLock section(arena);
- AddToFreelist(v, arena);
- ABSL_RAW_CHECK(arena->allocation_count > 0, "nothing in arena to free");
- arena->allocation_count--;
- section.Leave();
- }
-}
-
-// allocates and returns a block of size bytes, to be freed with Free()
-// L < arena->mu
-static void *DoAllocWithArena(size_t request, LowLevelAlloc::Arena *arena) {
- void *result = nullptr;
- if (request != 0) {
- AllocList *s; // will point to region that satisfies request
- ArenaLock section(arena);
- // round up with header
- size_t req_rnd = RoundUp(CheckedAdd(request, sizeof (s->header)),
- arena->round_up);
- for (;;) { // loop until we find a suitable region
- // find the minimum levels that a block of this size must have
- int i = LLA_SkiplistLevels(req_rnd, arena->min_size, nullptr) - 1;
- if (i < arena->freelist.levels) { // potential blocks exist
- AllocList *before = &arena->freelist; // predecessor of s
- while ((s = Next(i, before, arena)) != nullptr &&
- s->header.size < req_rnd) {
- before = s;
- }
- if (s != nullptr) { // we found a region
- break;
- }
- }
- // we unlock before mmap() both because mmap() may call a callback hook,
- // and because it may be slow.
- arena->mu.Unlock();
- // mmap generous 64K chunks to decrease
- // the chances/impact of fragmentation:
- size_t new_pages_size = RoundUp(req_rnd, arena->pagesize * 16);
- void *new_pages;
-#ifdef _WIN32
- new_pages = VirtualAlloc(0, new_pages_size,
- MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
- ABSL_RAW_CHECK(new_pages != nullptr, "VirtualAlloc failed");
-#else
-#ifndef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING
- if ((arena->flags & LowLevelAlloc::kAsyncSignalSafe) != 0) {
- new_pages = base_internal::DirectMmap(nullptr, new_pages_size,
- PROT_WRITE|PROT_READ, MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
- } else {
- new_pages = mmap(nullptr, new_pages_size, PROT_WRITE | PROT_READ,
- MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
- }
-#else
- new_pages = mmap(nullptr, new_pages_size, PROT_WRITE | PROT_READ,
- MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
-#endif // ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING
- if (new_pages == MAP_FAILED) {
- ABSL_RAW_LOG(FATAL, "mmap error: %d", errno);
- }
-
-#endif // _WIN32
- arena->mu.Lock();
- s = reinterpret_cast<AllocList *>(new_pages);
- s->header.size = new_pages_size;
- // Pretend the block is allocated; call AddToFreelist() to free it.
- s->header.magic = Magic(kMagicAllocated, &s->header);
- s->header.arena = arena;
- AddToFreelist(&s->levels, arena); // insert new region into free list
- }
- AllocList *prev[kMaxLevel];
- LLA_SkiplistDelete(&arena->freelist, s, prev); // remove from free list
- // s points to the first free region that's big enough
- if (CheckedAdd(req_rnd, arena->min_size) <= s->header.size) {
- // big enough to split
- AllocList *n = reinterpret_cast<AllocList *>
- (req_rnd + reinterpret_cast<char *>(s));
- n->header.size = s->header.size - req_rnd;
- n->header.magic = Magic(kMagicAllocated, &n->header);
- n->header.arena = arena;
- s->header.size = req_rnd;
- AddToFreelist(&n->levels, arena);
- }
- s->header.magic = Magic(kMagicAllocated, &s->header);
- ABSL_RAW_CHECK(s->header.arena == arena, "");
- arena->allocation_count++;
- section.Leave();
- result = &s->levels;
- }
- ABSL_ANNOTATE_MEMORY_IS_UNINITIALIZED(result, request);
- return result;
-}
-
-void *LowLevelAlloc::Alloc(size_t request) {
- void *result = DoAllocWithArena(request, DefaultArena());
- return result;
-}
-
-void *LowLevelAlloc::AllocWithArena(size_t request, Arena *arena) {
- ABSL_RAW_CHECK(arena != nullptr, "must pass a valid arena");
- void *result = DoAllocWithArena(request, arena);
- return result;
-}
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_LOW_LEVEL_ALLOC_MISSING
diff --git a/third_party/abseil-cpp/absl/base/internal/low_level_alloc.h b/third_party/abseil-cpp/absl/base/internal/low_level_alloc.h
deleted file mode 100644
index eabb14a..0000000
--- a/third_party/abseil-cpp/absl/base/internal/low_level_alloc.h
+++ /dev/null
@@ -1,126 +0,0 @@
-// Copyright 2017 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_LOW_LEVEL_ALLOC_H_
-#define ABSL_BASE_INTERNAL_LOW_LEVEL_ALLOC_H_
-
-// A simple thread-safe memory allocator that does not depend on
-// mutexes or thread-specific data. It is intended to be used
-// sparingly, and only when malloc() would introduce an unwanted
-// dependency, such as inside the heap-checker, or the Mutex
-// implementation.
-
-// IWYU pragma: private, include "base/low_level_alloc.h"
-
-#include <sys/types.h>
-
-#include <cstdint>
-
-#include "absl/base/attributes.h"
-#include "absl/base/config.h"
-
-// LowLevelAlloc requires that the platform support low-level
-// allocation of virtual memory. Platforms lacking this cannot use
-// LowLevelAlloc.
-#ifdef ABSL_LOW_LEVEL_ALLOC_MISSING
-#error ABSL_LOW_LEVEL_ALLOC_MISSING cannot be directly set
-#elif !defined(ABSL_HAVE_MMAP) && !defined(_WIN32)
-#define ABSL_LOW_LEVEL_ALLOC_MISSING 1
-#endif
-
-// Using LowLevelAlloc with kAsyncSignalSafe isn't supported on Windows or
-// asm.js / WebAssembly.
-// See https://kripken.github.io/emscripten-site/docs/porting/pthreads.html
-// for more information.
-#ifdef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING
-#error ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING cannot be directly set
-#elif defined(_WIN32) || defined(__asmjs__) || defined(__wasm__)
-#define ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING 1
-#endif
-
-#include <cstddef>
-
-#include "absl/base/port.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-
-class LowLevelAlloc {
- public:
- struct Arena; // an arena from which memory may be allocated
-
- // Returns a pointer to a block of at least "request" bytes
- // that have been newly allocated from the specific arena.
- // for Alloc() call the DefaultArena() is used.
- // Returns 0 if passed request==0.
- // Does not return 0 under other circumstances; it crashes if memory
- // is not available.
- static void *Alloc(size_t request) ABSL_ATTRIBUTE_SECTION(malloc_hook);
- static void *AllocWithArena(size_t request, Arena *arena)
- ABSL_ATTRIBUTE_SECTION(malloc_hook);
-
- // Deallocates a region of memory that was previously allocated with
- // Alloc(). Does nothing if passed 0. "s" must be either 0,
- // or must have been returned from a call to Alloc() and not yet passed to
- // Free() since that call to Alloc(). The space is returned to the arena
- // from which it was allocated.
- static void Free(void *s) ABSL_ATTRIBUTE_SECTION(malloc_hook);
-
- // ABSL_ATTRIBUTE_SECTION(malloc_hook) for Alloc* and Free
- // are to put all callers of MallocHook::Invoke* in this module
- // into special section,
- // so that MallocHook::GetCallerStackTrace can function accurately.
-
- // Create a new arena.
- // The root metadata for the new arena is allocated in the
- // meta_data_arena; the DefaultArena() can be passed for meta_data_arena.
- // These values may be ored into flags:
- enum {
- // Report calls to Alloc() and Free() via the MallocHook interface.
- // Set in the DefaultArena.
- kCallMallocHook = 0x0001,
-
-#ifndef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING
- // Make calls to Alloc(), Free() be async-signal-safe. Not set in
- // DefaultArena(). Not supported on all platforms.
- kAsyncSignalSafe = 0x0002,
-#endif
- };
- // Construct a new arena. The allocation of the underlying metadata honors
- // the provided flags. For example, the call NewArena(kAsyncSignalSafe)
- // is itself async-signal-safe, as well as generatating an arena that provides
- // async-signal-safe Alloc/Free.
- static Arena *NewArena(uint32_t flags);
-
- // Destroys an arena allocated by NewArena and returns true,
- // provided no allocated blocks remain in the arena.
- // If allocated blocks remain in the arena, does nothing and
- // returns false.
- // It is illegal to attempt to destroy the DefaultArena().
- static bool DeleteArena(Arena *arena);
-
- // The default arena that always exists.
- static Arena *DefaultArena();
-
- private:
- LowLevelAlloc(); // no instances
-};
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_BASE_INTERNAL_LOW_LEVEL_ALLOC_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/low_level_alloc_test.cc b/third_party/abseil-cpp/absl/base/internal/low_level_alloc_test.cc
deleted file mode 100644
index 8fdec09..0000000
--- a/third_party/abseil-cpp/absl/base/internal/low_level_alloc_test.cc
+++ /dev/null
@@ -1,180 +0,0 @@
-// Copyright 2017 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/low_level_alloc.h"
-
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <thread> // NOLINT(build/c++11)
-#include <unordered_map>
-#include <utility>
-
-#ifdef __EMSCRIPTEN__
-#include <emscripten.h>
-#endif
-
-#include "absl/container/node_hash_map.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-namespace {
-
-// This test doesn't use gtest since it needs to test that everything
-// works before main().
-#define TEST_ASSERT(x) \
- if (!(x)) { \
- printf("TEST_ASSERT(%s) FAILED ON LINE %d\n", #x, __LINE__); \
- abort(); \
- }
-
-// a block of memory obtained from the allocator
-struct BlockDesc {
- char *ptr; // pointer to memory
- int len; // number of bytes
- int fill; // filled with data starting with this
-};
-
-// Check that the pattern placed in the block d
-// by RandomizeBlockDesc is still there.
-static void CheckBlockDesc(const BlockDesc &d) {
- for (int i = 0; i != d.len; i++) {
- TEST_ASSERT((d.ptr[i] & 0xff) == ((d.fill + i) & 0xff));
- }
-}
-
-// Fill the block "*d" with a pattern
-// starting with a random byte.
-static void RandomizeBlockDesc(BlockDesc *d) {
- d->fill = rand() & 0xff;
- for (int i = 0; i != d->len; i++) {
- d->ptr[i] = (d->fill + i) & 0xff;
- }
-}
-
-// Use to indicate to the malloc hooks that
-// this calls is from LowLevelAlloc.
-static bool using_low_level_alloc = false;
-
-// n times, toss a coin, and based on the outcome
-// either allocate a new block or deallocate an old block.
-// New blocks are placed in a std::unordered_map with a random key
-// and initialized with RandomizeBlockDesc().
-// If keys conflict, the older block is freed.
-// Old blocks are always checked with CheckBlockDesc()
-// before being freed. At the end of the run,
-// all remaining allocated blocks are freed.
-// If use_new_arena is true, use a fresh arena, and then delete it.
-// If call_malloc_hook is true and user_arena is true,
-// allocations and deallocations are reported via the MallocHook
-// interface.
-static void Test(bool use_new_arena, bool call_malloc_hook, int n) {
- typedef absl::node_hash_map<int, BlockDesc> AllocMap;
- AllocMap allocated;
- AllocMap::iterator it;
- BlockDesc block_desc;
- int rnd;
- LowLevelAlloc::Arena *arena = nullptr;
- if (use_new_arena) {
- int32_t flags = call_malloc_hook ? LowLevelAlloc::kCallMallocHook : 0;
- arena = LowLevelAlloc::NewArena(flags);
- }
- for (int i = 0; i != n; i++) {
- if (i != 0 && i % 10000 == 0) {
- printf(".");
- fflush(stdout);
- }
-
- switch (rand() & 1) { // toss a coin
- case 0: // coin came up heads: add a block
- using_low_level_alloc = true;
- block_desc.len = rand() & 0x3fff;
- block_desc.ptr = reinterpret_cast<char *>(
- arena == nullptr
- ? LowLevelAlloc::Alloc(block_desc.len)
- : LowLevelAlloc::AllocWithArena(block_desc.len, arena));
- using_low_level_alloc = false;
- RandomizeBlockDesc(&block_desc);
- rnd = rand();
- it = allocated.find(rnd);
- if (it != allocated.end()) {
- CheckBlockDesc(it->second);
- using_low_level_alloc = true;
- LowLevelAlloc::Free(it->second.ptr);
- using_low_level_alloc = false;
- it->second = block_desc;
- } else {
- allocated[rnd] = block_desc;
- }
- break;
- case 1: // coin came up tails: remove a block
- it = allocated.begin();
- if (it != allocated.end()) {
- CheckBlockDesc(it->second);
- using_low_level_alloc = true;
- LowLevelAlloc::Free(it->second.ptr);
- using_low_level_alloc = false;
- allocated.erase(it);
- }
- break;
- }
- }
- // remove all remaining blocks
- while ((it = allocated.begin()) != allocated.end()) {
- CheckBlockDesc(it->second);
- using_low_level_alloc = true;
- LowLevelAlloc::Free(it->second.ptr);
- using_low_level_alloc = false;
- allocated.erase(it);
- }
- if (use_new_arena) {
- TEST_ASSERT(LowLevelAlloc::DeleteArena(arena));
- }
-}
-
-// LowLevelAlloc is designed to be safe to call before main().
-static struct BeforeMain {
- BeforeMain() {
- Test(false, false, 50000);
- Test(true, false, 50000);
- Test(true, true, 50000);
- }
-} before_main;
-
-} // namespace
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-int main(int argc, char *argv[]) {
- // The actual test runs in the global constructor of `before_main`.
- printf("PASS\n");
-#ifdef __EMSCRIPTEN__
- // clang-format off
-// This is JS here. Don't try to format it.
- MAIN_THREAD_EM_ASM({
- if (ENVIRONMENT_IS_WEB) {
- if (typeof TEST_FINISH === 'function') {
- TEST_FINISH($0);
- } else {
- console.error('Attempted to exit with status ' + $0);
- console.error('But TEST_FINSIHED is not a function.');
- }
- }
- }, 0);
-// clang-format on
-#endif
- return 0;
-}
diff --git a/third_party/abseil-cpp/absl/base/internal/low_level_scheduling.h b/third_party/abseil-cpp/absl/base/internal/low_level_scheduling.h
deleted file mode 100644
index 9baccc0..0000000
--- a/third_party/abseil-cpp/absl/base/internal/low_level_scheduling.h
+++ /dev/null
@@ -1,134 +0,0 @@
-// Copyright 2017 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.
-//
-// Core interfaces and definitions used by by low-level interfaces such as
-// SpinLock.
-
-#ifndef ABSL_BASE_INTERNAL_LOW_LEVEL_SCHEDULING_H_
-#define ABSL_BASE_INTERNAL_LOW_LEVEL_SCHEDULING_H_
-
-#include "absl/base/internal/raw_logging.h"
-#include "absl/base/internal/scheduling_mode.h"
-#include "absl/base/macros.h"
-
-// The following two declarations exist so SchedulingGuard may friend them with
-// the appropriate language linkage. These callbacks allow libc internals, such
-// as function level statics, to schedule cooperatively when locking.
-extern "C" bool __google_disable_rescheduling(void);
-extern "C" void __google_enable_rescheduling(bool disable_result);
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-class CondVar;
-class Mutex;
-
-namespace synchronization_internal {
-int MutexDelay(int32_t c, int mode);
-} // namespace synchronization_internal
-
-namespace base_internal {
-
-class SchedulingHelper; // To allow use of SchedulingGuard.
-class SpinLock; // To allow use of SchedulingGuard.
-
-// SchedulingGuard
-// Provides guard semantics that may be used to disable cooperative rescheduling
-// of the calling thread within specific program blocks. This is used to
-// protect resources (e.g. low-level SpinLocks or Domain code) that cooperative
-// scheduling depends on.
-//
-// Domain implementations capable of rescheduling in reaction to involuntary
-// kernel thread actions (e.g blocking due to a pagefault or syscall) must
-// guarantee that an annotated thread is not allowed to (cooperatively)
-// reschedule until the annotated region is complete.
-//
-// It is an error to attempt to use a cooperatively scheduled resource (e.g.
-// Mutex) within a rescheduling-disabled region.
-//
-// All methods are async-signal safe.
-class SchedulingGuard {
- public:
- // Returns true iff the calling thread may be cooperatively rescheduled.
- static bool ReschedulingIsAllowed();
- SchedulingGuard(const SchedulingGuard&) = delete;
- SchedulingGuard& operator=(const SchedulingGuard&) = delete;
-
- private:
- // Disable cooperative rescheduling of the calling thread. It may still
- // initiate scheduling operations (e.g. wake-ups), however, it may not itself
- // reschedule. Nestable. The returned result is opaque, clients should not
- // attempt to interpret it.
- // REQUIRES: Result must be passed to a pairing EnableScheduling().
- static bool DisableRescheduling();
-
- // Marks the end of a rescheduling disabled region, previously started by
- // DisableRescheduling().
- // REQUIRES: Pairs with innermost call (and result) of DisableRescheduling().
- static void EnableRescheduling(bool disable_result);
-
- // A scoped helper for {Disable, Enable}Rescheduling().
- // REQUIRES: destructor must run in same thread as constructor.
- struct ScopedDisable {
- ScopedDisable() { disabled = SchedulingGuard::DisableRescheduling(); }
- ~ScopedDisable() { SchedulingGuard::EnableRescheduling(disabled); }
-
- bool disabled;
- };
-
- // A scoped helper to enable rescheduling temporarily.
- // REQUIRES: destructor must run in same thread as constructor.
- class ScopedEnable {
- public:
- ScopedEnable();
- ~ScopedEnable();
-
- private:
- int scheduling_disabled_depth_;
- };
-
- // Access to SchedulingGuard is explicitly permitted.
- friend class absl::CondVar;
- friend class absl::Mutex;
- friend class SchedulingHelper;
- friend class SpinLock;
- friend int absl::synchronization_internal::MutexDelay(int32_t c, int mode);
-};
-
-//------------------------------------------------------------------------------
-// End of public interfaces.
-//------------------------------------------------------------------------------
-
-inline bool SchedulingGuard::ReschedulingIsAllowed() {
- return false;
-}
-
-inline bool SchedulingGuard::DisableRescheduling() {
- return false;
-}
-
-inline void SchedulingGuard::EnableRescheduling(bool /* disable_result */) {
- return;
-}
-
-inline SchedulingGuard::ScopedEnable::ScopedEnable()
- : scheduling_disabled_depth_(0) {}
-inline SchedulingGuard::ScopedEnable::~ScopedEnable() {
- ABSL_RAW_CHECK(scheduling_disabled_depth_ == 0, "disable unused warning");
-}
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_BASE_INTERNAL_LOW_LEVEL_SCHEDULING_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/per_thread_tls.h b/third_party/abseil-cpp/absl/base/internal/per_thread_tls.h
deleted file mode 100644
index cf5e97a..0000000
--- a/third_party/abseil-cpp/absl/base/internal/per_thread_tls.h
+++ /dev/null
@@ -1,52 +0,0 @@
-// Copyright 2017 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_PER_THREAD_TLS_H_
-#define ABSL_BASE_INTERNAL_PER_THREAD_TLS_H_
-
-// This header defines two macros:
-//
-// If the platform supports thread-local storage:
-//
-// * ABSL_PER_THREAD_TLS_KEYWORD is the C keyword needed to declare a
-// thread-local variable
-// * ABSL_PER_THREAD_TLS is 1
-//
-// Otherwise:
-//
-// * ABSL_PER_THREAD_TLS_KEYWORD is empty
-// * ABSL_PER_THREAD_TLS is 0
-//
-// Microsoft C supports thread-local storage.
-// GCC supports it if the appropriate version of glibc is available,
-// which the programmer can indicate by defining ABSL_HAVE_TLS
-
-#include "absl/base/port.h" // For ABSL_HAVE_TLS
-
-#if defined(ABSL_PER_THREAD_TLS)
-#error ABSL_PER_THREAD_TLS cannot be directly set
-#elif defined(ABSL_PER_THREAD_TLS_KEYWORD)
-#error ABSL_PER_THREAD_TLS_KEYWORD cannot be directly set
-#elif defined(ABSL_HAVE_TLS)
-#define ABSL_PER_THREAD_TLS_KEYWORD __thread
-#define ABSL_PER_THREAD_TLS 1
-#elif defined(_MSC_VER)
-#define ABSL_PER_THREAD_TLS_KEYWORD __declspec(thread)
-#define ABSL_PER_THREAD_TLS 1
-#else
-#define ABSL_PER_THREAD_TLS_KEYWORD
-#define ABSL_PER_THREAD_TLS 0
-#endif
-
-#endif // ABSL_BASE_INTERNAL_PER_THREAD_TLS_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/prefetch.h b/third_party/abseil-cpp/absl/base/internal/prefetch.h
deleted file mode 100644
index 0641928..0000000
--- a/third_party/abseil-cpp/absl/base/internal/prefetch.h
+++ /dev/null
@@ -1,138 +0,0 @@
-// Copyright 2022 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_PREFETCH_H_
-#define ABSL_BASE_INTERNAL_PREFETCH_H_
-
-#include "absl/base/config.h"
-
-#ifdef __SSE__
-#include <xmmintrin.h>
-#endif
-
-#if defined(_MSC_VER) && defined(ABSL_INTERNAL_HAVE_SSE)
-#include <intrin.h>
-#pragma intrinsic(_mm_prefetch)
-#endif
-
-// Compatibility wrappers around __builtin_prefetch, to prefetch data
-// for read if supported by the toolchain.
-
-// Move data into the cache before it is read, or "prefetch" it.
-//
-// The value of `addr` is the address of the memory to prefetch. If
-// the target and compiler support it, data prefetch instructions are
-// generated. If the prefetch is done some time before the memory is
-// read, it may be in the cache by the time the read occurs.
-//
-// The function names specify the temporal locality heuristic applied,
-// using the names of Intel prefetch instructions:
-//
-// T0 - high degree of temporal locality; data should be left in as
-// many levels of the cache possible
-// T1 - moderate degree of temporal locality
-// T2 - low degree of temporal locality
-// Nta - no temporal locality, data need not be left in the cache
-// after the read
-//
-// Incorrect or gratuitous use of these functions can degrade
-// performance, so use them only when representative benchmarks show
-// an improvement.
-//
-// Example usage:
-//
-// absl::base_internal::PrefetchT0(addr);
-//
-// Currently, the different prefetch calls behave on some Intel
-// architectures as follows:
-//
-// SNB..SKL SKX
-// PrefetchT0() L1/L2/L3 L1/L2
-// PrefetchT1() L2/L3 L2
-// PrefetchT2() L2/L3 L2
-// PrefetchNta() L1/--/L3 L1*
-//
-// * On SKX PrefetchNta() will bring the line into L1 but will evict
-// from L3 cache. This might result in surprising behavior.
-//
-// SNB = Sandy Bridge, SKL = Skylake, SKX = Skylake Xeon.
-//
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-
-void PrefetchT0(const void* addr);
-void PrefetchT1(const void* addr);
-void PrefetchT2(const void* addr);
-void PrefetchNta(const void* addr);
-
-// Implementation details follow.
-
-#if ABSL_HAVE_BUILTIN(__builtin_prefetch) || defined(__GNUC__)
-
-#define ABSL_INTERNAL_HAVE_PREFETCH 1
-
-// See __builtin_prefetch:
-// https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html.
-//
-// These functions speculatively load for read only. This is
-// safe for all currently supported platforms. However, prefetch for
-// store may have problems depending on the target platform.
-//
-inline void PrefetchT0(const void* addr) {
- // Note: this uses prefetcht0 on Intel.
- __builtin_prefetch(addr, 0, 3);
-}
-inline void PrefetchT1(const void* addr) {
- // Note: this uses prefetcht1 on Intel.
- __builtin_prefetch(addr, 0, 2);
-}
-inline void PrefetchT2(const void* addr) {
- // Note: this uses prefetcht2 on Intel.
- __builtin_prefetch(addr, 0, 1);
-}
-inline void PrefetchNta(const void* addr) {
- // Note: this uses prefetchtnta on Intel.
- __builtin_prefetch(addr, 0, 0);
-}
-
-#elif defined(ABSL_INTERNAL_HAVE_SSE)
-
-#define ABSL_INTERNAL_HAVE_PREFETCH 1
-
-inline void PrefetchT0(const void* addr) {
- _mm_prefetch(reinterpret_cast<const char*>(addr), _MM_HINT_T0);
-}
-inline void PrefetchT1(const void* addr) {
- _mm_prefetch(reinterpret_cast<const char*>(addr), _MM_HINT_T1);
-}
-inline void PrefetchT2(const void* addr) {
- _mm_prefetch(reinterpret_cast<const char*>(addr), _MM_HINT_T2);
-}
-inline void PrefetchNta(const void* addr) {
- _mm_prefetch(reinterpret_cast<const char*>(addr), _MM_HINT_NTA);
-}
-
-#else
-inline void PrefetchT0(const void*) {}
-inline void PrefetchT1(const void*) {}
-inline void PrefetchT2(const void*) {}
-inline void PrefetchNta(const void*) {}
-#endif
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_BASE_INTERNAL_PREFETCH_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/prefetch_test.cc b/third_party/abseil-cpp/absl/base/internal/prefetch_test.cc
deleted file mode 100644
index 7c1dae4..0000000
--- a/third_party/abseil-cpp/absl/base/internal/prefetch_test.cc
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright 2022 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/prefetch.h"
-
-#include "gtest/gtest.h"
-
-namespace {
-
-int number = 42;
-
-TEST(Prefetch, TemporalLocalityNone) {
- absl::base_internal::PrefetchNta(&number);
- EXPECT_EQ(number, 42);
-}
-
-TEST(Prefetch, TemporalLocalityLow) {
- absl::base_internal::PrefetchT2(&number);
- EXPECT_EQ(number, 42);
-}
-
-TEST(Prefetch, TemporalLocalityMedium) {
- absl::base_internal::PrefetchT1(&number);
- EXPECT_EQ(number, 42);
-}
-
-TEST(Prefetch, TemporalLocalityHigh) {
- absl::base_internal::PrefetchT0(&number);
- EXPECT_EQ(number, 42);
-}
-
-} // namespace
diff --git a/third_party/abseil-cpp/absl/base/internal/pretty_function.h b/third_party/abseil-cpp/absl/base/internal/pretty_function.h
deleted file mode 100644
index 35d5167..0000000
--- a/third_party/abseil-cpp/absl/base/internal/pretty_function.h
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright 2017 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_PRETTY_FUNCTION_H_
-#define ABSL_BASE_INTERNAL_PRETTY_FUNCTION_H_
-
-// ABSL_PRETTY_FUNCTION
-//
-// In C++11, __func__ gives the undecorated name of the current function. That
-// is, "main", not "int main()". Various compilers give extra macros to get the
-// decorated function name, including return type and arguments, to
-// differentiate between overload sets. ABSL_PRETTY_FUNCTION is a portable
-// version of these macros which forwards to the correct macro on each compiler.
-#if defined(_MSC_VER)
-#define ABSL_PRETTY_FUNCTION __FUNCSIG__
-#elif defined(__GNUC__)
-#define ABSL_PRETTY_FUNCTION __PRETTY_FUNCTION__
-#else
-#error "Unsupported compiler"
-#endif
-
-#endif // ABSL_BASE_INTERNAL_PRETTY_FUNCTION_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/raw_logging.cc b/third_party/abseil-cpp/absl/base/internal/raw_logging.cc
deleted file mode 100644
index 6273e84..0000000
--- a/third_party/abseil-cpp/absl/base/internal/raw_logging.cc
+++ /dev/null
@@ -1,253 +0,0 @@
-// Copyright 2017 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/raw_logging.h"
-
-#include <cstdarg>
-#include <cstddef>
-#include <cstdio>
-#include <cstdlib>
-#include <cstring>
-#include <string>
-
-#include "absl/base/attributes.h"
-#include "absl/base/config.h"
-#include "absl/base/internal/atomic_hook.h"
-#include "absl/base/internal/errno_saver.h"
-#include "absl/base/log_severity.h"
-
-// We know how to perform low-level writes to stderr in POSIX and Windows. For
-// these platforms, we define the token ABSL_LOW_LEVEL_WRITE_SUPPORTED.
-// Much of raw_logging.cc becomes a no-op when we can't output messages,
-// although a FATAL ABSL_RAW_LOG message will still abort the process.
-
-// ABSL_HAVE_POSIX_WRITE is defined when the platform provides posix write()
-// (as from unistd.h)
-//
-// This preprocessor token is also defined in raw_io.cc. If you need to copy
-// this, consider moving both to config.h instead.
-#if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || \
- defined(__Fuchsia__) || defined(__native_client__) || \
- defined(__OpenBSD__) || defined(__EMSCRIPTEN__) || defined(__ASYLO__)
-
-#include <unistd.h>
-
-#define ABSL_HAVE_POSIX_WRITE 1
-#define ABSL_LOW_LEVEL_WRITE_SUPPORTED 1
-#else
-#undef ABSL_HAVE_POSIX_WRITE
-#endif
-
-// ABSL_HAVE_SYSCALL_WRITE is defined when the platform provides the syscall
-// syscall(SYS_write, /*int*/ fd, /*char* */ buf, /*size_t*/ len);
-// for low level operations that want to avoid libc.
-#if (defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__)) && \
- !defined(__ANDROID__)
-#include <sys/syscall.h>
-#define ABSL_HAVE_SYSCALL_WRITE 1
-#define ABSL_LOW_LEVEL_WRITE_SUPPORTED 1
-#else
-#undef ABSL_HAVE_SYSCALL_WRITE
-#endif
-
-#ifdef _WIN32
-#include <io.h>
-
-#define ABSL_HAVE_RAW_IO 1
-#define ABSL_LOW_LEVEL_WRITE_SUPPORTED 1
-#else
-#undef ABSL_HAVE_RAW_IO
-#endif
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace raw_log_internal {
-namespace {
-
-// TODO(gfalcon): We want raw-logging to work on as many platforms as possible.
-// Explicitly `#error` out when not `ABSL_LOW_LEVEL_WRITE_SUPPORTED`, except for
-// a selected set of platforms for which we expect not to be able to raw log.
-
-#ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
-constexpr char kTruncated[] = " ... (message truncated)\n";
-
-// sprintf the format to the buffer, adjusting *buf and *size to reflect the
-// consumed bytes, and return whether the message fit without truncation. If
-// truncation occurred, if possible leave room in the buffer for the message
-// kTruncated[].
-bool VADoRawLog(char** buf, int* size, const char* format, va_list ap)
- ABSL_PRINTF_ATTRIBUTE(3, 0);
-bool VADoRawLog(char** buf, int* size, const char* format, va_list ap) {
- if (*size < 0)
- return false;
- int n = vsnprintf(*buf, static_cast<size_t>(*size), format, ap);
- bool result = true;
- if (n < 0 || n > *size) {
- result = false;
- if (static_cast<size_t>(*size) > sizeof(kTruncated)) {
- n = *size - static_cast<int>(sizeof(kTruncated));
- } else {
- n = 0; // no room for truncation message
- }
- }
- *size -= n;
- *buf += n;
- return result;
-}
-#endif // ABSL_LOW_LEVEL_WRITE_SUPPORTED
-
-constexpr int kLogBufSize = 3000;
-
-// CAVEAT: vsnprintf called from *DoRawLog below has some (exotic) code paths
-// that invoke malloc() and getenv() that might acquire some locks.
-
-// Helper for RawLog below.
-// *DoRawLog writes to *buf of *size and move them past the written portion.
-// It returns true iff there was no overflow or error.
-bool DoRawLog(char** buf, int* size, const char* format, ...)
- ABSL_PRINTF_ATTRIBUTE(3, 4);
-bool DoRawLog(char** buf, int* size, const char* format, ...) {
- if (*size < 0)
- return false;
- va_list ap;
- va_start(ap, format);
- int n = vsnprintf(*buf, static_cast<size_t>(*size), format, ap);
- va_end(ap);
- if (n < 0 || n > *size) return false;
- *size -= n;
- *buf += n;
- return true;
-}
-
-bool DefaultLogFilterAndPrefix(absl::LogSeverity, const char* file, int line,
- char** buf, int* buf_size) {
- DoRawLog(buf, buf_size, "[%s : %d] RAW: ", file, line);
- return true;
-}
-
-ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES
-absl::base_internal::AtomicHook<LogFilterAndPrefixHook>
- log_filter_and_prefix_hook(DefaultLogFilterAndPrefix);
-ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES
-absl::base_internal::AtomicHook<AbortHook> abort_hook;
-
-void RawLogVA(absl::LogSeverity severity, const char* file, int line,
- const char* format, va_list ap) ABSL_PRINTF_ATTRIBUTE(4, 0);
-void RawLogVA(absl::LogSeverity severity, const char* file, int line,
- const char* format, va_list ap) {
- char buffer[kLogBufSize];
- char* buf = buffer;
- int size = sizeof(buffer);
-#ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
- bool enabled = true;
-#else
- bool enabled = false;
-#endif
-
-#ifdef ABSL_MIN_LOG_LEVEL
- if (severity < static_cast<absl::LogSeverity>(ABSL_MIN_LOG_LEVEL) &&
- severity < absl::LogSeverity::kFatal) {
- enabled = false;
- }
-#endif
-
- enabled = log_filter_and_prefix_hook(severity, file, line, &buf, &size);
- const char* const prefix_end = buf;
-
-#ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
- if (enabled) {
- bool no_chop = VADoRawLog(&buf, &size, format, ap);
- if (no_chop) {
- DoRawLog(&buf, &size, "\n");
- } else {
- DoRawLog(&buf, &size, "%s", kTruncated);
- }
- AsyncSignalSafeWriteToStderr(buffer, strlen(buffer));
- }
-#else
- static_cast<void>(format);
- static_cast<void>(ap);
- static_cast<void>(enabled);
-#endif
-
- // Abort the process after logging a FATAL message, even if the output itself
- // was suppressed.
- if (severity == absl::LogSeverity::kFatal) {
- abort_hook(file, line, buffer, prefix_end, buffer + kLogBufSize);
- abort();
- }
-}
-
-// Non-formatting version of RawLog().
-//
-// TODO(gfalcon): When string_view no longer depends on base, change this
-// interface to take its message as a string_view instead.
-void DefaultInternalLog(absl::LogSeverity severity, const char* file, int line,
- const std::string& message) {
- RawLog(severity, file, line, "%.*s", static_cast<int>(message.size()),
- message.data());
-}
-
-} // namespace
-
-void AsyncSignalSafeWriteToStderr(const char* s, size_t len) {
- absl::base_internal::ErrnoSaver errno_saver;
-#if defined(ABSL_HAVE_SYSCALL_WRITE)
- // We prefer calling write via `syscall` to minimize the risk of libc doing
- // something "helpful".
- syscall(SYS_write, STDERR_FILENO, s, len);
-#elif defined(ABSL_HAVE_POSIX_WRITE)
- write(STDERR_FILENO, s, len);
-#elif defined(ABSL_HAVE_RAW_IO)
- _write(/* stderr */ 2, s, static_cast<unsigned>(len));
-#else
- // stderr logging unsupported on this platform
- (void) s;
- (void) len;
-#endif
-}
-
-void RawLog(absl::LogSeverity severity, const char* file, int line,
- const char* format, ...) {
- va_list ap;
- va_start(ap, format);
- RawLogVA(severity, file, line, format, ap);
- va_end(ap);
-}
-
-bool RawLoggingFullySupported() {
-#ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED
- return true;
-#else // !ABSL_LOW_LEVEL_WRITE_SUPPORTED
- return false;
-#endif // !ABSL_LOW_LEVEL_WRITE_SUPPORTED
-}
-
-ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES ABSL_DLL
- absl::base_internal::AtomicHook<InternalLogFunction>
- internal_log_function(DefaultInternalLog);
-
-void RegisterLogFilterAndPrefixHook(LogFilterAndPrefixHook func) {
- log_filter_and_prefix_hook.Store(func);
-}
-
-void RegisterAbortHook(AbortHook func) { abort_hook.Store(func); }
-
-void RegisterInternalLogFunction(InternalLogFunction func) {
- internal_log_function.Store(func);
-}
-
-} // namespace raw_log_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/base/internal/raw_logging.h b/third_party/abseil-cpp/absl/base/internal/raw_logging.h
deleted file mode 100644
index db2ef38..0000000
--- a/third_party/abseil-cpp/absl/base/internal/raw_logging.h
+++ /dev/null
@@ -1,195 +0,0 @@
-// Copyright 2017 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.
-//
-// Thread-safe logging routines that do not allocate any memory or
-// acquire any locks, and can therefore be used by low-level memory
-// allocation, synchronization, and signal-handling code.
-
-#ifndef ABSL_BASE_INTERNAL_RAW_LOGGING_H_
-#define ABSL_BASE_INTERNAL_RAW_LOGGING_H_
-
-#include <string>
-
-#include "absl/base/attributes.h"
-#include "absl/base/config.h"
-#include "absl/base/internal/atomic_hook.h"
-#include "absl/base/log_severity.h"
-#include "absl/base/macros.h"
-#include "absl/base/optimization.h"
-#include "absl/base/port.h"
-
-// This is similar to LOG(severity) << format..., but
-// * it is to be used ONLY by low-level modules that can't use normal LOG()
-// * it is designed to be a low-level logger that does not allocate any
-// memory and does not need any locks, hence:
-// * it logs straight and ONLY to STDERR w/o buffering
-// * it uses an explicit printf-format and arguments list
-// * it will silently chop off really long message strings
-// Usage example:
-// ABSL_RAW_LOG(ERROR, "Failed foo with %i: %s", status, error);
-// This will print an almost standard log line like this to stderr only:
-// E0821 211317 file.cc:123] RAW: Failed foo with 22: bad_file
-
-#define ABSL_RAW_LOG(severity, ...) \
- do { \
- constexpr const char* absl_raw_log_internal_basename = \
- ::absl::raw_log_internal::Basename(__FILE__, sizeof(__FILE__) - 1); \
- ::absl::raw_log_internal::RawLog(ABSL_RAW_LOG_INTERNAL_##severity, \
- absl_raw_log_internal_basename, __LINE__, \
- __VA_ARGS__); \
- } while (0)
-
-// Similar to CHECK(condition) << message, but for low-level modules:
-// we use only ABSL_RAW_LOG that does not allocate memory.
-// We do not want to provide args list here to encourage this usage:
-// if (!cond) ABSL_RAW_LOG(FATAL, "foo ...", hard_to_compute_args);
-// so that the args are not computed when not needed.
-#define ABSL_RAW_CHECK(condition, message) \
- do { \
- if (ABSL_PREDICT_FALSE(!(condition))) { \
- ABSL_RAW_LOG(FATAL, "Check %s failed: %s", #condition, message); \
- } \
- } while (0)
-
-// ABSL_INTERNAL_LOG and ABSL_INTERNAL_CHECK work like the RAW variants above,
-// except that if the richer log library is linked into the binary, we dispatch
-// to that instead. This is potentially useful for internal logging and
-// assertions, where we are using RAW_LOG neither for its async-signal-safety
-// nor for its non-allocating nature, but rather because raw logging has very
-// few other dependencies.
-//
-// The API is a subset of the above: each macro only takes two arguments. Use
-// StrCat if you need to build a richer message.
-#define ABSL_INTERNAL_LOG(severity, message) \
- do { \
- constexpr const char* absl_raw_log_internal_filename = __FILE__; \
- ::absl::raw_log_internal::internal_log_function( \
- ABSL_RAW_LOG_INTERNAL_##severity, absl_raw_log_internal_filename, \
- __LINE__, message); \
- if (ABSL_RAW_LOG_INTERNAL_##severity == ::absl::LogSeverity::kFatal) \
- ABSL_INTERNAL_UNREACHABLE; \
- } while (0)
-
-#define ABSL_INTERNAL_CHECK(condition, message) \
- do { \
- if (ABSL_PREDICT_FALSE(!(condition))) { \
- std::string death_message = "Check " #condition " failed: "; \
- death_message += std::string(message); \
- ABSL_INTERNAL_LOG(FATAL, death_message); \
- } \
- } while (0)
-
-#define ABSL_RAW_LOG_INTERNAL_INFO ::absl::LogSeverity::kInfo
-#define ABSL_RAW_LOG_INTERNAL_WARNING ::absl::LogSeverity::kWarning
-#define ABSL_RAW_LOG_INTERNAL_ERROR ::absl::LogSeverity::kError
-#define ABSL_RAW_LOG_INTERNAL_FATAL ::absl::LogSeverity::kFatal
-#define ABSL_RAW_LOG_INTERNAL_LEVEL(severity) \
- ::absl::NormalizeLogSeverity(severity)
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace raw_log_internal {
-
-// Helper function to implement ABSL_RAW_LOG
-// Logs format... at "severity" level, reporting it
-// as called from file:line.
-// This does not allocate memory or acquire locks.
-void RawLog(absl::LogSeverity severity, const char* file, int line,
- const char* format, ...) ABSL_PRINTF_ATTRIBUTE(4, 5);
-
-// Writes the provided buffer directly to stderr, in a signal-safe, low-level
-// manner.
-void AsyncSignalSafeWriteToStderr(const char* s, size_t len);
-
-// compile-time function to get the "base" filename, that is, the part of
-// a filename after the last "/" or "\" path separator. The search starts at
-// the end of the string; the second parameter is the length of the string.
-constexpr const char* Basename(const char* fname, int offset) {
- return offset == 0 || fname[offset - 1] == '/' || fname[offset - 1] == '\\'
- ? fname + offset
- : Basename(fname, offset - 1);
-}
-
-// For testing only.
-// Returns true if raw logging is fully supported. When it is not
-// fully supported, no messages will be emitted, but a log at FATAL
-// severity will cause an abort.
-//
-// TODO(gfalcon): Come up with a better name for this method.
-bool RawLoggingFullySupported();
-
-// Function type for a raw_log customization hook for suppressing messages
-// by severity, and for writing custom prefixes on non-suppressed messages.
-//
-// The installed hook is called for every raw log invocation. The message will
-// be logged to stderr only if the hook returns true. FATAL errors will cause
-// the process to abort, even if writing to stderr is suppressed. The hook is
-// also provided with an output buffer, where it can write a custom log message
-// prefix.
-//
-// The raw_log system does not allocate memory or grab locks. User-provided
-// hooks must avoid these operations, and must not throw exceptions.
-//
-// 'severity' is the severity level of the message being written.
-// 'file' and 'line' are the file and line number where the ABSL_RAW_LOG macro
-// was located.
-// 'buf' and 'buf_size' are pointers to the buffer and buffer size. If the
-// hook writes a prefix, it must increment *buf and decrement *buf_size
-// accordingly.
-using LogFilterAndPrefixHook = bool (*)(absl::LogSeverity severity,
- const char* file, int line, char** buf,
- int* buf_size);
-
-// Function type for a raw_log customization hook called to abort a process
-// when a FATAL message is logged. If the provided AbortHook() returns, the
-// logging system will call abort().
-//
-// 'file' and 'line' are the file and line number where the ABSL_RAW_LOG macro
-// was located.
-// The NUL-terminated logged message lives in the buffer between 'buf_start'
-// and 'buf_end'. 'prefix_end' points to the first non-prefix character of the
-// buffer (as written by the LogFilterAndPrefixHook.)
-//
-// The lifetime of the filename and message buffers will not end while the
-// process remains alive.
-using AbortHook = void (*)(const char* file, int line, const char* buf_start,
- const char* prefix_end, const char* buf_end);
-
-// Internal logging function for ABSL_INTERNAL_LOG to dispatch to.
-//
-// TODO(gfalcon): When string_view no longer depends on base, change this
-// interface to take its message as a string_view instead.
-using InternalLogFunction = void (*)(absl::LogSeverity severity,
- const char* file, int line,
- const std::string& message);
-
-ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES ABSL_DLL extern base_internal::AtomicHook<
- InternalLogFunction>
- internal_log_function;
-
-// Registers hooks of the above types. Only a single hook of each type may be
-// registered. It is an error to call these functions multiple times with
-// different input arguments.
-//
-// These functions are safe to call at any point during initialization; they do
-// not block or malloc, and are async-signal safe.
-void RegisterLogFilterAndPrefixHook(LogFilterAndPrefixHook func);
-void RegisterAbortHook(AbortHook func);
-void RegisterInternalLogFunction(InternalLogFunction func);
-
-} // namespace raw_log_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_BASE_INTERNAL_RAW_LOGGING_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/scheduling_mode.h b/third_party/abseil-cpp/absl/base/internal/scheduling_mode.h
deleted file mode 100644
index 8be5ab6..0000000
--- a/third_party/abseil-cpp/absl/base/internal/scheduling_mode.h
+++ /dev/null
@@ -1,58 +0,0 @@
-// Copyright 2017 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.
-//
-// Core interfaces and definitions used by by low-level interfaces such as
-// SpinLock.
-
-#ifndef ABSL_BASE_INTERNAL_SCHEDULING_MODE_H_
-#define ABSL_BASE_INTERNAL_SCHEDULING_MODE_H_
-
-#include "absl/base/config.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-
-// Used to describe how a thread may be scheduled. Typically associated with
-// the declaration of a resource supporting synchronized access.
-//
-// SCHEDULE_COOPERATIVE_AND_KERNEL:
-// Specifies that when waiting, a cooperative thread (e.g. a Fiber) may
-// reschedule (using base::scheduling semantics); allowing other cooperative
-// threads to proceed.
-//
-// SCHEDULE_KERNEL_ONLY: (Also described as "non-cooperative")
-// Specifies that no cooperative scheduling semantics may be used, even if the
-// current thread is itself cooperatively scheduled. This means that
-// cooperative threads will NOT allow other cooperative threads to execute in
-// their place while waiting for a resource of this type. Host operating system
-// semantics (e.g. a futex) may still be used.
-//
-// When optional, clients should strongly prefer SCHEDULE_COOPERATIVE_AND_KERNEL
-// by default. SCHEDULE_KERNEL_ONLY should only be used for resources on which
-// base::scheduling (e.g. the implementation of a Scheduler) may depend.
-//
-// NOTE: Cooperative resources may not be nested below non-cooperative ones.
-// This means that it is invalid to to acquire a SCHEDULE_COOPERATIVE_AND_KERNEL
-// resource if a SCHEDULE_KERNEL_ONLY resource is already held.
-enum SchedulingMode {
- SCHEDULE_KERNEL_ONLY = 0, // Allow scheduling only the host OS.
- SCHEDULE_COOPERATIVE_AND_KERNEL, // Also allow cooperative scheduling.
-};
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_BASE_INTERNAL_SCHEDULING_MODE_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/scoped_set_env.cc b/third_party/abseil-cpp/absl/base/internal/scoped_set_env.cc
deleted file mode 100644
index 8a934cb..0000000
--- a/third_party/abseil-cpp/absl/base/internal/scoped_set_env.cc
+++ /dev/null
@@ -1,81 +0,0 @@
-// Copyright 2019 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/scoped_set_env.h"
-
-#ifdef _WIN32
-#include <windows.h>
-#endif
-
-#include <cstdlib>
-
-#include "absl/base/internal/raw_logging.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-
-namespace {
-
-#ifdef _WIN32
-const int kMaxEnvVarValueSize = 1024;
-#endif
-
-void SetEnvVar(const char* name, const char* value) {
-#ifdef _WIN32
- SetEnvironmentVariableA(name, value);
-#else
- if (value == nullptr) {
- ::unsetenv(name);
- } else {
- ::setenv(name, value, 1);
- }
-#endif
-}
-
-} // namespace
-
-ScopedSetEnv::ScopedSetEnv(const char* var_name, const char* new_value)
- : var_name_(var_name), was_unset_(false) {
-#ifdef _WIN32
- char buf[kMaxEnvVarValueSize];
- auto get_res = GetEnvironmentVariableA(var_name_.c_str(), buf, sizeof(buf));
- ABSL_INTERNAL_CHECK(get_res < sizeof(buf), "value exceeds buffer size");
-
- if (get_res == 0) {
- was_unset_ = (GetLastError() == ERROR_ENVVAR_NOT_FOUND);
- } else {
- old_value_.assign(buf, get_res);
- }
-
- SetEnvironmentVariableA(var_name_.c_str(), new_value);
-#else
- const char* val = ::getenv(var_name_.c_str());
- if (val == nullptr) {
- was_unset_ = true;
- } else {
- old_value_ = val;
- }
-#endif
-
- SetEnvVar(var_name_.c_str(), new_value);
-}
-
-ScopedSetEnv::~ScopedSetEnv() {
- SetEnvVar(var_name_.c_str(), was_unset_ ? nullptr : old_value_.c_str());
-}
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/base/internal/scoped_set_env.h b/third_party/abseil-cpp/absl/base/internal/scoped_set_env.h
deleted file mode 100644
index 19ec7b5..0000000
--- a/third_party/abseil-cpp/absl/base/internal/scoped_set_env.h
+++ /dev/null
@@ -1,45 +0,0 @@
-//
-// Copyright 2019 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_SCOPED_SET_ENV_H_
-#define ABSL_BASE_INTERNAL_SCOPED_SET_ENV_H_
-
-#include <string>
-
-#include "absl/base/config.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-
-class ScopedSetEnv {
- public:
- ScopedSetEnv(const char* var_name, const char* new_value);
- ~ScopedSetEnv();
-
- private:
- std::string var_name_;
- std::string old_value_;
-
- // True if the environment variable was initially not set.
- bool was_unset_;
-};
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_BASE_INTERNAL_SCOPED_SET_ENV_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/scoped_set_env_test.cc b/third_party/abseil-cpp/absl/base/internal/scoped_set_env_test.cc
deleted file mode 100644
index 5cbad24..0000000
--- a/third_party/abseil-cpp/absl/base/internal/scoped_set_env_test.cc
+++ /dev/null
@@ -1,99 +0,0 @@
-// Copyright 2019 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.
-
-#ifdef _WIN32
-#include <windows.h>
-#endif
-
-#include "gtest/gtest.h"
-#include "absl/base/internal/scoped_set_env.h"
-
-namespace {
-
-using absl::base_internal::ScopedSetEnv;
-
-std::string GetEnvVar(const char* name) {
-#ifdef _WIN32
- char buf[1024];
- auto get_res = GetEnvironmentVariableA(name, buf, sizeof(buf));
- if (get_res >= sizeof(buf)) {
- return "TOO_BIG";
- }
-
- if (get_res == 0) {
- return "UNSET";
- }
-
- return std::string(buf, get_res);
-#else
- const char* val = ::getenv(name);
- if (val == nullptr) {
- return "UNSET";
- }
-
- return val;
-#endif
-}
-
-TEST(ScopedSetEnvTest, SetNonExistingVarToString) {
- EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "UNSET");
-
- {
- ScopedSetEnv scoped_set("SCOPED_SET_ENV_TEST_VAR", "value");
-
- EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "value");
- }
-
- EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "UNSET");
-}
-
-TEST(ScopedSetEnvTest, SetNonExistingVarToNull) {
- EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "UNSET");
-
- {
- ScopedSetEnv scoped_set("SCOPED_SET_ENV_TEST_VAR", nullptr);
-
- EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "UNSET");
- }
-
- EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "UNSET");
-}
-
-TEST(ScopedSetEnvTest, SetExistingVarToString) {
- ScopedSetEnv scoped_set("SCOPED_SET_ENV_TEST_VAR", "value");
- EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "value");
-
- {
- ScopedSetEnv scoped_set("SCOPED_SET_ENV_TEST_VAR", "new_value");
-
- EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "new_value");
- }
-
- EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "value");
-}
-
-TEST(ScopedSetEnvTest, SetExistingVarToNull) {
- ScopedSetEnv scoped_set("SCOPED_SET_ENV_TEST_VAR", "value");
- EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "value");
-
- {
- ScopedSetEnv scoped_set("SCOPED_SET_ENV_TEST_VAR", nullptr);
-
- EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "UNSET");
- }
-
- EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "value");
-}
-
-} // namespace
diff --git a/third_party/abseil-cpp/absl/base/internal/spinlock.cc b/third_party/abseil-cpp/absl/base/internal/spinlock.cc
deleted file mode 100644
index 381b913..0000000
--- a/third_party/abseil-cpp/absl/base/internal/spinlock.cc
+++ /dev/null
@@ -1,232 +0,0 @@
-// Copyright 2017 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/spinlock.h"
-
-#include <algorithm>
-#include <atomic>
-#include <limits>
-
-#include "absl/base/attributes.h"
-#include "absl/base/config.h"
-#include "absl/base/internal/atomic_hook.h"
-#include "absl/base/internal/cycleclock.h"
-#include "absl/base/internal/spinlock_wait.h"
-#include "absl/base/internal/sysinfo.h" /* For NumCPUs() */
-#include "absl/base/call_once.h"
-
-// Description of lock-word:
-// 31..00: [............................3][2][1][0]
-//
-// [0]: kSpinLockHeld
-// [1]: kSpinLockCooperative
-// [2]: kSpinLockDisabledScheduling
-// [31..3]: ONLY kSpinLockSleeper OR
-// Wait time in cycles >> PROFILE_TIMESTAMP_SHIFT
-//
-// Detailed descriptions:
-//
-// Bit [0]: The lock is considered held iff kSpinLockHeld is set.
-//
-// Bit [1]: Eligible waiters (e.g. Fibers) may co-operatively reschedule when
-// contended iff kSpinLockCooperative is set.
-//
-// Bit [2]: This bit is exclusive from bit [1]. It is used only by a
-// non-cooperative lock. When set, indicates that scheduling was
-// successfully disabled when the lock was acquired. May be unset,
-// even if non-cooperative, if a ThreadIdentity did not yet exist at
-// time of acquisition.
-//
-// Bit [3]: If this is the only upper bit ([31..3]) set then this lock was
-// acquired without contention, however, at least one waiter exists.
-//
-// Otherwise, bits [31..3] represent the time spent by the current lock
-// holder to acquire the lock. There may be outstanding waiter(s).
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-
-ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES static base_internal::AtomicHook<void (*)(
- const void *lock, int64_t wait_cycles)>
- submit_profile_data;
-
-void RegisterSpinLockProfiler(void (*fn)(const void *contendedlock,
- int64_t wait_cycles)) {
- submit_profile_data.Store(fn);
-}
-
-#ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL
-// Static member variable definitions.
-constexpr uint32_t SpinLock::kSpinLockHeld;
-constexpr uint32_t SpinLock::kSpinLockCooperative;
-constexpr uint32_t SpinLock::kSpinLockDisabledScheduling;
-constexpr uint32_t SpinLock::kSpinLockSleeper;
-constexpr uint32_t SpinLock::kWaitTimeMask;
-#endif
-
-// Uncommon constructors.
-SpinLock::SpinLock(base_internal::SchedulingMode mode)
- : lockword_(IsCooperative(mode) ? kSpinLockCooperative : 0) {
- ABSL_TSAN_MUTEX_CREATE(this, __tsan_mutex_not_static);
-}
-
-// Monitor the lock to see if its value changes within some time period
-// (adaptive_spin_count loop iterations). The last value read from the lock
-// is returned from the method.
-uint32_t SpinLock::SpinLoop() {
- // We are already in the slow path of SpinLock, initialize the
- // adaptive_spin_count here.
- ABSL_CONST_INIT static absl::once_flag init_adaptive_spin_count;
- ABSL_CONST_INIT static int adaptive_spin_count = 0;
- base_internal::LowLevelCallOnce(&init_adaptive_spin_count, []() {
- adaptive_spin_count = base_internal::NumCPUs() > 1 ? 1000 : 1;
- });
-
- int c = adaptive_spin_count;
- uint32_t lock_value;
- do {
- lock_value = lockword_.load(std::memory_order_relaxed);
- } while ((lock_value & kSpinLockHeld) != 0 && --c > 0);
- return lock_value;
-}
-
-void SpinLock::SlowLock() {
- uint32_t lock_value = SpinLoop();
- lock_value = TryLockInternal(lock_value, 0);
- if ((lock_value & kSpinLockHeld) == 0) {
- return;
- }
-
- base_internal::SchedulingMode scheduling_mode;
- if ((lock_value & kSpinLockCooperative) != 0) {
- scheduling_mode = base_internal::SCHEDULE_COOPERATIVE_AND_KERNEL;
- } else {
- scheduling_mode = base_internal::SCHEDULE_KERNEL_ONLY;
- }
-
- // The lock was not obtained initially, so this thread needs to wait for
- // it. Record the current timestamp in the local variable wait_start_time
- // so the total wait time can be stored in the lockword once this thread
- // obtains the lock.
- int64_t wait_start_time = CycleClock::Now();
- uint32_t wait_cycles = 0;
- int lock_wait_call_count = 0;
- while ((lock_value & kSpinLockHeld) != 0) {
- // If the lock is currently held, but not marked as having a sleeper, mark
- // it as having a sleeper.
- if ((lock_value & kWaitTimeMask) == 0) {
- // Here, just "mark" that the thread is going to sleep. Don't store the
- // lock wait time in the lock -- the lock word stores the amount of time
- // that the current holder waited before acquiring the lock, not the wait
- // time of any thread currently waiting to acquire it.
- if (lockword_.compare_exchange_strong(
- lock_value, lock_value | kSpinLockSleeper,
- std::memory_order_relaxed, std::memory_order_relaxed)) {
- // Successfully transitioned to kSpinLockSleeper. Pass
- // kSpinLockSleeper to the SpinLockWait routine to properly indicate
- // the last lock_value observed.
- lock_value |= kSpinLockSleeper;
- } else if ((lock_value & kSpinLockHeld) == 0) {
- // Lock is free again, so try and acquire it before sleeping. The
- // new lock state will be the number of cycles this thread waited if
- // this thread obtains the lock.
- lock_value = TryLockInternal(lock_value, wait_cycles);
- continue; // Skip the delay at the end of the loop.
- } else if ((lock_value & kWaitTimeMask) == 0) {
- // The lock is still held, without a waiter being marked, but something
- // else about the lock word changed, causing our CAS to fail. For
- // example, a new lock holder may have acquired the lock with
- // kSpinLockDisabledScheduling set, whereas the previous holder had not
- // set that flag. In this case, attempt again to mark ourselves as a
- // waiter.
- continue;
- }
- }
-
- // SpinLockDelay() calls into fiber scheduler, we need to see
- // synchronization there to avoid false positives.
- ABSL_TSAN_MUTEX_PRE_DIVERT(this, 0);
- // Wait for an OS specific delay.
- base_internal::SpinLockDelay(&lockword_, lock_value, ++lock_wait_call_count,
- scheduling_mode);
- ABSL_TSAN_MUTEX_POST_DIVERT(this, 0);
- // Spin again after returning from the wait routine to give this thread
- // some chance of obtaining the lock.
- lock_value = SpinLoop();
- wait_cycles = EncodeWaitCycles(wait_start_time, CycleClock::Now());
- lock_value = TryLockInternal(lock_value, wait_cycles);
- }
-}
-
-void SpinLock::SlowUnlock(uint32_t lock_value) {
- base_internal::SpinLockWake(&lockword_,
- false); // wake waiter if necessary
-
- // If our acquisition was contended, collect contentionz profile info. We
- // reserve a unitary wait time to represent that a waiter exists without our
- // own acquisition having been contended.
- if ((lock_value & kWaitTimeMask) != kSpinLockSleeper) {
- const int64_t wait_cycles = DecodeWaitCycles(lock_value);
- ABSL_TSAN_MUTEX_PRE_DIVERT(this, 0);
- submit_profile_data(this, wait_cycles);
- ABSL_TSAN_MUTEX_POST_DIVERT(this, 0);
- }
-}
-
-// We use the upper 29 bits of the lock word to store the time spent waiting to
-// acquire this lock. This is reported by contentionz profiling. Since the
-// lower bits of the cycle counter wrap very quickly on high-frequency
-// processors we divide to reduce the granularity to 2^kProfileTimestampShift
-// sized units. On a 4Ghz machine this will lose track of wait times greater
-// than (2^29/4 Ghz)*128 =~ 17.2 seconds. Such waits should be extremely rare.
-static constexpr int kProfileTimestampShift = 7;
-
-// We currently reserve the lower 3 bits.
-static constexpr int kLockwordReservedShift = 3;
-
-uint32_t SpinLock::EncodeWaitCycles(int64_t wait_start_time,
- int64_t wait_end_time) {
- static const int64_t kMaxWaitTime =
- std::numeric_limits<uint32_t>::max() >> kLockwordReservedShift;
- int64_t scaled_wait_time =
- (wait_end_time - wait_start_time) >> kProfileTimestampShift;
-
- // Return a representation of the time spent waiting that can be stored in
- // the lock word's upper bits.
- uint32_t clamped = static_cast<uint32_t>(
- std::min(scaled_wait_time, kMaxWaitTime) << kLockwordReservedShift);
-
- if (clamped == 0) {
- return kSpinLockSleeper; // Just wake waiters, but don't record contention.
- }
- // Bump up value if necessary to avoid returning kSpinLockSleeper.
- const uint32_t kMinWaitTime =
- kSpinLockSleeper + (1 << kLockwordReservedShift);
- if (clamped == kSpinLockSleeper) {
- return kMinWaitTime;
- }
- return clamped;
-}
-
-int64_t SpinLock::DecodeWaitCycles(uint32_t lock_value) {
- // Cast to uint32_t first to ensure bits [63:32] are cleared.
- const int64_t scaled_wait_time =
- static_cast<uint32_t>(lock_value & kWaitTimeMask);
- return scaled_wait_time << (kProfileTimestampShift - kLockwordReservedShift);
-}
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/base/internal/spinlock.h b/third_party/abseil-cpp/absl/base/internal/spinlock.h
deleted file mode 100644
index 09ba582..0000000
--- a/third_party/abseil-cpp/absl/base/internal/spinlock.h
+++ /dev/null
@@ -1,252 +0,0 @@
-//
-// Copyright 2017 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.
-//
-
-// Most users requiring mutual exclusion should use Mutex.
-// SpinLock is provided for use in two situations:
-// - for use by Abseil internal code that Mutex itself depends on
-// - for async signal safety (see below)
-
-// SpinLock is async signal safe. If a spinlock is used within a signal
-// handler, all code that acquires the lock must ensure that the signal cannot
-// arrive while they are holding the lock. Typically, this is done by blocking
-// the signal.
-//
-// Threads waiting on a SpinLock may be woken in an arbitrary order.
-
-#ifndef ABSL_BASE_INTERNAL_SPINLOCK_H_
-#define ABSL_BASE_INTERNAL_SPINLOCK_H_
-
-#include <atomic>
-#include <cstdint>
-
-#include "absl/base/attributes.h"
-#include "absl/base/const_init.h"
-#include "absl/base/dynamic_annotations.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/tsan_mutex_interface.h"
-#include "absl/base/thread_annotations.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-
-class ABSL_LOCKABLE SpinLock {
- public:
- SpinLock() : lockword_(kSpinLockCooperative) {
- ABSL_TSAN_MUTEX_CREATE(this, __tsan_mutex_not_static);
- }
-
- // Constructors that allow non-cooperative spinlocks to be created for use
- // inside thread schedulers. Normal clients should not use these.
- explicit SpinLock(base_internal::SchedulingMode mode);
-
- // Constructor for global SpinLock instances. See absl/base/const_init.h.
- constexpr SpinLock(absl::ConstInitType, base_internal::SchedulingMode mode)
- : lockword_(IsCooperative(mode) ? kSpinLockCooperative : 0) {}
-
- // For global SpinLock instances prefer trivial destructor when possible.
- // Default but non-trivial destructor in some build configurations causes an
- // extra static initializer.
-#ifdef ABSL_INTERNAL_HAVE_TSAN_INTERFACE
- ~SpinLock() { ABSL_TSAN_MUTEX_DESTROY(this, __tsan_mutex_not_static); }
-#else
- ~SpinLock() = default;
-#endif
-
- // Acquire this SpinLock.
- inline void Lock() ABSL_EXCLUSIVE_LOCK_FUNCTION() {
- ABSL_TSAN_MUTEX_PRE_LOCK(this, 0);
- if (!TryLockImpl()) {
- SlowLock();
- }
- ABSL_TSAN_MUTEX_POST_LOCK(this, 0, 0);
- }
-
- // Try to acquire this SpinLock without blocking and return true if the
- // acquisition was successful. If the lock was not acquired, false is
- // returned. If this SpinLock is free at the time of the call, TryLock
- // will return true with high probability.
- inline bool TryLock() ABSL_EXCLUSIVE_TRYLOCK_FUNCTION(true) {
- ABSL_TSAN_MUTEX_PRE_LOCK(this, __tsan_mutex_try_lock);
- bool res = TryLockImpl();
- ABSL_TSAN_MUTEX_POST_LOCK(
- this, __tsan_mutex_try_lock | (res ? 0 : __tsan_mutex_try_lock_failed),
- 0);
- return res;
- }
-
- // Release this SpinLock, which must be held by the calling thread.
- inline void Unlock() ABSL_UNLOCK_FUNCTION() {
- ABSL_TSAN_MUTEX_PRE_UNLOCK(this, 0);
- uint32_t lock_value = lockword_.load(std::memory_order_relaxed);
- lock_value = lockword_.exchange(lock_value & kSpinLockCooperative,
- std::memory_order_release);
-
- if ((lock_value & kSpinLockDisabledScheduling) != 0) {
- base_internal::SchedulingGuard::EnableRescheduling(true);
- }
- if ((lock_value & kWaitTimeMask) != 0) {
- // Collect contentionz profile info, and speed the wakeup of any waiter.
- // The wait_cycles value indicates how long this thread spent waiting
- // for the lock.
- SlowUnlock(lock_value);
- }
- ABSL_TSAN_MUTEX_POST_UNLOCK(this, 0);
- }
-
- // Determine if the lock is held. When the lock is held by the invoking
- // thread, true will always be returned. Intended to be used as
- // CHECK(lock.IsHeld()).
- inline bool IsHeld() const {
- return (lockword_.load(std::memory_order_relaxed) & kSpinLockHeld) != 0;
- }
-
- // Return immediately if this thread holds the SpinLock exclusively.
- // Otherwise, report an error by crashing with a diagnostic.
- inline void AssertHeld() const ABSL_ASSERT_EXCLUSIVE_LOCK() {
- if (!IsHeld()) {
- ABSL_RAW_LOG(FATAL, "thread should hold the lock on SpinLock");
- }
- }
-
- protected:
- // These should not be exported except for testing.
-
- // Store number of cycles between wait_start_time and wait_end_time in a
- // lock value.
- static uint32_t EncodeWaitCycles(int64_t wait_start_time,
- int64_t wait_end_time);
-
- // Extract number of wait cycles in a lock value.
- static int64_t DecodeWaitCycles(uint32_t lock_value);
-
- // Provide access to protected method above. Use for testing only.
- friend struct SpinLockTest;
-
- private:
- // lockword_ is used to store the following:
- //
- // bit[0] encodes whether a lock is being held.
- // bit[1] encodes whether a lock uses cooperative scheduling.
- // bit[2] encodes whether the current lock holder disabled scheduling when
- // acquiring the lock. Only set when kSpinLockHeld is also set.
- // bit[3:31] encodes time a lock spent on waiting as a 29-bit unsigned int.
- // This is set by the lock holder to indicate how long it waited on
- // the lock before eventually acquiring it. The number of cycles is
- // encoded as a 29-bit unsigned int, or in the case that the current
- // holder did not wait but another waiter is queued, the LSB
- // (kSpinLockSleeper) is set. The implementation does not explicitly
- // track the number of queued waiters beyond this. It must always be
- // assumed that waiters may exist if the current holder was required to
- // queue.
- //
- // Invariant: if the lock is not held, the value is either 0 or
- // kSpinLockCooperative.
- static constexpr uint32_t kSpinLockHeld = 1;
- static constexpr uint32_t kSpinLockCooperative = 2;
- static constexpr uint32_t kSpinLockDisabledScheduling = 4;
- static constexpr uint32_t kSpinLockSleeper = 8;
- // Includes kSpinLockSleeper.
- static constexpr uint32_t kWaitTimeMask =
- ~(kSpinLockHeld | kSpinLockCooperative | kSpinLockDisabledScheduling);
-
- // Returns true if the provided scheduling mode is cooperative.
- static constexpr bool IsCooperative(
- base_internal::SchedulingMode scheduling_mode) {
- return scheduling_mode == base_internal::SCHEDULE_COOPERATIVE_AND_KERNEL;
- }
-
- uint32_t TryLockInternal(uint32_t lock_value, uint32_t wait_cycles);
- void SlowLock() ABSL_ATTRIBUTE_COLD;
- void SlowUnlock(uint32_t lock_value) ABSL_ATTRIBUTE_COLD;
- uint32_t SpinLoop();
-
- inline bool TryLockImpl() {
- uint32_t lock_value = lockword_.load(std::memory_order_relaxed);
- return (TryLockInternal(lock_value, 0) & kSpinLockHeld) == 0;
- }
-
- std::atomic<uint32_t> lockword_;
-
- SpinLock(const SpinLock&) = delete;
- SpinLock& operator=(const SpinLock&) = delete;
-};
-
-// Corresponding locker object that arranges to acquire a spinlock for
-// the duration of a C++ scope.
-class ABSL_SCOPED_LOCKABLE SpinLockHolder {
- public:
- inline explicit SpinLockHolder(SpinLock* l) ABSL_EXCLUSIVE_LOCK_FUNCTION(l)
- : lock_(l) {
- l->Lock();
- }
- inline ~SpinLockHolder() ABSL_UNLOCK_FUNCTION() { lock_->Unlock(); }
-
- SpinLockHolder(const SpinLockHolder&) = delete;
- SpinLockHolder& operator=(const SpinLockHolder&) = delete;
-
- private:
- SpinLock* lock_;
-};
-
-// Register a hook for profiling support.
-//
-// The function pointer registered here will be called whenever a spinlock is
-// contended. The callback is given an opaque handle to the contended spinlock
-// and the number of wait cycles. This is thread-safe, but only a single
-// profiler can be registered. It is an error to call this function multiple
-// times with different arguments.
-void RegisterSpinLockProfiler(void (*fn)(const void* lock,
- int64_t wait_cycles));
-
-//------------------------------------------------------------------------------
-// Public interface ends here.
-//------------------------------------------------------------------------------
-
-// If (result & kSpinLockHeld) == 0, then *this was successfully locked.
-// Otherwise, returns last observed value for lockword_.
-inline uint32_t SpinLock::TryLockInternal(uint32_t lock_value,
- uint32_t wait_cycles) {
- if ((lock_value & kSpinLockHeld) != 0) {
- return lock_value;
- }
-
- uint32_t sched_disabled_bit = 0;
- if ((lock_value & kSpinLockCooperative) == 0) {
- // For non-cooperative locks we must make sure we mark ourselves as
- // non-reschedulable before we attempt to CompareAndSwap.
- if (base_internal::SchedulingGuard::DisableRescheduling()) {
- sched_disabled_bit = kSpinLockDisabledScheduling;
- }
- }
-
- if (!lockword_.compare_exchange_strong(
- lock_value,
- kSpinLockHeld | lock_value | wait_cycles | sched_disabled_bit,
- std::memory_order_acquire, std::memory_order_relaxed)) {
- base_internal::SchedulingGuard::EnableRescheduling(sched_disabled_bit != 0);
- }
-
- return lock_value;
-}
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_BASE_INTERNAL_SPINLOCK_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/spinlock_akaros.inc b/third_party/abseil-cpp/absl/base/internal/spinlock_akaros.inc
deleted file mode 100644
index 7b0cada..0000000
--- a/third_party/abseil-cpp/absl/base/internal/spinlock_akaros.inc
+++ /dev/null
@@ -1,35 +0,0 @@
-// Copyright 2017 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.
-//
-// This file is an Akaros-specific part of spinlock_wait.cc
-
-#include <atomic>
-
-#include "absl/base/internal/scheduling_mode.h"
-
-extern "C" {
-
-ABSL_ATTRIBUTE_WEAK void ABSL_INTERNAL_C_SYMBOL(AbslInternalSpinLockDelay)(
- std::atomic<uint32_t>* /* lock_word */, uint32_t /* value */,
- int /* loop */, absl::base_internal::SchedulingMode /* mode */) {
- // In Akaros, one must take care not to call anything that could cause a
- // malloc(), a blocking system call, or a uthread_yield() while holding a
- // spinlock. Our callers assume will not call into libraries or other
- // arbitrary code.
-}
-
-ABSL_ATTRIBUTE_WEAK void ABSL_INTERNAL_C_SYMBOL(AbslInternalSpinLockWake)(
- std::atomic<uint32_t>* /* lock_word */, bool /* all */) {}
-
-} // extern "C"
diff --git a/third_party/abseil-cpp/absl/base/internal/spinlock_benchmark.cc b/third_party/abseil-cpp/absl/base/internal/spinlock_benchmark.cc
deleted file mode 100644
index 0451c65..0000000
--- a/third_party/abseil-cpp/absl/base/internal/spinlock_benchmark.cc
+++ /dev/null
@@ -1,52 +0,0 @@
-// Copyright 2018 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.
-
-// See also //absl/synchronization:mutex_benchmark for a comparison of SpinLock
-// and Mutex performance under varying levels of contention.
-
-#include "absl/base/internal/raw_logging.h"
-#include "absl/base/internal/scheduling_mode.h"
-#include "absl/base/internal/spinlock.h"
-#include "absl/synchronization/internal/create_thread_identity.h"
-#include "benchmark/benchmark.h"
-
-namespace {
-
-template <absl::base_internal::SchedulingMode scheduling_mode>
-static void BM_SpinLock(benchmark::State& state) {
- // Ensure a ThreadIdentity is installed.
- ABSL_INTERNAL_CHECK(
- absl::synchronization_internal::GetOrCreateCurrentThreadIdentity() !=
- nullptr,
- "GetOrCreateCurrentThreadIdentity() failed");
-
- static auto* spinlock = new absl::base_internal::SpinLock(scheduling_mode);
- for (auto _ : state) {
- absl::base_internal::SpinLockHolder holder(spinlock);
- }
-}
-
-BENCHMARK_TEMPLATE(BM_SpinLock,
- absl::base_internal::SCHEDULE_KERNEL_ONLY)
- ->UseRealTime()
- ->Threads(1)
- ->ThreadPerCpu();
-
-BENCHMARK_TEMPLATE(BM_SpinLock,
- absl::base_internal::SCHEDULE_COOPERATIVE_AND_KERNEL)
- ->UseRealTime()
- ->Threads(1)
- ->ThreadPerCpu();
-
-} // namespace
diff --git a/third_party/abseil-cpp/absl/base/internal/spinlock_linux.inc b/third_party/abseil-cpp/absl/base/internal/spinlock_linux.inc
deleted file mode 100644
index fe8ba67..0000000
--- a/third_party/abseil-cpp/absl/base/internal/spinlock_linux.inc
+++ /dev/null
@@ -1,71 +0,0 @@
-// Copyright 2018 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.
-//
-// This file is a Linux-specific part of spinlock_wait.cc
-
-#include <linux/futex.h>
-#include <sys/syscall.h>
-#include <unistd.h>
-
-#include <atomic>
-#include <climits>
-#include <cstdint>
-#include <ctime>
-
-#include "absl/base/attributes.h"
-#include "absl/base/internal/errno_saver.h"
-
-// The SpinLock lockword is `std::atomic<uint32_t>`. Here we assert that
-// `std::atomic<uint32_t>` is bitwise equivalent of the `int` expected
-// by SYS_futex. We also assume that reads/writes done to the lockword
-// by SYS_futex have rational semantics with regard to the
-// std::atomic<> API. C++ provides no guarantees of these assumptions,
-// but they are believed to hold in practice.
-static_assert(sizeof(std::atomic<uint32_t>) == sizeof(int),
- "SpinLock lockword has the wrong size for a futex");
-
-// Some Android headers are missing these definitions even though they
-// support these futex operations.
-#ifdef __BIONIC__
-#ifndef SYS_futex
-#define SYS_futex __NR_futex
-#endif
-#ifndef FUTEX_PRIVATE_FLAG
-#define FUTEX_PRIVATE_FLAG 128
-#endif
-#endif
-
-#if defined(__NR_futex_time64) && !defined(SYS_futex_time64)
-#define SYS_futex_time64 __NR_futex_time64
-#endif
-
-#if defined(SYS_futex_time64) && !defined(SYS_futex)
-#define SYS_futex SYS_futex_time64
-#endif
-
-extern "C" {
-
-ABSL_ATTRIBUTE_WEAK void ABSL_INTERNAL_C_SYMBOL(AbslInternalSpinLockDelay)(
- std::atomic<uint32_t> *w, uint32_t value, int,
- absl::base_internal::SchedulingMode) {
- absl::base_internal::ErrnoSaver errno_saver;
- syscall(SYS_futex, w, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, value, nullptr);
-}
-
-ABSL_ATTRIBUTE_WEAK void ABSL_INTERNAL_C_SYMBOL(AbslInternalSpinLockWake)(
- std::atomic<uint32_t> *w, bool all) {
- syscall(SYS_futex, w, FUTEX_WAKE | FUTEX_PRIVATE_FLAG, all ? INT_MAX : 1, 0);
-}
-
-} // extern "C"
diff --git a/third_party/abseil-cpp/absl/base/internal/spinlock_posix.inc b/third_party/abseil-cpp/absl/base/internal/spinlock_posix.inc
deleted file mode 100644
index 4f6f887..0000000
--- a/third_party/abseil-cpp/absl/base/internal/spinlock_posix.inc
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright 2017 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.
-//
-// This file is a Posix-specific part of spinlock_wait.cc
-
-#include <sched.h>
-
-#include <atomic>
-#include <ctime>
-
-#include "absl/base/internal/errno_saver.h"
-#include "absl/base/internal/scheduling_mode.h"
-#include "absl/base/port.h"
-
-extern "C" {
-
-ABSL_ATTRIBUTE_WEAK void ABSL_INTERNAL_C_SYMBOL(AbslInternalSpinLockDelay)(
- std::atomic<uint32_t>* /* lock_word */, uint32_t /* value */, int loop,
- absl::base_internal::SchedulingMode /* mode */) {
- absl::base_internal::ErrnoSaver errno_saver;
- if (loop == 0) {
- } else if (loop == 1) {
- sched_yield();
- } else {
- struct timespec tm;
- tm.tv_sec = 0;
- tm.tv_nsec = absl::base_internal::SpinLockSuggestedDelayNS(loop);
- nanosleep(&tm, nullptr);
- }
-}
-
-ABSL_ATTRIBUTE_WEAK void ABSL_INTERNAL_C_SYMBOL(AbslInternalSpinLockWake)(
- std::atomic<uint32_t>* /* lock_word */, bool /* all */) {}
-
-} // extern "C"
diff --git a/third_party/abseil-cpp/absl/base/internal/spinlock_wait.cc b/third_party/abseil-cpp/absl/base/internal/spinlock_wait.cc
deleted file mode 100644
index fa824be..0000000
--- a/third_party/abseil-cpp/absl/base/internal/spinlock_wait.cc
+++ /dev/null
@@ -1,81 +0,0 @@
-// Copyright 2017 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.
-
-// The OS-specific header included below must provide two calls:
-// AbslInternalSpinLockDelay() and AbslInternalSpinLockWake().
-// See spinlock_wait.h for the specs.
-
-#include <atomic>
-#include <cstdint>
-
-#include "absl/base/internal/spinlock_wait.h"
-
-#if defined(_WIN32)
-#include "absl/base/internal/spinlock_win32.inc"
-#elif defined(__linux__)
-#include "absl/base/internal/spinlock_linux.inc"
-#elif defined(__akaros__)
-#include "absl/base/internal/spinlock_akaros.inc"
-#else
-#include "absl/base/internal/spinlock_posix.inc"
-#endif
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-
-// See spinlock_wait.h for spec.
-uint32_t SpinLockWait(std::atomic<uint32_t> *w, int n,
- const SpinLockWaitTransition trans[],
- base_internal::SchedulingMode scheduling_mode) {
- int loop = 0;
- for (;;) {
- uint32_t v = w->load(std::memory_order_acquire);
- int i;
- for (i = 0; i != n && v != trans[i].from; i++) {
- }
- if (i == n) {
- SpinLockDelay(w, v, ++loop, scheduling_mode); // no matching transition
- } else if (trans[i].to == v || // null transition
- w->compare_exchange_strong(v, trans[i].to,
- std::memory_order_acquire,
- std::memory_order_relaxed)) {
- if (trans[i].done) return v;
- }
- }
-}
-
-static std::atomic<uint64_t> delay_rand;
-
-// Return a suggested delay in nanoseconds for iteration number "loop"
-int SpinLockSuggestedDelayNS(int loop) {
- // Weak pseudo-random number generator to get some spread between threads
- // when many are spinning.
- uint64_t r = delay_rand.load(std::memory_order_relaxed);
- r = 0x5deece66dLL * r + 0xb; // numbers from nrand48()
- delay_rand.store(r, std::memory_order_relaxed);
-
- if (loop < 0 || loop > 32) { // limit loop to 0..32
- loop = 32;
- }
- const int kMinDelay = 128 << 10; // 128us
- // Double delay every 8 iterations, up to 16x (2ms).
- int delay = kMinDelay << (loop / 8);
- // Randomize in delay..2*delay range, for resulting 128us..4ms range.
- return delay | ((delay - 1) & static_cast<int>(r));
-}
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/base/internal/spinlock_wait.h b/third_party/abseil-cpp/absl/base/internal/spinlock_wait.h
deleted file mode 100644
index 9a1adcd..0000000
--- a/third_party/abseil-cpp/absl/base/internal/spinlock_wait.h
+++ /dev/null
@@ -1,95 +0,0 @@
-// Copyright 2017 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_SPINLOCK_WAIT_H_
-#define ABSL_BASE_INTERNAL_SPINLOCK_WAIT_H_
-
-// Operations to make atomic transitions on a word, and to allow
-// waiting for those transitions to become possible.
-
-#include <stdint.h>
-#include <atomic>
-
-#include "absl/base/internal/scheduling_mode.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-
-// SpinLockWait() waits until it can perform one of several transitions from
-// "from" to "to". It returns when it performs a transition where done==true.
-struct SpinLockWaitTransition {
- uint32_t from;
- uint32_t to;
- bool done;
-};
-
-// Wait until *w can transition from trans[i].from to trans[i].to for some i
-// satisfying 0<=i<n && trans[i].done, atomically make the transition,
-// then return the old value of *w. Make any other atomic transitions
-// where !trans[i].done, but continue waiting.
-//
-// Wakeups for threads blocked on SpinLockWait do not respect priorities.
-uint32_t SpinLockWait(std::atomic<uint32_t> *w, int n,
- const SpinLockWaitTransition trans[],
- SchedulingMode scheduling_mode);
-
-// If possible, wake some thread that has called SpinLockDelay(w, ...). If `all`
-// is true, wake all such threads. On some systems, this may be a no-op; on
-// those systems, threads calling SpinLockDelay() will always wake eventually
-// even if SpinLockWake() is never called.
-void SpinLockWake(std::atomic<uint32_t> *w, bool all);
-
-// Wait for an appropriate spin delay on iteration "loop" of a
-// spin loop on location *w, whose previously observed value was "value".
-// SpinLockDelay() may do nothing, may yield the CPU, may sleep a clock tick,
-// or may wait for a call to SpinLockWake(w).
-void SpinLockDelay(std::atomic<uint32_t> *w, uint32_t value, int loop,
- base_internal::SchedulingMode scheduling_mode);
-
-// Helper used by AbslInternalSpinLockDelay.
-// Returns a suggested delay in nanoseconds for iteration number "loop".
-int SpinLockSuggestedDelayNS(int loop);
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-// In some build configurations we pass --detect-odr-violations to the
-// gold linker. This causes it to flag weak symbol overrides as ODR
-// violations. Because ODR only applies to C++ and not C,
-// --detect-odr-violations ignores symbols not mangled with C++ names.
-// By changing our extension points to be extern "C", we dodge this
-// check.
-extern "C" {
-void ABSL_INTERNAL_C_SYMBOL(AbslInternalSpinLockWake)(std::atomic<uint32_t> *w,
- bool all);
-void ABSL_INTERNAL_C_SYMBOL(AbslInternalSpinLockDelay)(
- std::atomic<uint32_t> *w, uint32_t value, int loop,
- absl::base_internal::SchedulingMode scheduling_mode);
-}
-
-inline void absl::base_internal::SpinLockWake(std::atomic<uint32_t> *w,
- bool all) {
- ABSL_INTERNAL_C_SYMBOL(AbslInternalSpinLockWake)(w, all);
-}
-
-inline void absl::base_internal::SpinLockDelay(
- std::atomic<uint32_t> *w, uint32_t value, int loop,
- absl::base_internal::SchedulingMode scheduling_mode) {
- ABSL_INTERNAL_C_SYMBOL(AbslInternalSpinLockDelay)
- (w, value, loop, scheduling_mode);
-}
-
-#endif // ABSL_BASE_INTERNAL_SPINLOCK_WAIT_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/spinlock_win32.inc b/third_party/abseil-cpp/absl/base/internal/spinlock_win32.inc
deleted file mode 100644
index 934c201..0000000
--- a/third_party/abseil-cpp/absl/base/internal/spinlock_win32.inc
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright 2017 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.
-//
-// This file is a Win32-specific part of spinlock_wait.cc
-
-#include <windows.h>
-#include <atomic>
-#include "absl/base/internal/scheduling_mode.h"
-
-extern "C" {
-
-void ABSL_INTERNAL_C_SYMBOL(AbslInternalSpinLockDelay)(
- std::atomic<uint32_t>* /* lock_word */, uint32_t /* value */, int loop,
- absl::base_internal::SchedulingMode /* mode */) {
- if (loop == 0) {
- } else if (loop == 1) {
- Sleep(0);
- } else {
- // SpinLockSuggestedDelayNS() always returns a positive integer, so this
- // static_cast is safe.
- Sleep(static_cast<DWORD>(
- absl::base_internal::SpinLockSuggestedDelayNS(loop) / 1000000));
- }
-}
-
-void ABSL_INTERNAL_C_SYMBOL(AbslInternalSpinLockWake)(
- std::atomic<uint32_t>* /* lock_word */, bool /* all */) {}
-
-} // extern "C"
diff --git a/third_party/abseil-cpp/absl/base/internal/strerror.cc b/third_party/abseil-cpp/absl/base/internal/strerror.cc
deleted file mode 100644
index de91c05..0000000
--- a/third_party/abseil-cpp/absl/base/internal/strerror.cc
+++ /dev/null
@@ -1,88 +0,0 @@
-// 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/strerror.h"
-
-#include <array>
-#include <cerrno>
-#include <cstddef>
-#include <cstdio>
-#include <cstring>
-#include <string>
-#include <type_traits>
-
-#include "absl/base/internal/errno_saver.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-namespace {
-
-const char* StrErrorAdaptor(int errnum, char* buf, size_t buflen) {
-#if defined(_WIN32)
- int rc = strerror_s(buf, buflen, errnum);
- buf[buflen - 1] = '\0'; // guarantee NUL termination
- if (rc == 0 && strncmp(buf, "Unknown error", buflen) == 0) *buf = '\0';
- return buf;
-#else
- // The type of `ret` is platform-specific; both of these branches must compile
- // either way but only one will execute on any given platform:
- auto ret = strerror_r(errnum, buf, buflen);
- if (std::is_same<decltype(ret), int>::value) {
- // XSI `strerror_r`; `ret` is `int`:
- if (ret) *buf = '\0';
- return buf;
- } else {
- // GNU `strerror_r`; `ret` is `char *`:
- return reinterpret_cast<const char*>(ret);
- }
-#endif
-}
-
-std::string StrErrorInternal(int errnum) {
- char buf[100];
- const char* str = StrErrorAdaptor(errnum, buf, sizeof buf);
- if (*str == '\0') {
- snprintf(buf, sizeof buf, "Unknown error %d", errnum);
- str = buf;
- }
- return str;
-}
-
-// kSysNerr is the number of errors from a recent glibc. `StrError()` falls back
-// to `StrErrorAdaptor()` if the value is larger than this.
-constexpr int kSysNerr = 135;
-
-std::array<std::string, kSysNerr>* NewStrErrorTable() {
- auto* table = new std::array<std::string, kSysNerr>;
- for (size_t i = 0; i < table->size(); ++i) {
- (*table)[i] = StrErrorInternal(static_cast<int>(i));
- }
- return table;
-}
-
-} // namespace
-
-std::string StrError(int errnum) {
- absl::base_internal::ErrnoSaver errno_saver;
- static const auto* table = NewStrErrorTable();
- if (errnum >= 0 && static_cast<size_t>(errnum) < table->size()) {
- return (*table)[static_cast<size_t>(errnum)];
- }
- return StrErrorInternal(errnum);
-}
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/base/internal/strerror.h b/third_party/abseil-cpp/absl/base/internal/strerror.h
deleted file mode 100644
index 3500973..0000000
--- a/third_party/abseil-cpp/absl/base/internal/strerror.h
+++ /dev/null
@@ -1,39 +0,0 @@
-// 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_STRERROR_H_
-#define ABSL_BASE_INTERNAL_STRERROR_H_
-
-#include <string>
-
-#include "absl/base/config.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-
-// A portable and thread-safe alternative to C89's `strerror`.
-//
-// The C89 specification of `strerror` is not suitable for use in a
-// multi-threaded application as the returned string may be changed by calls to
-// `strerror` from another thread. The many non-stdlib alternatives differ
-// enough in their names, availability, and semantics to justify this wrapper
-// around them. `errno` will not be modified by a call to `absl::StrError`.
-std::string StrError(int errnum);
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_BASE_INTERNAL_STRERROR_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/strerror_benchmark.cc b/third_party/abseil-cpp/absl/base/internal/strerror_benchmark.cc
deleted file mode 100644
index c9ab14a..0000000
--- a/third_party/abseil-cpp/absl/base/internal/strerror_benchmark.cc
+++ /dev/null
@@ -1,29 +0,0 @@
-// 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 <cerrno>
-#include <cstdio>
-#include <string>
-
-#include "absl/base/internal/strerror.h"
-#include "benchmark/benchmark.h"
-
-namespace {
-void BM_AbslStrError(benchmark::State& state) {
- for (auto _ : state) {
- benchmark::DoNotOptimize(absl::base_internal::StrError(ERANGE));
- }
-}
-BENCHMARK(BM_AbslStrError);
-} // namespace
diff --git a/third_party/abseil-cpp/absl/base/internal/strerror_test.cc b/third_party/abseil-cpp/absl/base/internal/strerror_test.cc
deleted file mode 100644
index e32d5b5..0000000
--- a/third_party/abseil-cpp/absl/base/internal/strerror_test.cc
+++ /dev/null
@@ -1,88 +0,0 @@
-// 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/strerror.h"
-
-#include <atomic>
-#include <cerrno>
-#include <cstdio>
-#include <cstring>
-#include <string>
-#include <thread> // NOLINT(build/c++11)
-#include <vector>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/strings/match.h"
-
-namespace {
-using ::testing::AnyOf;
-using ::testing::Eq;
-
-TEST(StrErrorTest, ValidErrorCode) {
- errno = ERANGE;
- EXPECT_THAT(absl::base_internal::StrError(EDOM), Eq(strerror(EDOM)));
- EXPECT_THAT(errno, Eq(ERANGE));
-}
-
-TEST(StrErrorTest, InvalidErrorCode) {
- errno = ERANGE;
- EXPECT_THAT(absl::base_internal::StrError(-1),
- AnyOf(Eq("No error information"), Eq("Unknown error -1")));
- EXPECT_THAT(errno, Eq(ERANGE));
-}
-
-TEST(StrErrorTest, MultipleThreads) {
- // In this test, we will start up 2 threads and have each one call
- // StrError 1000 times, each time with a different errnum. We
- // expect that StrError(errnum) will return a string equal to the
- // one returned by strerror(errnum), if the code is known. Since
- // strerror is known to be thread-hostile, collect all the expected
- // strings up front.
- const int kNumCodes = 1000;
- std::vector<std::string> expected_strings(kNumCodes);
- for (int i = 0; i < kNumCodes; ++i) {
- expected_strings[i] = strerror(i);
- }
-
- std::atomic_int counter(0);
- auto thread_fun = [&]() {
- for (int i = 0; i < kNumCodes; ++i) {
- ++counter;
- errno = ERANGE;
- const std::string value = absl::base_internal::StrError(i);
- // EXPECT_* could change errno. Stash it first.
- int check_err = errno;
- EXPECT_THAT(check_err, Eq(ERANGE));
- // Only the GNU implementation is guaranteed to provide the
- // string "Unknown error nnn". POSIX doesn't say anything.
- if (!absl::StartsWith(value, "Unknown error ")) {
- EXPECT_THAT(value, Eq(expected_strings[i]));
- }
- }
- };
-
- const int kNumThreads = 100;
- std::vector<std::thread> threads;
- for (int i = 0; i < kNumThreads; ++i) {
- threads.push_back(std::thread(thread_fun));
- }
- for (auto& thread : threads) {
- thread.join();
- }
-
- EXPECT_THAT(counter, Eq(kNumThreads * kNumCodes));
-}
-
-} // namespace
diff --git a/third_party/abseil-cpp/absl/base/internal/sysinfo.cc b/third_party/abseil-cpp/absl/base/internal/sysinfo.cc
deleted file mode 100644
index da499d3..0000000
--- a/third_party/abseil-cpp/absl/base/internal/sysinfo.cc
+++ /dev/null
@@ -1,511 +0,0 @@
-// Copyright 2017 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/sysinfo.h"
-
-#include "absl/base/attributes.h"
-
-#ifdef _WIN32
-#include <windows.h>
-#else
-#include <fcntl.h>
-#include <pthread.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
-#endif
-
-#ifdef __linux__
-#include <sys/syscall.h>
-#endif
-
-#if defined(__APPLE__) || defined(__FreeBSD__)
-#include <sys/sysctl.h>
-#endif
-
-#if defined(__myriad2__)
-#include <rtems.h>
-#endif
-
-#include <string.h>
-
-#include <cassert>
-#include <cstdint>
-#include <cstdio>
-#include <cstdlib>
-#include <ctime>
-#include <limits>
-#include <thread> // NOLINT(build/c++11)
-#include <utility>
-#include <vector>
-
-#include "absl/base/call_once.h"
-#include "absl/base/config.h"
-#include "absl/base/internal/raw_logging.h"
-#include "absl/base/internal/spinlock.h"
-#include "absl/base/internal/unscaledcycleclock.h"
-#include "absl/base/thread_annotations.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-
-namespace {
-
-#if defined(_WIN32)
-
-// Returns number of bits set in `bitMask`
-DWORD Win32CountSetBits(ULONG_PTR bitMask) {
- for (DWORD bitSetCount = 0; ; ++bitSetCount) {
- if (bitMask == 0) return bitSetCount;
- bitMask &= bitMask - 1;
- }
-}
-
-// Returns the number of logical CPUs using GetLogicalProcessorInformation(), or
-// 0 if the number of processors is not available or can not be computed.
-// https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getlogicalprocessorinformation
-int Win32NumCPUs() {
-#pragma comment(lib, "kernel32.lib")
- using Info = SYSTEM_LOGICAL_PROCESSOR_INFORMATION;
-
- DWORD info_size = sizeof(Info);
- Info* info(static_cast<Info*>(malloc(info_size)));
- if (info == nullptr) return 0;
-
- bool success = GetLogicalProcessorInformation(info, &info_size);
- if (!success && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
- free(info);
- info = static_cast<Info*>(malloc(info_size));
- if (info == nullptr) return 0;
- success = GetLogicalProcessorInformation(info, &info_size);
- }
-
- DWORD logicalProcessorCount = 0;
- if (success) {
- Info* ptr = info;
- DWORD byteOffset = 0;
- while (byteOffset + sizeof(Info) <= info_size) {
- switch (ptr->Relationship) {
- case RelationProcessorCore:
- logicalProcessorCount += Win32CountSetBits(ptr->ProcessorMask);
- break;
-
- case RelationNumaNode:
- case RelationCache:
- case RelationProcessorPackage:
- // Ignore other entries
- break;
-
- default:
- // Ignore unknown entries
- break;
- }
- byteOffset += sizeof(Info);
- ptr++;
- }
- }
- free(info);
- return static_cast<int>(logicalProcessorCount);
-}
-
-#endif
-
-} // namespace
-
-static int GetNumCPUs() {
-#if defined(__myriad2__)
- return 1;
-#elif defined(_WIN32)
- const int hardware_concurrency = Win32NumCPUs();
- return hardware_concurrency ? hardware_concurrency : 1;
-#elif defined(_AIX)
- return sysconf(_SC_NPROCESSORS_ONLN);
-#else
- // Other possibilities:
- // - Read /sys/devices/system/cpu/online and use cpumask_parse()
- // - sysconf(_SC_NPROCESSORS_ONLN)
- return static_cast<int>(std::thread::hardware_concurrency());
-#endif
-}
-
-#if defined(_WIN32)
-
-static double GetNominalCPUFrequency() {
-#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) && \
- !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
- // UWP apps don't have access to the registry and currently don't provide an
- // API informing about CPU nominal frequency.
- return 1.0;
-#else
-#pragma comment(lib, "advapi32.lib") // For Reg* functions.
- HKEY key;
- // Use the Reg* functions rather than the SH functions because shlwapi.dll
- // pulls in gdi32.dll which makes process destruction much more costly.
- if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,
- "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0,
- KEY_READ, &key) == ERROR_SUCCESS) {
- DWORD type = 0;
- DWORD data = 0;
- DWORD data_size = sizeof(data);
- auto result = RegQueryValueExA(key, "~MHz", 0, &type,
- reinterpret_cast<LPBYTE>(&data), &data_size);
- RegCloseKey(key);
- if (result == ERROR_SUCCESS && type == REG_DWORD &&
- data_size == sizeof(data)) {
- return data * 1e6; // Value is MHz.
- }
- }
- return 1.0;
-#endif // WINAPI_PARTITION_APP && !WINAPI_PARTITION_DESKTOP
-}
-
-#elif defined(CTL_HW) && defined(HW_CPU_FREQ)
-
-static double GetNominalCPUFrequency() {
- unsigned freq;
- size_t size = sizeof(freq);
- int mib[2] = {CTL_HW, HW_CPU_FREQ};
- if (sysctl(mib, 2, &freq, &size, nullptr, 0) == 0) {
- return static_cast<double>(freq);
- }
- return 1.0;
-}
-
-#else
-
-// Helper function for reading a long from a file. Returns true if successful
-// and the memory location pointed to by value is set to the value read.
-static bool ReadLongFromFile(const char *file, long *value) {
- bool ret = false;
- int fd = open(file, O_RDONLY | O_CLOEXEC);
- if (fd != -1) {
- char line[1024];
- char *err;
- memset(line, '\0', sizeof(line));
- ssize_t len;
- do {
- len = read(fd, line, sizeof(line) - 1);
- } while (len < 0 && errno == EINTR);
- if (len <= 0) {
- ret = false;
- } else {
- const long temp_value = strtol(line, &err, 10);
- if (line[0] != '\0' && (*err == '\n' || *err == '\0')) {
- *value = temp_value;
- ret = true;
- }
- }
- close(fd);
- }
- return ret;
-}
-
-#if defined(ABSL_INTERNAL_UNSCALED_CYCLECLOCK_FREQUENCY_IS_CPU_FREQUENCY)
-
-// Reads a monotonic time source and returns a value in
-// nanoseconds. The returned value uses an arbitrary epoch, not the
-// Unix epoch.
-static int64_t ReadMonotonicClockNanos() {
- struct timespec t;
-#ifdef CLOCK_MONOTONIC_RAW
- int rc = clock_gettime(CLOCK_MONOTONIC_RAW, &t);
-#else
- int rc = clock_gettime(CLOCK_MONOTONIC, &t);
-#endif
- if (rc != 0) {
- perror("clock_gettime() failed");
- abort();
- }
- return int64_t{t.tv_sec} * 1000000000 + t.tv_nsec;
-}
-
-class UnscaledCycleClockWrapperForInitializeFrequency {
- public:
- static int64_t Now() { return base_internal::UnscaledCycleClock::Now(); }
-};
-
-struct TimeTscPair {
- int64_t time; // From ReadMonotonicClockNanos().
- int64_t tsc; // From UnscaledCycleClock::Now().
-};
-
-// Returns a pair of values (monotonic kernel time, TSC ticks) that
-// approximately correspond to each other. This is accomplished by
-// doing several reads and picking the reading with the lowest
-// latency. This approach is used to minimize the probability that
-// our thread was preempted between clock reads.
-static TimeTscPair GetTimeTscPair() {
- int64_t best_latency = std::numeric_limits<int64_t>::max();
- TimeTscPair best;
- for (int i = 0; i < 10; ++i) {
- int64_t t0 = ReadMonotonicClockNanos();
- int64_t tsc = UnscaledCycleClockWrapperForInitializeFrequency::Now();
- int64_t t1 = ReadMonotonicClockNanos();
- int64_t latency = t1 - t0;
- if (latency < best_latency) {
- best_latency = latency;
- best.time = t0;
- best.tsc = tsc;
- }
- }
- return best;
-}
-
-// Measures and returns the TSC frequency by taking a pair of
-// measurements approximately `sleep_nanoseconds` apart.
-static double MeasureTscFrequencyWithSleep(int sleep_nanoseconds) {
- auto t0 = GetTimeTscPair();
- struct timespec ts;
- ts.tv_sec = 0;
- ts.tv_nsec = sleep_nanoseconds;
- while (nanosleep(&ts, &ts) != 0 && errno == EINTR) {}
- auto t1 = GetTimeTscPair();
- double elapsed_ticks = t1.tsc - t0.tsc;
- double elapsed_time = (t1.time - t0.time) * 1e-9;
- return elapsed_ticks / elapsed_time;
-}
-
-// Measures and returns the TSC frequency by calling
-// MeasureTscFrequencyWithSleep(), doubling the sleep interval until the
-// frequency measurement stabilizes.
-static double MeasureTscFrequency() {
- double last_measurement = -1.0;
- int sleep_nanoseconds = 1000000; // 1 millisecond.
- for (int i = 0; i < 8; ++i) {
- double measurement = MeasureTscFrequencyWithSleep(sleep_nanoseconds);
- if (measurement * 0.99 < last_measurement &&
- last_measurement < measurement * 1.01) {
- // Use the current measurement if it is within 1% of the
- // previous measurement.
- return measurement;
- }
- last_measurement = measurement;
- sleep_nanoseconds *= 2;
- }
- return last_measurement;
-}
-
-#endif // ABSL_INTERNAL_UNSCALED_CYCLECLOCK_FREQUENCY_IS_CPU_FREQUENCY
-
-static double GetNominalCPUFrequency() {
- long freq = 0;
-
- // Google's production kernel has a patch to export the TSC
- // frequency through sysfs. If the kernel is exporting the TSC
- // frequency use that. There are issues where cpuinfo_max_freq
- // cannot be relied on because the BIOS may be exporting an invalid
- // p-state (on x86) or p-states may be used to put the processor in
- // a new mode (turbo mode). Essentially, those frequencies cannot
- // always be relied upon. The same reasons apply to /proc/cpuinfo as
- // well.
- if (ReadLongFromFile("/sys/devices/system/cpu/cpu0/tsc_freq_khz", &freq)) {
- return freq * 1e3; // Value is kHz.
- }
-
-#if defined(ABSL_INTERNAL_UNSCALED_CYCLECLOCK_FREQUENCY_IS_CPU_FREQUENCY)
- // On these platforms, the TSC frequency is the nominal CPU
- // frequency. But without having the kernel export it directly
- // though /sys/devices/system/cpu/cpu0/tsc_freq_khz, there is no
- // other way to reliably get the TSC frequency, so we have to
- // measure it ourselves. Some CPUs abuse cpuinfo_max_freq by
- // exporting "fake" frequencies for implementing new features. For
- // example, Intel's turbo mode is enabled by exposing a p-state
- // value with a higher frequency than that of the real TSC
- // rate. Because of this, we prefer to measure the TSC rate
- // ourselves on i386 and x86-64.
- return MeasureTscFrequency();
-#else
-
- // If CPU scaling is in effect, we want to use the *maximum*
- // frequency, not whatever CPU speed some random processor happens
- // to be using now.
- if (ReadLongFromFile("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq",
- &freq)) {
- return freq * 1e3; // Value is kHz.
- }
-
- return 1.0;
-#endif // !ABSL_INTERNAL_UNSCALED_CYCLECLOCK_FREQUENCY_IS_CPU_FREQUENCY
-}
-
-#endif
-
-ABSL_CONST_INIT static once_flag init_num_cpus_once;
-ABSL_CONST_INIT static int num_cpus = 0;
-
-// NumCPUs() may be called before main() and before malloc is properly
-// initialized, therefore this must not allocate memory.
-int NumCPUs() {
- base_internal::LowLevelCallOnce(
- &init_num_cpus_once, []() { num_cpus = GetNumCPUs(); });
- return num_cpus;
-}
-
-// A default frequency of 0.0 might be dangerous if it is used in division.
-ABSL_CONST_INIT static once_flag init_nominal_cpu_frequency_once;
-ABSL_CONST_INIT static double nominal_cpu_frequency = 1.0;
-
-// NominalCPUFrequency() may be called before main() and before malloc is
-// properly initialized, therefore this must not allocate memory.
-double NominalCPUFrequency() {
- base_internal::LowLevelCallOnce(
- &init_nominal_cpu_frequency_once,
- []() { nominal_cpu_frequency = GetNominalCPUFrequency(); });
- return nominal_cpu_frequency;
-}
-
-#if defined(_WIN32)
-
-pid_t GetTID() {
- return pid_t{GetCurrentThreadId()};
-}
-
-#elif defined(__linux__)
-
-#ifndef SYS_gettid
-#define SYS_gettid __NR_gettid
-#endif
-
-pid_t GetTID() {
- return static_cast<pid_t>(syscall(SYS_gettid));
-}
-
-#elif defined(__akaros__)
-
-pid_t GetTID() {
- // Akaros has a concept of "vcore context", which is the state the program
- // is forced into when we need to make a user-level scheduling decision, or
- // run a signal handler. This is analogous to the interrupt context that a
- // CPU might enter if it encounters some kind of exception.
- //
- // There is no current thread context in vcore context, but we need to give
- // a reasonable answer if asked for a thread ID (e.g., in a signal handler).
- // Thread 0 always exists, so if we are in vcore context, we return that.
- //
- // Otherwise, we know (since we are using pthreads) that the uthread struct
- // current_uthread is pointing to is the first element of a
- // struct pthread_tcb, so we extract and return the thread ID from that.
- //
- // TODO(dcross): Akaros anticipates moving the thread ID to the uthread
- // structure at some point. We should modify this code to remove the cast
- // when that happens.
- if (in_vcore_context())
- return 0;
- return reinterpret_cast<struct pthread_tcb *>(current_uthread)->id;
-}
-
-#elif defined(__myriad2__)
-
-pid_t GetTID() {
- uint32_t tid;
- rtems_task_ident(RTEMS_SELF, 0, &tid);
- return tid;
-}
-
-#else
-
-// Fallback implementation of GetTID using pthread_getspecific.
-ABSL_CONST_INIT static once_flag tid_once;
-ABSL_CONST_INIT static pthread_key_t tid_key;
-ABSL_CONST_INIT static absl::base_internal::SpinLock tid_lock(
- absl::kConstInit, base_internal::SCHEDULE_KERNEL_ONLY);
-
-// We set a bit per thread in this array to indicate that an ID is in
-// use. ID 0 is unused because it is the default value returned by
-// pthread_getspecific().
-ABSL_CONST_INIT static std::vector<uint32_t> *tid_array
- ABSL_GUARDED_BY(tid_lock) = nullptr;
-static constexpr int kBitsPerWord = 32; // tid_array is uint32_t.
-
-// Returns the TID to tid_array.
-static void FreeTID(void *v) {
- intptr_t tid = reinterpret_cast<intptr_t>(v);
- intptr_t word = tid / kBitsPerWord;
- uint32_t mask = ~(1u << (tid % kBitsPerWord));
- absl::base_internal::SpinLockHolder lock(&tid_lock);
- assert(0 <= word && static_cast<size_t>(word) < tid_array->size());
- (*tid_array)[static_cast<size_t>(word)] &= mask;
-}
-
-static void InitGetTID() {
- if (pthread_key_create(&tid_key, FreeTID) != 0) {
- // The logging system calls GetTID() so it can't be used here.
- perror("pthread_key_create failed");
- abort();
- }
-
- // Initialize tid_array.
- absl::base_internal::SpinLockHolder lock(&tid_lock);
- tid_array = new std::vector<uint32_t>(1);
- (*tid_array)[0] = 1; // ID 0 is never-allocated.
-}
-
-// Return a per-thread small integer ID from pthread's thread-specific data.
-pid_t GetTID() {
- absl::call_once(tid_once, InitGetTID);
-
- intptr_t tid = reinterpret_cast<intptr_t>(pthread_getspecific(tid_key));
- if (tid != 0) {
- return static_cast<pid_t>(tid);
- }
-
- int bit; // tid_array[word] = 1u << bit;
- size_t word;
- {
- // Search for the first unused ID.
- absl::base_internal::SpinLockHolder lock(&tid_lock);
- // First search for a word in the array that is not all ones.
- word = 0;
- while (word < tid_array->size() && ~(*tid_array)[word] == 0) {
- ++word;
- }
- if (word == tid_array->size()) {
- tid_array->push_back(0); // No space left, add kBitsPerWord more IDs.
- }
- // Search for a zero bit in the word.
- bit = 0;
- while (bit < kBitsPerWord && (((*tid_array)[word] >> bit) & 1) != 0) {
- ++bit;
- }
- tid =
- static_cast<intptr_t>((word * kBitsPerWord) + static_cast<size_t>(bit));
- (*tid_array)[word] |= 1u << bit; // Mark the TID as allocated.
- }
-
- if (pthread_setspecific(tid_key, reinterpret_cast<void *>(tid)) != 0) {
- perror("pthread_setspecific failed");
- abort();
- }
-
- return static_cast<pid_t>(tid);
-}
-
-#endif
-
-// GetCachedTID() caches the thread ID in thread-local storage (which is a
-// userspace construct) to avoid unnecessary system calls. Without this caching,
-// it can take roughly 98ns, while it takes roughly 1ns with this caching.
-pid_t GetCachedTID() {
-#ifdef ABSL_HAVE_THREAD_LOCAL
- static thread_local pid_t thread_id = GetTID();
- return thread_id;
-#else
- return GetTID();
-#endif // ABSL_HAVE_THREAD_LOCAL
-}
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/base/internal/sysinfo.h b/third_party/abseil-cpp/absl/base/internal/sysinfo.h
deleted file mode 100644
index 119cf1f..0000000
--- a/third_party/abseil-cpp/absl/base/internal/sysinfo.h
+++ /dev/null
@@ -1,74 +0,0 @@
-// Copyright 2017 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.
-//
-// This file includes routines to find out characteristics
-// of the machine a program is running on. It is undoubtedly
-// system-dependent.
-
-// Functions listed here that accept a pid_t as an argument act on the
-// current process if the pid_t argument is 0
-// All functions here are thread-hostile due to file caching unless
-// commented otherwise.
-
-#ifndef ABSL_BASE_INTERNAL_SYSINFO_H_
-#define ABSL_BASE_INTERNAL_SYSINFO_H_
-
-#ifndef _WIN32
-#include <sys/types.h>
-#endif
-
-#include <cstdint>
-
-#include "absl/base/config.h"
-#include "absl/base/port.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-
-// Nominal core processor cycles per second of each processor. This is _not_
-// necessarily the frequency of the CycleClock counter (see cycleclock.h)
-// Thread-safe.
-double NominalCPUFrequency();
-
-// Number of logical processors (hyperthreads) in system. Thread-safe.
-int NumCPUs();
-
-// Return the thread id of the current thread, as told by the system.
-// No two currently-live threads implemented by the OS shall have the same ID.
-// Thread ids of exited threads may be reused. Multiple user-level threads
-// may have the same thread ID if multiplexed on the same OS thread.
-//
-// On Linux, you may send a signal to the resulting ID with kill(). However,
-// it is recommended for portability that you use pthread_kill() instead.
-#ifdef _WIN32
-// On Windows, process id and thread id are of the same type according to the
-// return types of GetProcessId() and GetThreadId() are both DWORD, an unsigned
-// 32-bit type.
-using pid_t = uint32_t;
-#endif
-pid_t GetTID();
-
-// Like GetTID(), but caches the result in thread-local storage in order
-// to avoid unnecessary system calls. Note that there are some cases where
-// one must call through to GetTID directly, which is why this exists as a
-// separate function. For example, GetCachedTID() is not safe to call in
-// an asynchronous signal-handling context nor right after a call to fork().
-pid_t GetCachedTID();
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_BASE_INTERNAL_SYSINFO_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/sysinfo_test.cc b/third_party/abseil-cpp/absl/base/internal/sysinfo_test.cc
deleted file mode 100644
index f305b6c..0000000
--- a/third_party/abseil-cpp/absl/base/internal/sysinfo_test.cc
+++ /dev/null
@@ -1,88 +0,0 @@
-// Copyright 2017 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/sysinfo.h"
-
-#ifndef _WIN32
-#include <sys/types.h>
-#include <unistd.h>
-#endif
-
-#include <thread> // NOLINT(build/c++11)
-#include <unordered_set>
-#include <vector>
-
-#include "gtest/gtest.h"
-#include "absl/synchronization/barrier.h"
-#include "absl/synchronization/mutex.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-namespace {
-
-TEST(SysinfoTest, NumCPUs) {
- EXPECT_NE(NumCPUs(), 0)
- << "NumCPUs() should not have the default value of 0";
-}
-
-TEST(SysinfoTest, GetTID) {
- EXPECT_EQ(GetTID(), GetTID()); // Basic compile and equality test.
-#ifdef __native_client__
- // Native Client has a race condition bug that leads to memory
- // exaustion when repeatedly creating and joining threads.
- // https://bugs.chromium.org/p/nativeclient/issues/detail?id=1027
- return;
-#endif
- // Test that TIDs are unique to each thread.
- // Uses a few loops to exercise implementations that reallocate IDs.
- for (int i = 0; i < 10; ++i) {
- constexpr int kNumThreads = 10;
- Barrier all_threads_done(kNumThreads);
- std::vector<std::thread> threads;
-
- Mutex mutex;
- std::unordered_set<pid_t> tids;
-
- for (int j = 0; j < kNumThreads; ++j) {
- threads.push_back(std::thread([&]() {
- pid_t id = GetTID();
- {
- MutexLock lock(&mutex);
- ASSERT_TRUE(tids.find(id) == tids.end());
- tids.insert(id);
- }
- // We can't simply join the threads here. The threads need to
- // be alive otherwise the TID might have been reallocated to
- // another live thread.
- all_threads_done.Block();
- }));
- }
- for (auto& thread : threads) {
- thread.join();
- }
- }
-}
-
-#ifdef __linux__
-TEST(SysinfoTest, LinuxGetTID) {
- // On Linux, for the main thread, GetTID()==getpid() is guaranteed by the API.
- EXPECT_EQ(GetTID(), getpid());
-}
-#endif
-
-} // namespace
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/base/internal/thread_identity.cc b/third_party/abseil-cpp/absl/base/internal/thread_identity.cc
deleted file mode 100644
index 79853f0..0000000
--- a/third_party/abseil-cpp/absl/base/internal/thread_identity.cc
+++ /dev/null
@@ -1,156 +0,0 @@
-// Copyright 2017 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/thread_identity.h"
-
-#if !defined(_WIN32) || defined(__MINGW32__)
-#include <pthread.h>
-#include <signal.h>
-#endif
-
-#include <atomic>
-#include <cassert>
-#include <memory>
-
-#include "absl/base/attributes.h"
-#include "absl/base/call_once.h"
-#include "absl/base/internal/raw_logging.h"
-#include "absl/base/internal/spinlock.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-
-#if ABSL_THREAD_IDENTITY_MODE != ABSL_THREAD_IDENTITY_MODE_USE_CPP11
-namespace {
-// Used to co-ordinate one-time creation of our pthread_key
-absl::once_flag init_thread_identity_key_once;
-pthread_key_t thread_identity_pthread_key;
-std::atomic<bool> pthread_key_initialized(false);
-
-void AllocateThreadIdentityKey(ThreadIdentityReclaimerFunction reclaimer) {
- pthread_key_create(&thread_identity_pthread_key, reclaimer);
- pthread_key_initialized.store(true, std::memory_order_release);
-}
-} // namespace
-#endif
-
-#if ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_TLS || \
- ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_CPP11
-// The actual TLS storage for a thread's currently associated ThreadIdentity.
-// This is referenced by inline accessors in the header.
-// "protected" visibility ensures that if multiple instances of Abseil code
-// exist within a process (via dlopen() or similar), references to
-// thread_identity_ptr from each instance of the code will refer to
-// *different* instances of this ptr.
-// Apple platforms have the visibility attribute, but issue a compile warning
-// that protected visibility is unsupported.
-ABSL_CONST_INIT // Must come before __attribute__((visibility("protected")))
-#if ABSL_HAVE_ATTRIBUTE(visibility) && !defined(__APPLE__)
-__attribute__((visibility("protected")))
-#endif // ABSL_HAVE_ATTRIBUTE(visibility) && !defined(__APPLE__)
-#if ABSL_PER_THREAD_TLS
-// Prefer __thread to thread_local as benchmarks indicate it is a bit faster.
-ABSL_PER_THREAD_TLS_KEYWORD ThreadIdentity* thread_identity_ptr = nullptr;
-#elif defined(ABSL_HAVE_THREAD_LOCAL)
-thread_local ThreadIdentity* thread_identity_ptr = nullptr;
-#endif // ABSL_PER_THREAD_TLS
-#endif // TLS or CPP11
-
-void SetCurrentThreadIdentity(
- ThreadIdentity* identity, ThreadIdentityReclaimerFunction reclaimer) {
- assert(CurrentThreadIdentityIfPresent() == nullptr);
- // Associate our destructor.
- // NOTE: This call to pthread_setspecific is currently the only immovable
- // barrier to CurrentThreadIdentity() always being async signal safe.
-#if ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC
- // NOTE: Not async-safe. But can be open-coded.
- absl::call_once(init_thread_identity_key_once, AllocateThreadIdentityKey,
- reclaimer);
-
-#if defined(__EMSCRIPTEN__) || defined(__MINGW32__)
- // Emscripten and MinGW pthread implementations does not support signals.
- // See https://kripken.github.io/emscripten-site/docs/porting/pthreads.html
- // for more information.
- pthread_setspecific(thread_identity_pthread_key,
- reinterpret_cast<void*>(identity));
-#else
- // We must mask signals around the call to setspecific as with current glibc,
- // a concurrent getspecific (needed for GetCurrentThreadIdentityIfPresent())
- // may zero our value.
- //
- // While not officially async-signal safe, getspecific within a signal handler
- // is otherwise OK.
- sigset_t all_signals;
- sigset_t curr_signals;
- sigfillset(&all_signals);
- pthread_sigmask(SIG_SETMASK, &all_signals, &curr_signals);
- pthread_setspecific(thread_identity_pthread_key,
- reinterpret_cast<void*>(identity));
- pthread_sigmask(SIG_SETMASK, &curr_signals, nullptr);
-#endif // !__EMSCRIPTEN__ && !__MINGW32__
-
-#elif ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_TLS
- // NOTE: Not async-safe. But can be open-coded.
- absl::call_once(init_thread_identity_key_once, AllocateThreadIdentityKey,
- reclaimer);
- pthread_setspecific(thread_identity_pthread_key,
- reinterpret_cast<void*>(identity));
- thread_identity_ptr = identity;
-#elif ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_CPP11
- thread_local std::unique_ptr<ThreadIdentity, ThreadIdentityReclaimerFunction>
- holder(identity, reclaimer);
- thread_identity_ptr = identity;
-#else
-#error Unimplemented ABSL_THREAD_IDENTITY_MODE
-#endif
-}
-
-#if ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_TLS || \
- ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_CPP11
-
-// Please see the comment on `CurrentThreadIdentityIfPresent` in
-// thread_identity.h. When we cannot expose thread_local variables in
-// headers, we opt for the correct-but-slower option of not inlining this
-// function.
-#ifndef ABSL_INTERNAL_INLINE_CURRENT_THREAD_IDENTITY_IF_PRESENT
-ThreadIdentity* CurrentThreadIdentityIfPresent() { return thread_identity_ptr; }
-#endif
-#endif
-
-void ClearCurrentThreadIdentity() {
-#if ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_TLS || \
- ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_CPP11
- thread_identity_ptr = nullptr;
-#elif ABSL_THREAD_IDENTITY_MODE == \
- ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC
- // pthread_setspecific expected to clear value on destruction
- assert(CurrentThreadIdentityIfPresent() == nullptr);
-#endif
-}
-
-#if ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC
-ThreadIdentity* CurrentThreadIdentityIfPresent() {
- bool initialized = pthread_key_initialized.load(std::memory_order_acquire);
- if (!initialized) {
- return nullptr;
- }
- return reinterpret_cast<ThreadIdentity*>(
- pthread_getspecific(thread_identity_pthread_key));
-}
-#endif
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/base/internal/thread_identity.h b/third_party/abseil-cpp/absl/base/internal/thread_identity.h
deleted file mode 100644
index 659694b..0000000
--- a/third_party/abseil-cpp/absl/base/internal/thread_identity.h
+++ /dev/null
@@ -1,265 +0,0 @@
-// Copyright 2017 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.
-//
-// Each active thread has an ThreadIdentity that may represent the thread in
-// various level interfaces. ThreadIdentity objects are never deallocated.
-// When a thread terminates, its ThreadIdentity object may be reused for a
-// thread created later.
-
-#ifndef ABSL_BASE_INTERNAL_THREAD_IDENTITY_H_
-#define ABSL_BASE_INTERNAL_THREAD_IDENTITY_H_
-
-#ifndef _WIN32
-#include <pthread.h>
-// Defines __GOOGLE_GRTE_VERSION__ (via glibc-specific features.h) when
-// supported.
-#include <unistd.h>
-#endif
-
-#include <atomic>
-#include <cstdint>
-
-#include "absl/base/config.h"
-#include "absl/base/internal/per_thread_tls.h"
-#include "absl/base/optimization.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-
-struct SynchLocksHeld;
-struct SynchWaitParams;
-
-namespace base_internal {
-
-class SpinLock;
-struct ThreadIdentity;
-
-// Used by the implementation of absl::Mutex and absl::CondVar.
-struct PerThreadSynch {
- // The internal representation of absl::Mutex and absl::CondVar rely
- // on the alignment of PerThreadSynch. Both store the address of the
- // PerThreadSynch in the high-order bits of their internal state,
- // which means the low kLowZeroBits of the address of PerThreadSynch
- // must be zero.
- static constexpr int kLowZeroBits = 8;
- static constexpr int kAlignment = 1 << kLowZeroBits;
-
- // Returns the associated ThreadIdentity.
- // This can be implemented as a cast because we guarantee
- // PerThreadSynch is the first element of ThreadIdentity.
- ThreadIdentity* thread_identity() {
- return reinterpret_cast<ThreadIdentity*>(this);
- }
-
- PerThreadSynch *next; // Circular waiter queue; initialized to 0.
- PerThreadSynch *skip; // If non-zero, all entries in Mutex queue
- // up to and including "skip" have same
- // condition as this, and will be woken later
- bool may_skip; // if false while on mutex queue, a mutex unlocker
- // is using this PerThreadSynch as a terminator. Its
- // skip field must not be filled in because the loop
- // might then skip over the terminator.
- bool wake; // This thread is to be woken from a Mutex.
- // If "x" is on a waiter list for a mutex, "x->cond_waiter" is true iff the
- // waiter is waiting on the mutex as part of a CV Wait or Mutex Await.
- //
- // The value of "x->cond_waiter" is meaningless if "x" is not on a
- // Mutex waiter list.
- bool cond_waiter;
- bool maybe_unlocking; // Valid at head of Mutex waiter queue;
- // true if UnlockSlow could be searching
- // for a waiter to wake. Used for an optimization
- // in Enqueue(). true is always a valid value.
- // Can be reset to false when the unlocker or any
- // writer releases the lock, or a reader fully
- // releases the lock. It may not be set to false
- // by a reader that decrements the count to
- // non-zero. protected by mutex spinlock
- bool suppress_fatal_errors; // If true, try to proceed even in the face
- // of broken invariants. This is used within
- // fatal signal handlers to improve the
- // chances of debug logging information being
- // output successfully.
- int priority; // Priority of thread (updated every so often).
-
- // State values:
- // kAvailable: This PerThreadSynch is available.
- // kQueued: This PerThreadSynch is unavailable, it's currently queued on a
- // Mutex or CondVar waistlist.
- //
- // Transitions from kQueued to kAvailable require a release
- // barrier. This is needed as a waiter may use "state" to
- // independently observe that it's no longer queued.
- //
- // Transitions from kAvailable to kQueued require no barrier, they
- // are externally ordered by the Mutex.
- enum State {
- kAvailable,
- kQueued
- };
- std::atomic<State> state;
-
- // The wait parameters of the current wait. waitp is null if the
- // thread is not waiting. Transitions from null to non-null must
- // occur before the enqueue commit point (state = kQueued in
- // Enqueue() and CondVarEnqueue()). Transitions from non-null to
- // null must occur after the wait is finished (state = kAvailable in
- // Mutex::Block() and CondVar::WaitCommon()). This field may be
- // changed only by the thread that describes this PerThreadSynch. A
- // special case is Fer(), which calls Enqueue() on another thread,
- // but with an identical SynchWaitParams pointer, thus leaving the
- // pointer unchanged.
- SynchWaitParams* waitp;
-
- intptr_t readers; // Number of readers in mutex.
-
- // When priority will next be read (cycles).
- int64_t next_priority_read_cycles;
-
- // Locks held; used during deadlock detection.
- // Allocated in Synch_GetAllLocks() and freed in ReclaimThreadIdentity().
- SynchLocksHeld *all_locks;
-};
-
-// The instances of this class are allocated in NewThreadIdentity() with an
-// alignment of PerThreadSynch::kAlignment.
-struct ThreadIdentity {
- // Must be the first member. The Mutex implementation requires that
- // the PerThreadSynch object associated with each thread is
- // PerThreadSynch::kAlignment aligned. We provide this alignment on
- // ThreadIdentity itself.
- PerThreadSynch per_thread_synch;
-
- // Private: Reserved for absl::synchronization_internal::Waiter.
- struct WaiterState {
- alignas(void*) char data[128];
- } waiter_state;
-
- // Used by PerThreadSem::{Get,Set}ThreadBlockedCounter().
- std::atomic<int>* blocked_count_ptr;
-
- // The following variables are mostly read/written just by the
- // thread itself. The only exception is that these are read by
- // a ticker thread as a hint.
- std::atomic<int> ticker; // Tick counter, incremented once per second.
- std::atomic<int> wait_start; // Ticker value when thread started waiting.
- std::atomic<bool> is_idle; // Has thread become idle yet?
-
- ThreadIdentity* next;
-};
-
-// Returns the ThreadIdentity object representing the calling thread; guaranteed
-// to be unique for its lifetime. The returned object will remain valid for the
-// program's lifetime; although it may be re-assigned to a subsequent thread.
-// If one does not exist, return nullptr instead.
-//
-// Does not malloc(*), and is async-signal safe.
-// [*] Technically pthread_setspecific() does malloc on first use; however this
-// is handled internally within tcmalloc's initialization already.
-//
-// New ThreadIdentity objects can be constructed and associated with a thread
-// by calling GetOrCreateCurrentThreadIdentity() in per-thread-sem.h.
-ThreadIdentity* CurrentThreadIdentityIfPresent();
-
-using ThreadIdentityReclaimerFunction = void (*)(void*);
-
-// Sets the current thread identity to the given value. 'reclaimer' is a
-// pointer to the global function for cleaning up instances on thread
-// destruction.
-void SetCurrentThreadIdentity(ThreadIdentity* identity,
- ThreadIdentityReclaimerFunction reclaimer);
-
-// Removes the currently associated ThreadIdentity from the running thread.
-// This must be called from inside the ThreadIdentityReclaimerFunction, and only
-// from that function.
-void ClearCurrentThreadIdentity();
-
-// May be chosen at compile time via: -DABSL_FORCE_THREAD_IDENTITY_MODE=<mode
-// index>
-#ifdef ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC
-#error ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC cannot be directly set
-#else
-#define ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC 0
-#endif
-
-#ifdef ABSL_THREAD_IDENTITY_MODE_USE_TLS
-#error ABSL_THREAD_IDENTITY_MODE_USE_TLS cannot be directly set
-#else
-#define ABSL_THREAD_IDENTITY_MODE_USE_TLS 1
-#endif
-
-#ifdef ABSL_THREAD_IDENTITY_MODE_USE_CPP11
-#error ABSL_THREAD_IDENTITY_MODE_USE_CPP11 cannot be directly set
-#else
-#define ABSL_THREAD_IDENTITY_MODE_USE_CPP11 2
-#endif
-
-#ifdef ABSL_THREAD_IDENTITY_MODE
-#error ABSL_THREAD_IDENTITY_MODE cannot be directly set
-#elif defined(ABSL_FORCE_THREAD_IDENTITY_MODE)
-#define ABSL_THREAD_IDENTITY_MODE ABSL_FORCE_THREAD_IDENTITY_MODE
-#elif defined(_WIN32) && !defined(__MINGW32__)
-#define ABSL_THREAD_IDENTITY_MODE ABSL_THREAD_IDENTITY_MODE_USE_CPP11
-#elif defined(__APPLE__) && defined(ABSL_HAVE_THREAD_LOCAL)
-#define ABSL_THREAD_IDENTITY_MODE ABSL_THREAD_IDENTITY_MODE_USE_CPP11
-#elif ABSL_PER_THREAD_TLS && defined(__GOOGLE_GRTE_VERSION__) && \
- (__GOOGLE_GRTE_VERSION__ >= 20140228L)
-// Support for async-safe TLS was specifically added in GRTEv4. It's not
-// present in the upstream eglibc.
-// Note: Current default for production systems.
-#define ABSL_THREAD_IDENTITY_MODE ABSL_THREAD_IDENTITY_MODE_USE_TLS
-#else
-#define ABSL_THREAD_IDENTITY_MODE \
- ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC
-#endif
-
-#if ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_TLS || \
- ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_CPP11
-
-#if ABSL_PER_THREAD_TLS
-ABSL_CONST_INIT extern ABSL_PER_THREAD_TLS_KEYWORD ThreadIdentity*
- thread_identity_ptr;
-#elif defined(ABSL_HAVE_THREAD_LOCAL)
-ABSL_CONST_INIT extern thread_local ThreadIdentity* thread_identity_ptr;
-#else
-#error Thread-local storage not detected on this platform
-#endif
-
-// thread_local variables cannot be in headers exposed by DLLs or in certain
-// build configurations on Apple platforms. However, it is important for
-// performance reasons in general that `CurrentThreadIdentityIfPresent` be
-// inlined. In the other cases we opt to have the function not be inlined. Note
-// that `CurrentThreadIdentityIfPresent` is declared above so we can exclude
-// this entire inline definition.
-#if !defined(__APPLE__) && !defined(ABSL_BUILD_DLL) && \
- !defined(ABSL_CONSUME_DLL)
-#define ABSL_INTERNAL_INLINE_CURRENT_THREAD_IDENTITY_IF_PRESENT 1
-#endif
-
-#ifdef ABSL_INTERNAL_INLINE_CURRENT_THREAD_IDENTITY_IF_PRESENT
-inline ThreadIdentity* CurrentThreadIdentityIfPresent() {
- return thread_identity_ptr;
-}
-#endif
-
-#elif ABSL_THREAD_IDENTITY_MODE != \
- ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC
-#error Unknown ABSL_THREAD_IDENTITY_MODE
-#endif
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_BASE_INTERNAL_THREAD_IDENTITY_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/thread_identity_benchmark.cc b/third_party/abseil-cpp/absl/base/internal/thread_identity_benchmark.cc
deleted file mode 100644
index 0ae10f2..0000000
--- a/third_party/abseil-cpp/absl/base/internal/thread_identity_benchmark.cc
+++ /dev/null
@@ -1,38 +0,0 @@
-// Copyright 2017 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 "benchmark/benchmark.h"
-#include "absl/base/internal/thread_identity.h"
-#include "absl/synchronization/internal/create_thread_identity.h"
-#include "absl/synchronization/internal/per_thread_sem.h"
-
-namespace {
-
-void BM_SafeCurrentThreadIdentity(benchmark::State& state) {
- for (auto _ : state) {
- benchmark::DoNotOptimize(
- absl::synchronization_internal::GetOrCreateCurrentThreadIdentity());
- }
-}
-BENCHMARK(BM_SafeCurrentThreadIdentity);
-
-void BM_UnsafeCurrentThreadIdentity(benchmark::State& state) {
- for (auto _ : state) {
- benchmark::DoNotOptimize(
- absl::base_internal::CurrentThreadIdentityIfPresent());
- }
-}
-BENCHMARK(BM_UnsafeCurrentThreadIdentity);
-
-} // namespace
diff --git a/third_party/abseil-cpp/absl/base/internal/thread_identity_test.cc b/third_party/abseil-cpp/absl/base/internal/thread_identity_test.cc
deleted file mode 100644
index 46a6f74..0000000
--- a/third_party/abseil-cpp/absl/base/internal/thread_identity_test.cc
+++ /dev/null
@@ -1,129 +0,0 @@
-// Copyright 2017 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/thread_identity.h"
-
-#include <thread> // NOLINT(build/c++11)
-#include <vector>
-
-#include "gtest/gtest.h"
-#include "absl/base/attributes.h"
-#include "absl/base/internal/spinlock.h"
-#include "absl/base/macros.h"
-#include "absl/base/thread_annotations.h"
-#include "absl/synchronization/internal/per_thread_sem.h"
-#include "absl/synchronization/mutex.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-namespace {
-
-ABSL_CONST_INIT static absl::base_internal::SpinLock map_lock(
- absl::kConstInit, base_internal::SCHEDULE_KERNEL_ONLY);
-ABSL_CONST_INIT static int num_identities_reused ABSL_GUARDED_BY(map_lock);
-
-static const void* const kCheckNoIdentity = reinterpret_cast<void*>(1);
-
-static void TestThreadIdentityCurrent(const void* assert_no_identity) {
- ThreadIdentity* identity;
-
- // We have to test this conditionally, because if the test framework relies
- // on Abseil, then some previous action may have already allocated an
- // identity.
- if (assert_no_identity == kCheckNoIdentity) {
- identity = CurrentThreadIdentityIfPresent();
- EXPECT_TRUE(identity == nullptr);
- }
-
- identity = synchronization_internal::GetOrCreateCurrentThreadIdentity();
- EXPECT_TRUE(identity != nullptr);
- ThreadIdentity* identity_no_init;
- identity_no_init = CurrentThreadIdentityIfPresent();
- EXPECT_TRUE(identity == identity_no_init);
-
- // Check that per_thread_synch is correctly aligned.
- EXPECT_EQ(0, reinterpret_cast<intptr_t>(&identity->per_thread_synch) %
- PerThreadSynch::kAlignment);
- EXPECT_EQ(identity, identity->per_thread_synch.thread_identity());
-
- absl::base_internal::SpinLockHolder l(&map_lock);
- num_identities_reused++;
-}
-
-TEST(ThreadIdentityTest, BasicIdentityWorks) {
- // This tests for the main() thread.
- TestThreadIdentityCurrent(nullptr);
-}
-
-TEST(ThreadIdentityTest, BasicIdentityWorksThreaded) {
- // Now try the same basic test with multiple threads being created and
- // destroyed. This makes sure that:
- // - New threads are created without a ThreadIdentity.
- // - We re-allocate ThreadIdentity objects from the free-list.
- // - If a thread implementation chooses to recycle threads, that
- // correct re-initialization occurs.
- static const int kNumLoops = 3;
- static const int kNumThreads = 32;
- for (int iter = 0; iter < kNumLoops; iter++) {
- std::vector<std::thread> threads;
- for (int i = 0; i < kNumThreads; ++i) {
- threads.push_back(
- std::thread(TestThreadIdentityCurrent, kCheckNoIdentity));
- }
- for (auto& thread : threads) {
- thread.join();
- }
- }
-
- // We should have recycled ThreadIdentity objects above; while (external)
- // library threads allocating their own identities may preclude some
- // reuse, we should have sufficient repetitions to exclude this.
- absl::base_internal::SpinLockHolder l(&map_lock);
- EXPECT_LT(kNumThreads, num_identities_reused);
-}
-
-TEST(ThreadIdentityTest, ReusedThreadIdentityMutexTest) {
- // This test repeatly creates and joins a series of threads, each of
- // which acquires and releases shared Mutex locks. This verifies
- // Mutex operations work correctly under a reused
- // ThreadIdentity. Note that the most likely failure mode of this
- // test is a crash or deadlock.
- static const int kNumLoops = 10;
- static const int kNumThreads = 12;
- static const int kNumMutexes = 3;
- static const int kNumLockLoops = 5;
-
- Mutex mutexes[kNumMutexes];
- for (int iter = 0; iter < kNumLoops; ++iter) {
- std::vector<std::thread> threads;
- for (int thread = 0; thread < kNumThreads; ++thread) {
- threads.push_back(std::thread([&]() {
- for (int l = 0; l < kNumLockLoops; ++l) {
- for (int m = 0; m < kNumMutexes; ++m) {
- MutexLock lock(&mutexes[m]);
- }
- }
- }));
- }
- for (auto& thread : threads) {
- thread.join();
- }
- }
-}
-
-} // namespace
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/base/internal/throw_delegate.cc b/third_party/abseil-cpp/absl/base/internal/throw_delegate.cc
deleted file mode 100644
index c260ff1..0000000
--- a/third_party/abseil-cpp/absl/base/internal/throw_delegate.cc
+++ /dev/null
@@ -1,212 +0,0 @@
-// Copyright 2017 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/throw_delegate.h"
-
-#include <cstdlib>
-#include <functional>
-#include <new>
-#include <stdexcept>
-
-#include "absl/base/config.h"
-#include "absl/base/internal/raw_logging.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-
-// NOTE: The various STL exception throwing functions are placed within the
-// #ifdef blocks so the symbols aren't exposed on platforms that don't support
-// them, such as the Android NDK. For example, ANGLE fails to link when building
-// within AOSP without them, since the STL functions don't exist.
-namespace {
-#ifdef ABSL_HAVE_EXCEPTIONS
-template <typename T>
-[[noreturn]] void Throw(const T& error) {
- throw error;
-}
-#endif
-} // namespace
-
-void ThrowStdLogicError(const std::string& what_arg) {
-#ifdef ABSL_HAVE_EXCEPTIONS
- Throw(std::logic_error(what_arg));
-#else
- ABSL_RAW_LOG(FATAL, "%s", what_arg.c_str());
- std::abort();
-#endif
-}
-void ThrowStdLogicError(const char* what_arg) {
-#ifdef ABSL_HAVE_EXCEPTIONS
- Throw(std::logic_error(what_arg));
-#else
- ABSL_RAW_LOG(FATAL, "%s", what_arg);
- std::abort();
-#endif
-}
-void ThrowStdInvalidArgument(const std::string& what_arg) {
-#ifdef ABSL_HAVE_EXCEPTIONS
- Throw(std::invalid_argument(what_arg));
-#else
- ABSL_RAW_LOG(FATAL, "%s", what_arg.c_str());
- std::abort();
-#endif
-}
-void ThrowStdInvalidArgument(const char* what_arg) {
-#ifdef ABSL_HAVE_EXCEPTIONS
- Throw(std::invalid_argument(what_arg));
-#else
- ABSL_RAW_LOG(FATAL, "%s", what_arg);
- std::abort();
-#endif
-}
-
-void ThrowStdDomainError(const std::string& what_arg) {
-#ifdef ABSL_HAVE_EXCEPTIONS
- Throw(std::domain_error(what_arg));
-#else
- ABSL_RAW_LOG(FATAL, "%s", what_arg.c_str());
- std::abort();
-#endif
-}
-void ThrowStdDomainError(const char* what_arg) {
-#ifdef ABSL_HAVE_EXCEPTIONS
- Throw(std::domain_error(what_arg));
-#else
- ABSL_RAW_LOG(FATAL, "%s", what_arg);
- std::abort();
-#endif
-}
-
-void ThrowStdLengthError(const std::string& what_arg) {
-#ifdef ABSL_HAVE_EXCEPTIONS
- Throw(std::length_error(what_arg));
-#else
- ABSL_RAW_LOG(FATAL, "%s", what_arg.c_str());
- std::abort();
-#endif
-}
-void ThrowStdLengthError(const char* what_arg) {
-#ifdef ABSL_HAVE_EXCEPTIONS
- Throw(std::length_error(what_arg));
-#else
- ABSL_RAW_LOG(FATAL, "%s", what_arg);
- std::abort();
-#endif
-}
-
-void ThrowStdOutOfRange(const std::string& what_arg) {
-#ifdef ABSL_HAVE_EXCEPTIONS
- Throw(std::out_of_range(what_arg));
-#else
- ABSL_RAW_LOG(FATAL, "%s", what_arg.c_str());
- std::abort();
-#endif
-}
-void ThrowStdOutOfRange(const char* what_arg) {
-#ifdef ABSL_HAVE_EXCEPTIONS
- Throw(std::out_of_range(what_arg));
-#else
- ABSL_RAW_LOG(FATAL, "%s", what_arg);
- std::abort();
-#endif
-}
-
-void ThrowStdRuntimeError(const std::string& what_arg) {
-#ifdef ABSL_HAVE_EXCEPTIONS
- Throw(std::runtime_error(what_arg));
-#else
- ABSL_RAW_LOG(FATAL, "%s", what_arg.c_str());
- std::abort();
-#endif
-}
-void ThrowStdRuntimeError(const char* what_arg) {
-#ifdef ABSL_HAVE_EXCEPTIONS
- Throw(std::runtime_error(what_arg));
-#else
- ABSL_RAW_LOG(FATAL, "%s", what_arg);
- std::abort();
-#endif
-}
-
-void ThrowStdRangeError(const std::string& what_arg) {
-#ifdef ABSL_HAVE_EXCEPTIONS
- Throw(std::range_error(what_arg));
-#else
- ABSL_RAW_LOG(FATAL, "%s", what_arg.c_str());
- std::abort();
-#endif
-}
-void ThrowStdRangeError(const char* what_arg) {
-#ifdef ABSL_HAVE_EXCEPTIONS
- Throw(std::range_error(what_arg));
-#else
- ABSL_RAW_LOG(FATAL, "%s", what_arg);
- std::abort();
-#endif
-}
-
-void ThrowStdOverflowError(const std::string& what_arg) {
-#ifdef ABSL_HAVE_EXCEPTIONS
- Throw(std::overflow_error(what_arg));
-#else
- ABSL_RAW_LOG(FATAL, "%s", what_arg.c_str());
- std::abort();
-#endif
-}
-void ThrowStdOverflowError(const char* what_arg) {
-#ifdef ABSL_HAVE_EXCEPTIONS
- Throw(std::overflow_error(what_arg));
-#else
- ABSL_RAW_LOG(FATAL, "%s", what_arg);
- std::abort();
-#endif
-}
-
-void ThrowStdUnderflowError(const std::string& what_arg) {
-#ifdef ABSL_HAVE_EXCEPTIONS
- Throw(std::underflow_error(what_arg));
-#else
- ABSL_RAW_LOG(FATAL, "%s", what_arg.c_str());
- std::abort();
-#endif
-}
-void ThrowStdUnderflowError(const char* what_arg) {
-#ifdef ABSL_HAVE_EXCEPTIONS
- Throw(std::underflow_error(what_arg));
-#else
- ABSL_RAW_LOG(FATAL, "%s", what_arg);
- std::abort();
-#endif
-}
-
-void ThrowStdBadFunctionCall() {
-#ifdef ABSL_HAVE_EXCEPTIONS
- Throw(std::bad_function_call());
-#else
- std::abort();
-#endif
-}
-
-void ThrowStdBadAlloc() {
-#ifdef ABSL_HAVE_EXCEPTIONS
- Throw(std::bad_alloc());
-#else
- std::abort();
-#endif
-}
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/base/internal/throw_delegate.h b/third_party/abseil-cpp/absl/base/internal/throw_delegate.h
deleted file mode 100644
index 075f527..0000000
--- a/third_party/abseil-cpp/absl/base/internal/throw_delegate.h
+++ /dev/null
@@ -1,75 +0,0 @@
-//
-// Copyright 2017 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_THROW_DELEGATE_H_
-#define ABSL_BASE_INTERNAL_THROW_DELEGATE_H_
-
-#include <string>
-
-#include "absl/base/config.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-
-// Helper functions that allow throwing exceptions consistently from anywhere.
-// The main use case is for header-based libraries (eg templates), as they will
-// be built by many different targets with their own compiler options.
-// In particular, this will allow a safe way to throw exceptions even if the
-// caller is compiled with -fno-exceptions. This is intended for implementing
-// things like map<>::at(), which the standard documents as throwing an
-// exception on error.
-//
-// Using other techniques like #if tricks could lead to ODR violations.
-//
-// You shouldn't use it unless you're writing code that you know will be built
-// both with and without exceptions and you need to conform to an interface
-// that uses exceptions.
-
-[[noreturn]] void ThrowStdLogicError(const std::string& what_arg);
-[[noreturn]] void ThrowStdLogicError(const char* what_arg);
-[[noreturn]] void ThrowStdInvalidArgument(const std::string& what_arg);
-[[noreturn]] void ThrowStdInvalidArgument(const char* what_arg);
-[[noreturn]] void ThrowStdDomainError(const std::string& what_arg);
-[[noreturn]] void ThrowStdDomainError(const char* what_arg);
-[[noreturn]] void ThrowStdLengthError(const std::string& what_arg);
-[[noreturn]] void ThrowStdLengthError(const char* what_arg);
-[[noreturn]] void ThrowStdOutOfRange(const std::string& what_arg);
-[[noreturn]] void ThrowStdOutOfRange(const char* what_arg);
-[[noreturn]] void ThrowStdRuntimeError(const std::string& what_arg);
-[[noreturn]] void ThrowStdRuntimeError(const char* what_arg);
-[[noreturn]] void ThrowStdRangeError(const std::string& what_arg);
-[[noreturn]] void ThrowStdRangeError(const char* what_arg);
-[[noreturn]] void ThrowStdOverflowError(const std::string& what_arg);
-[[noreturn]] void ThrowStdOverflowError(const char* what_arg);
-[[noreturn]] void ThrowStdUnderflowError(const std::string& what_arg);
-[[noreturn]] void ThrowStdUnderflowError(const char* what_arg);
-
-[[noreturn]] void ThrowStdBadFunctionCall();
-[[noreturn]] void ThrowStdBadAlloc();
-
-// ThrowStdBadArrayNewLength() cannot be consistently supported because
-// std::bad_array_new_length is missing in libstdc++ until 4.9.0.
-// https://gcc.gnu.org/onlinedocs/gcc-4.8.3/libstdc++/api/a01379_source.html
-// https://gcc.gnu.org/onlinedocs/gcc-4.9.0/libstdc++/api/a01327_source.html
-// libcxx (as of 3.2) and msvc (as of 2015) both have it.
-// [[noreturn]] void ThrowStdBadArrayNewLength();
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_BASE_INTERNAL_THROW_DELEGATE_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/tsan_mutex_interface.h b/third_party/abseil-cpp/absl/base/internal/tsan_mutex_interface.h
deleted file mode 100644
index 39207d8..0000000
--- a/third_party/abseil-cpp/absl/base/internal/tsan_mutex_interface.h
+++ /dev/null
@@ -1,68 +0,0 @@
-// Copyright 2017 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.
-//
-// This file is intended solely for spinlock.h.
-// It provides ThreadSanitizer annotations for custom mutexes.
-// See <sanitizer/tsan_interface.h> for meaning of these annotations.
-
-#ifndef ABSL_BASE_INTERNAL_TSAN_MUTEX_INTERFACE_H_
-#define ABSL_BASE_INTERNAL_TSAN_MUTEX_INTERFACE_H_
-
-#include "absl/base/config.h"
-
-// ABSL_INTERNAL_HAVE_TSAN_INTERFACE
-// Macro intended only for internal use.
-//
-// Checks whether LLVM Thread Sanitizer interfaces are available.
-// First made available in LLVM 5.0 (Sep 2017).
-#ifdef ABSL_INTERNAL_HAVE_TSAN_INTERFACE
-#error "ABSL_INTERNAL_HAVE_TSAN_INTERFACE cannot be directly set."
-#endif
-
-#if defined(ABSL_HAVE_THREAD_SANITIZER) && defined(__has_include)
-#if __has_include(<sanitizer/tsan_interface.h>)
-#define ABSL_INTERNAL_HAVE_TSAN_INTERFACE 1
-#endif
-#endif
-
-#ifdef ABSL_INTERNAL_HAVE_TSAN_INTERFACE
-#include <sanitizer/tsan_interface.h>
-
-#define ABSL_TSAN_MUTEX_CREATE __tsan_mutex_create
-#define ABSL_TSAN_MUTEX_DESTROY __tsan_mutex_destroy
-#define ABSL_TSAN_MUTEX_PRE_LOCK __tsan_mutex_pre_lock
-#define ABSL_TSAN_MUTEX_POST_LOCK __tsan_mutex_post_lock
-#define ABSL_TSAN_MUTEX_PRE_UNLOCK __tsan_mutex_pre_unlock
-#define ABSL_TSAN_MUTEX_POST_UNLOCK __tsan_mutex_post_unlock
-#define ABSL_TSAN_MUTEX_PRE_SIGNAL __tsan_mutex_pre_signal
-#define ABSL_TSAN_MUTEX_POST_SIGNAL __tsan_mutex_post_signal
-#define ABSL_TSAN_MUTEX_PRE_DIVERT __tsan_mutex_pre_divert
-#define ABSL_TSAN_MUTEX_POST_DIVERT __tsan_mutex_post_divert
-
-#else
-
-#define ABSL_TSAN_MUTEX_CREATE(...)
-#define ABSL_TSAN_MUTEX_DESTROY(...)
-#define ABSL_TSAN_MUTEX_PRE_LOCK(...)
-#define ABSL_TSAN_MUTEX_POST_LOCK(...)
-#define ABSL_TSAN_MUTEX_PRE_UNLOCK(...)
-#define ABSL_TSAN_MUTEX_POST_UNLOCK(...)
-#define ABSL_TSAN_MUTEX_PRE_SIGNAL(...)
-#define ABSL_TSAN_MUTEX_POST_SIGNAL(...)
-#define ABSL_TSAN_MUTEX_PRE_DIVERT(...)
-#define ABSL_TSAN_MUTEX_POST_DIVERT(...)
-
-#endif
-
-#endif // ABSL_BASE_INTERNAL_TSAN_MUTEX_INTERFACE_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/unaligned_access.h b/third_party/abseil-cpp/absl/base/internal/unaligned_access.h
deleted file mode 100644
index 093dd9b..0000000
--- a/third_party/abseil-cpp/absl/base/internal/unaligned_access.h
+++ /dev/null
@@ -1,82 +0,0 @@
-//
-// Copyright 2017 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_UNALIGNED_ACCESS_H_
-#define ABSL_BASE_INTERNAL_UNALIGNED_ACCESS_H_
-
-#include <string.h>
-
-#include <cstdint>
-
-#include "absl/base/attributes.h"
-#include "absl/base/config.h"
-
-// unaligned APIs
-
-// Portable handling of unaligned loads, stores, and copies.
-
-// The unaligned API is C++ only. The declarations use C++ features
-// (namespaces, inline) which are absent or incompatible in C.
-#if defined(__cplusplus)
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-
-inline uint16_t UnalignedLoad16(const void *p) {
- uint16_t t;
- memcpy(&t, p, sizeof t);
- return t;
-}
-
-inline uint32_t UnalignedLoad32(const void *p) {
- uint32_t t;
- memcpy(&t, p, sizeof t);
- return t;
-}
-
-inline uint64_t UnalignedLoad64(const void *p) {
- uint64_t t;
- memcpy(&t, p, sizeof t);
- return t;
-}
-
-inline void UnalignedStore16(void *p, uint16_t v) { memcpy(p, &v, sizeof v); }
-
-inline void UnalignedStore32(void *p, uint32_t v) { memcpy(p, &v, sizeof v); }
-
-inline void UnalignedStore64(void *p, uint64_t v) { memcpy(p, &v, sizeof v); }
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#define ABSL_INTERNAL_UNALIGNED_LOAD16(_p) \
- (absl::base_internal::UnalignedLoad16(_p))
-#define ABSL_INTERNAL_UNALIGNED_LOAD32(_p) \
- (absl::base_internal::UnalignedLoad32(_p))
-#define ABSL_INTERNAL_UNALIGNED_LOAD64(_p) \
- (absl::base_internal::UnalignedLoad64(_p))
-
-#define ABSL_INTERNAL_UNALIGNED_STORE16(_p, _val) \
- (absl::base_internal::UnalignedStore16(_p, _val))
-#define ABSL_INTERNAL_UNALIGNED_STORE32(_p, _val) \
- (absl::base_internal::UnalignedStore32(_p, _val))
-#define ABSL_INTERNAL_UNALIGNED_STORE64(_p, _val) \
- (absl::base_internal::UnalignedStore64(_p, _val))
-
-#endif // defined(__cplusplus), end of unaligned API
-
-#endif // ABSL_BASE_INTERNAL_UNALIGNED_ACCESS_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/unique_small_name_test.cc b/third_party/abseil-cpp/absl/base/internal/unique_small_name_test.cc
deleted file mode 100644
index ff8c2b3..0000000
--- a/third_party/abseil-cpp/absl/base/internal/unique_small_name_test.cc
+++ /dev/null
@@ -1,77 +0,0 @@
-// 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 "gtest/gtest.h"
-#include "absl/base/optimization.h"
-#include "absl/strings/string_view.h"
-
-// This test by itself does not do anything fancy, but it serves as binary I can
-// query in shell test.
-
-namespace {
-
-template <class T>
-void DoNotOptimize(const T& var) {
-#ifdef __GNUC__
- asm volatile("" : "+m"(const_cast<T&>(var)));
-#else
- std::cout << (void*)&var;
-#endif
-}
-
-int very_long_int_variable_name ABSL_INTERNAL_UNIQUE_SMALL_NAME() = 0;
-char very_long_str_variable_name[] ABSL_INTERNAL_UNIQUE_SMALL_NAME() = "abc";
-
-TEST(UniqueSmallName, NonAutomaticVar) {
- EXPECT_EQ(very_long_int_variable_name, 0);
- EXPECT_EQ(absl::string_view(very_long_str_variable_name), "abc");
-}
-
-int VeryLongFreeFunctionName() ABSL_INTERNAL_UNIQUE_SMALL_NAME();
-
-TEST(UniqueSmallName, FreeFunction) {
- DoNotOptimize(&VeryLongFreeFunctionName);
-
- EXPECT_EQ(VeryLongFreeFunctionName(), 456);
-}
-
-int VeryLongFreeFunctionName() { return 456; }
-
-struct VeryLongStructName {
- explicit VeryLongStructName(int i);
-
- int VeryLongMethodName() ABSL_INTERNAL_UNIQUE_SMALL_NAME();
-
- static int VeryLongStaticMethodName() ABSL_INTERNAL_UNIQUE_SMALL_NAME();
-
- private:
- int fld;
-};
-
-TEST(UniqueSmallName, Struct) {
- VeryLongStructName var(10);
-
- DoNotOptimize(var);
- DoNotOptimize(&VeryLongStructName::VeryLongMethodName);
- DoNotOptimize(&VeryLongStructName::VeryLongStaticMethodName);
-
- EXPECT_EQ(var.VeryLongMethodName(), 10);
- EXPECT_EQ(VeryLongStructName::VeryLongStaticMethodName(), 123);
-}
-
-VeryLongStructName::VeryLongStructName(int i) : fld(i) {}
-int VeryLongStructName::VeryLongMethodName() { return fld; }
-int VeryLongStructName::VeryLongStaticMethodName() { return 123; }
-
-} // namespace
diff --git a/third_party/abseil-cpp/absl/base/internal/unscaledcycleclock.cc b/third_party/abseil-cpp/absl/base/internal/unscaledcycleclock.cc
deleted file mode 100644
index b1c396c..0000000
--- a/third_party/abseil-cpp/absl/base/internal/unscaledcycleclock.cc
+++ /dev/null
@@ -1,153 +0,0 @@
-// Copyright 2017 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/unscaledcycleclock.h"
-
-#if ABSL_USE_UNSCALED_CYCLECLOCK
-
-#if defined(_WIN32)
-#include <intrin.h>
-#endif
-
-#if defined(__powerpc__) || defined(__ppc__)
-#ifdef __GLIBC__
-#include <sys/platform/ppc.h>
-#elif defined(__FreeBSD__)
-// clang-format off
-// This order does actually matter =(.
-#include <sys/types.h>
-#include <sys/sysctl.h>
-// clang-format on
-
-#include "absl/base/call_once.h"
-#endif
-#endif
-
-#include "absl/base/internal/sysinfo.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-
-#if defined(__i386__)
-
-int64_t UnscaledCycleClock::Now() {
- int64_t ret;
- __asm__ volatile("rdtsc" : "=A"(ret));
- return ret;
-}
-
-double UnscaledCycleClock::Frequency() {
- return base_internal::NominalCPUFrequency();
-}
-
-#elif defined(__x86_64__)
-
-double UnscaledCycleClock::Frequency() {
- return base_internal::NominalCPUFrequency();
-}
-
-#elif defined(__powerpc__) || defined(__ppc__)
-
-int64_t UnscaledCycleClock::Now() {
-#ifdef __GLIBC__
- return __ppc_get_timebase();
-#else
-#ifdef __powerpc64__
- int64_t tbr;
- asm volatile("mfspr %0, 268" : "=r"(tbr));
- return tbr;
-#else
- int32_t tbu, tbl, tmp;
- asm volatile(
- "0:\n"
- "mftbu %[hi32]\n"
- "mftb %[lo32]\n"
- "mftbu %[tmp]\n"
- "cmpw %[tmp],%[hi32]\n"
- "bne 0b\n"
- : [ hi32 ] "=r"(tbu), [ lo32 ] "=r"(tbl), [ tmp ] "=r"(tmp));
- return (static_cast<int64_t>(tbu) << 32) | tbl;
-#endif
-#endif
-}
-
-double UnscaledCycleClock::Frequency() {
-#ifdef __GLIBC__
- return __ppc_get_timebase_freq();
-#elif defined(_AIX)
- // This is the same constant value as returned by
- // __ppc_get_timebase_freq().
- return static_cast<double>(512000000);
-#elif defined(__FreeBSD__)
- static once_flag init_timebase_frequency_once;
- static double timebase_frequency = 0.0;
- base_internal::LowLevelCallOnce(&init_timebase_frequency_once, [&]() {
- size_t length = sizeof(timebase_frequency);
- sysctlbyname("kern.timecounter.tc.timebase.frequency", &timebase_frequency,
- &length, nullptr, 0);
- });
- return timebase_frequency;
-#else
-#error Must implement UnscaledCycleClock::Frequency()
-#endif
-}
-
-#elif defined(__aarch64__)
-
-// System timer of ARMv8 runs at a different frequency than the CPU's.
-// The frequency is fixed, typically in the range 1-50MHz. It can be
-// read at CNTFRQ special register. We assume the OS has set up
-// the virtual timer properly.
-int64_t UnscaledCycleClock::Now() {
- int64_t virtual_timer_value;
- asm volatile("mrs %0, cntvct_el0" : "=r"(virtual_timer_value));
- return virtual_timer_value;
-}
-
-double UnscaledCycleClock::Frequency() {
- uint64_t aarch64_timer_frequency;
- asm volatile("mrs %0, cntfrq_el0" : "=r"(aarch64_timer_frequency));
- return aarch64_timer_frequency;
-}
-
-#elif defined(__riscv)
-
-int64_t UnscaledCycleClock::Now() {
- int64_t virtual_timer_value;
- asm volatile("rdcycle %0" : "=r"(virtual_timer_value));
- return virtual_timer_value;
-}
-
-double UnscaledCycleClock::Frequency() {
- return base_internal::NominalCPUFrequency();
-}
-
-#elif defined(_M_IX86) || defined(_M_X64)
-
-#pragma intrinsic(__rdtsc)
-
-int64_t UnscaledCycleClock::Now() { return __rdtsc(); }
-
-double UnscaledCycleClock::Frequency() {
- return base_internal::NominalCPUFrequency();
-}
-
-#endif
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_USE_UNSCALED_CYCLECLOCK
diff --git a/third_party/abseil-cpp/absl/base/internal/unscaledcycleclock.h b/third_party/abseil-cpp/absl/base/internal/unscaledcycleclock.h
deleted file mode 100644
index cc1276b..0000000
--- a/third_party/abseil-cpp/absl/base/internal/unscaledcycleclock.h
+++ /dev/null
@@ -1,96 +0,0 @@
-// Copyright 2017 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.
-//
-// UnscaledCycleClock
-// An UnscaledCycleClock yields the value and frequency of a cycle counter
-// that increments at a rate that is approximately constant.
-// This class is for internal use only, you should consider using CycleClock
-// instead.
-//
-// Notes:
-// The cycle counter frequency is not necessarily the core clock frequency.
-// That is, CycleCounter cycles are not necessarily "CPU cycles".
-//
-// An arbitrary offset may have been added to the counter at power on.
-//
-// On some platforms, the rate and offset of the counter may differ
-// slightly when read from different CPUs of a multiprocessor. Usually,
-// we try to ensure that the operating system adjusts values periodically
-// so that values agree approximately. If you need stronger guarantees,
-// consider using alternate interfaces.
-//
-// The CPU is not required to maintain the ordering of a cycle counter read
-// with respect to surrounding instructions.
-
-#ifndef ABSL_BASE_INTERNAL_UNSCALEDCYCLECLOCK_H_
-#define ABSL_BASE_INTERNAL_UNSCALEDCYCLECLOCK_H_
-
-#include <cstdint>
-
-#if defined(__APPLE__)
-#include <TargetConditionals.h>
-#endif
-
-#include "absl/base/config.h"
-#include "absl/base/internal/unscaledcycleclock_config.h"
-
-#if ABSL_USE_UNSCALED_CYCLECLOCK
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace time_internal {
-class UnscaledCycleClockWrapperForGetCurrentTime;
-} // namespace time_internal
-
-namespace base_internal {
-class CycleClock;
-class UnscaledCycleClockWrapperForInitializeFrequency;
-
-class UnscaledCycleClock {
- private:
- UnscaledCycleClock() = delete;
-
- // Return the value of a cycle counter that counts at a rate that is
- // approximately constant.
- static int64_t Now();
-
- // Return the how much UnscaledCycleClock::Now() increases per second.
- // This is not necessarily the core CPU clock frequency.
- // It may be the nominal value report by the kernel, rather than a measured
- // value.
- static double Frequency();
-
- // Allowed users
- friend class base_internal::CycleClock;
- friend class time_internal::UnscaledCycleClockWrapperForGetCurrentTime;
- friend class base_internal::UnscaledCycleClockWrapperForInitializeFrequency;
-};
-
-#if defined(__x86_64__)
-
-inline int64_t UnscaledCycleClock::Now() {
- uint64_t low, high;
- __asm__ volatile("rdtsc" : "=a"(low), "=d"(high));
- return static_cast<int64_t>((high << 32) | low);
-}
-
-#endif
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_USE_UNSCALED_CYCLECLOCK
-
-#endif // ABSL_BASE_INTERNAL_UNSCALEDCYCLECLOCK_H_
diff --git a/third_party/abseil-cpp/absl/base/internal/unscaledcycleclock_config.h b/third_party/abseil-cpp/absl/base/internal/unscaledcycleclock_config.h
deleted file mode 100644
index 24b324a..0000000
--- a/third_party/abseil-cpp/absl/base/internal/unscaledcycleclock_config.h
+++ /dev/null
@@ -1,62 +0,0 @@
-// Copyright 2022 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_UNSCALEDCYCLECLOCK_CONFIG_H_
-#define ABSL_BASE_INTERNAL_UNSCALEDCYCLECLOCK_CONFIG_H_
-
-#if defined(__APPLE__)
-#include <TargetConditionals.h>
-#endif
-
-// The following platforms have an implementation of a hardware counter.
-#if defined(__i386__) || defined(__x86_64__) || defined(__aarch64__) || \
- defined(__powerpc__) || defined(__ppc__) || defined(__riscv) || \
- defined(_M_IX86) || (defined(_M_X64) && !defined(_M_ARM64EC))
-#define ABSL_HAVE_UNSCALED_CYCLECLOCK_IMPLEMENTATION 1
-#else
-#define ABSL_HAVE_UNSCALED_CYCLECLOCK_IMPLEMENTATION 0
-#endif
-
-// The following platforms often disable access to the hardware
-// counter (through a sandbox) even if the underlying hardware has a
-// usable counter. The CycleTimer interface also requires a *scaled*
-// CycleClock that runs at atleast 1 MHz. We've found some Android
-// ARM64 devices where this is not the case, so we disable it by
-// default on Android ARM64.
-#if defined(__native_client__) || (defined(__APPLE__)) || \
- (defined(__ANDROID__) && defined(__aarch64__))
-#define ABSL_USE_UNSCALED_CYCLECLOCK_DEFAULT 0
-#else
-#define ABSL_USE_UNSCALED_CYCLECLOCK_DEFAULT 1
-#endif
-
-// UnscaledCycleClock is an optional internal feature.
-// Use "#if ABSL_USE_UNSCALED_CYCLECLOCK" to test for its presence.
-// Can be overridden at compile-time via -DABSL_USE_UNSCALED_CYCLECLOCK=0|1
-#if !defined(ABSL_USE_UNSCALED_CYCLECLOCK)
-#define ABSL_USE_UNSCALED_CYCLECLOCK \
- (ABSL_HAVE_UNSCALED_CYCLECLOCK_IMPLEMENTATION && \
- ABSL_USE_UNSCALED_CYCLECLOCK_DEFAULT)
-#endif
-
-#if ABSL_USE_UNSCALED_CYCLECLOCK
-// This macro can be used to test if UnscaledCycleClock::Frequency()
-// is NominalCPUFrequency() on a particular platform.
-#if (defined(__i386__) || defined(__x86_64__) || defined(__riscv) || \
- defined(_M_IX86) || defined(_M_X64))
-#define ABSL_INTERNAL_UNSCALED_CYCLECLOCK_FREQUENCY_IS_CPU_FREQUENCY
-#endif
-#endif
-
-#endif // ABSL_BASE_INTERNAL_UNSCALEDCYCLECLOCK_CONFIG_H_
diff --git a/third_party/abseil-cpp/absl/base/invoke_test.cc b/third_party/abseil-cpp/absl/base/invoke_test.cc
deleted file mode 100644
index 7be26f6..0000000
--- a/third_party/abseil-cpp/absl/base/invoke_test.cc
+++ /dev/null
@@ -1,331 +0,0 @@
-// Copyright 2017 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/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;
-};
-
-// CallMaybeWithArg(f) resolves either to invoke(f) or invoke(f, 42), depending
-// on which one is valid.
-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)); // NOLINT
- 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};
- // This call could resolve to (obj.*&FlipFlop::ConstMethod)() or
- // ((*obj).*&FlipFlop::ConstMethod)(). We verify that it's the former.
- 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");
-}
-
-} // namespace
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/base/log_severity.cc b/third_party/abseil-cpp/absl/base/log_severity.cc
deleted file mode 100644
index 60a8fc1..0000000
--- a/third_party/abseil-cpp/absl/base/log_severity.cc
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright 2017 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/log_severity.h"
-
-#include <ostream>
-
-#include "absl/base/attributes.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-
-std::ostream& operator<<(std::ostream& os, absl::LogSeverity s) {
- if (s == absl::NormalizeLogSeverity(s)) return os << absl::LogSeverityName(s);
- return os << "absl::LogSeverity(" << static_cast<int>(s) << ")";
-}
-
-std::ostream& operator<<(std::ostream& os, absl::LogSeverityAtLeast s) {
- switch (s) {
- case absl::LogSeverityAtLeast::kInfo:
- case absl::LogSeverityAtLeast::kWarning:
- case absl::LogSeverityAtLeast::kError:
- case absl::LogSeverityAtLeast::kFatal:
- return os << ">=" << static_cast<absl::LogSeverity>(s);
- case absl::LogSeverityAtLeast::kInfinity:
- return os << "INFINITY";
- }
- return os;
-}
-
-std::ostream& operator<<(std::ostream& os, absl::LogSeverityAtMost s) {
- switch (s) {
- case absl::LogSeverityAtMost::kInfo:
- case absl::LogSeverityAtMost::kWarning:
- case absl::LogSeverityAtMost::kError:
- case absl::LogSeverityAtMost::kFatal:
- return os << "<=" << static_cast<absl::LogSeverity>(s);
- case absl::LogSeverityAtMost::kNegativeInfinity:
- return os << "NEGATIVE_INFINITY";
- }
- return os;
-}
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/base/log_severity.h b/third_party/abseil-cpp/absl/base/log_severity.h
deleted file mode 100644
index 8bdca38..0000000
--- a/third_party/abseil-cpp/absl/base/log_severity.h
+++ /dev/null
@@ -1,172 +0,0 @@
-// Copyright 2017 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_LOG_SEVERITY_H_
-#define ABSL_BASE_LOG_SEVERITY_H_
-
-#include <array>
-#include <ostream>
-
-#include "absl/base/attributes.h"
-#include "absl/base/config.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-
-// absl::LogSeverity
-//
-// Four severity levels are defined. Logging APIs should terminate the program
-// when a message is logged at severity `kFatal`; the other levels have no
-// special semantics.
-//
-// Values other than the four defined levels (e.g. produced by `static_cast`)
-// are valid, but their semantics when passed to a function, macro, or flag
-// depend on the function, macro, or flag. The usual behavior is to normalize
-// such values to a defined severity level, however in some cases values other
-// than the defined levels are useful for comparison.
-//
-// Example:
-//
-// // Effectively disables all logging:
-// SetMinLogLevel(static_cast<absl::LogSeverity>(100));
-//
-// Abseil flags may be defined with type `LogSeverity`. Dependency layering
-// constraints require that the `AbslParseFlag()` overload be declared and
-// defined in the flags library itself rather than here. The `AbslUnparseFlag()`
-// overload is defined there as well for consistency.
-//
-// absl::LogSeverity Flag String Representation
-//
-// An `absl::LogSeverity` has a string representation used for parsing
-// command-line flags based on the enumerator name (e.g. `kFatal`) or
-// its unprefixed name (without the `k`) in any case-insensitive form. (E.g.
-// "FATAL", "fatal" or "Fatal" are all valid.) Unparsing such flags produces an
-// unprefixed string representation in all caps (e.g. "FATAL") or an integer.
-//
-// Additionally, the parser accepts arbitrary integers (as if the type were
-// `int`).
-//
-// Examples:
-//
-// --my_log_level=kInfo
-// --my_log_level=INFO
-// --my_log_level=info
-// --my_log_level=0
-//
-// Unparsing a flag produces the same result as `absl::LogSeverityName()` for
-// the standard levels and a base-ten integer otherwise.
-enum class LogSeverity : int {
- kInfo = 0,
- kWarning = 1,
- kError = 2,
- kFatal = 3,
-};
-
-// LogSeverities()
-//
-// Returns an iterable of all standard `absl::LogSeverity` values, ordered from
-// least to most severe.
-constexpr std::array<absl::LogSeverity, 4> LogSeverities() {
- return {{absl::LogSeverity::kInfo, absl::LogSeverity::kWarning,
- absl::LogSeverity::kError, absl::LogSeverity::kFatal}};
-}
-
-// LogSeverityName()
-//
-// Returns the all-caps string representation (e.g. "INFO") of the specified
-// severity level if it is one of the standard levels and "UNKNOWN" otherwise.
-constexpr const char* LogSeverityName(absl::LogSeverity s) {
- return s == absl::LogSeverity::kInfo
- ? "INFO"
- : s == absl::LogSeverity::kWarning
- ? "WARNING"
- : s == absl::LogSeverity::kError
- ? "ERROR"
- : s == absl::LogSeverity::kFatal ? "FATAL" : "UNKNOWN";
-}
-
-// NormalizeLogSeverity()
-//
-// Values less than `kInfo` normalize to `kInfo`; values greater than `kFatal`
-// normalize to `kError` (**NOT** `kFatal`).
-constexpr absl::LogSeverity NormalizeLogSeverity(absl::LogSeverity s) {
- return s < absl::LogSeverity::kInfo
- ? absl::LogSeverity::kInfo
- : s > absl::LogSeverity::kFatal ? absl::LogSeverity::kError : s;
-}
-constexpr absl::LogSeverity NormalizeLogSeverity(int s) {
- return absl::NormalizeLogSeverity(static_cast<absl::LogSeverity>(s));
-}
-
-// operator<<
-//
-// The exact representation of a streamed `absl::LogSeverity` is deliberately
-// unspecified; do not rely on it.
-std::ostream& operator<<(std::ostream& os, absl::LogSeverity s);
-
-// Enums representing a lower bound for LogSeverity. APIs that only operate on
-// messages of at least a certain level (for example, `SetMinLogLevel()`) use
-// this type to specify that level. absl::LogSeverityAtLeast::kInfinity is
-// a level above all threshold levels and therefore no log message will
-// ever meet this threshold.
-enum class LogSeverityAtLeast : int {
- kInfo = static_cast<int>(absl::LogSeverity::kInfo),
- kWarning = static_cast<int>(absl::LogSeverity::kWarning),
- kError = static_cast<int>(absl::LogSeverity::kError),
- kFatal = static_cast<int>(absl::LogSeverity::kFatal),
- kInfinity = 1000,
-};
-
-std::ostream& operator<<(std::ostream& os, absl::LogSeverityAtLeast s);
-
-// Enums representing an upper bound for LogSeverity. APIs that only operate on
-// messages of at most a certain level (for example, buffer all messages at or
-// below a certain level) use this type to specify that level.
-// absl::LogSeverityAtMost::kNegativeInfinity is a level below all threshold
-// levels and therefore will exclude all log messages.
-enum class LogSeverityAtMost : int {
- kNegativeInfinity = -1000,
- kInfo = static_cast<int>(absl::LogSeverity::kInfo),
- kWarning = static_cast<int>(absl::LogSeverity::kWarning),
- kError = static_cast<int>(absl::LogSeverity::kError),
- kFatal = static_cast<int>(absl::LogSeverity::kFatal),
-};
-
-std::ostream& operator<<(std::ostream& os, absl::LogSeverityAtMost s);
-
-#define COMPOP(op1, op2, T) \
- constexpr bool operator op1(absl::T lhs, absl::LogSeverity rhs) { \
- return static_cast<absl::LogSeverity>(lhs) op1 rhs; \
- } \
- constexpr bool operator op2(absl::LogSeverity lhs, absl::T rhs) { \
- return lhs op2 static_cast<absl::LogSeverity>(rhs); \
- }
-
-// Comparisons between `LogSeverity` and `LogSeverityAtLeast`/
-// `LogSeverityAtMost` are only supported in one direction.
-// Valid checks are:
-// LogSeverity >= LogSeverityAtLeast
-// LogSeverity < LogSeverityAtLeast
-// LogSeverity <= LogSeverityAtMost
-// LogSeverity > LogSeverityAtMost
-COMPOP(>, <, LogSeverityAtLeast)
-COMPOP(<=, >=, LogSeverityAtLeast)
-COMPOP(<, >, LogSeverityAtMost)
-COMPOP(>=, <=, LogSeverityAtMost)
-#undef COMPOP
-
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_BASE_LOG_SEVERITY_H_
diff --git a/third_party/abseil-cpp/absl/base/log_severity_test.cc b/third_party/abseil-cpp/absl/base/log_severity_test.cc
deleted file mode 100644
index 16091a5..0000000
--- a/third_party/abseil-cpp/absl/base/log_severity_test.cc
+++ /dev/null
@@ -1,245 +0,0 @@
-// Copyright 2018 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/log_severity.h"
-
-#include <cstdint>
-#include <ios>
-#include <limits>
-#include <ostream>
-#include <sstream>
-#include <string>
-#include <tuple>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/flags/internal/flag.h"
-#include "absl/flags/marshalling.h"
-#include "absl/strings/str_cat.h"
-
-namespace {
-using ::testing::Eq;
-using ::testing::IsFalse;
-using ::testing::IsTrue;
-using ::testing::TestWithParam;
-using ::testing::Values;
-
-template <typename T>
-std::string StreamHelper(T value) {
- std::ostringstream stream;
- stream << value;
- return stream.str();
-}
-
-TEST(StreamTest, Works) {
- EXPECT_THAT(StreamHelper(static_cast<absl::LogSeverity>(-100)),
- Eq("absl::LogSeverity(-100)"));
- EXPECT_THAT(StreamHelper(absl::LogSeverity::kInfo), Eq("INFO"));
- EXPECT_THAT(StreamHelper(absl::LogSeverity::kWarning), Eq("WARNING"));
- EXPECT_THAT(StreamHelper(absl::LogSeverity::kError), Eq("ERROR"));
- EXPECT_THAT(StreamHelper(absl::LogSeverity::kFatal), Eq("FATAL"));
- EXPECT_THAT(StreamHelper(static_cast<absl::LogSeverity>(4)),
- Eq("absl::LogSeverity(4)"));
-}
-
-static_assert(absl::flags_internal::FlagUseValueAndInitBitStorage<
- absl::LogSeverity>::value,
- "Flags of type absl::LogSeverity ought to be lock-free.");
-
-using ParseFlagFromOutOfRangeIntegerTest = TestWithParam<int64_t>;
-INSTANTIATE_TEST_SUITE_P(
- Instantiation, ParseFlagFromOutOfRangeIntegerTest,
- Values(static_cast<int64_t>(std::numeric_limits<int>::min()) - 1,
- static_cast<int64_t>(std::numeric_limits<int>::max()) + 1));
-TEST_P(ParseFlagFromOutOfRangeIntegerTest, ReturnsError) {
- const std::string to_parse = absl::StrCat(GetParam());
- absl::LogSeverity value;
- std::string error;
- EXPECT_THAT(absl::ParseFlag(to_parse, &value, &error), IsFalse()) << value;
-}
-
-using ParseFlagFromAlmostOutOfRangeIntegerTest = TestWithParam<int>;
-INSTANTIATE_TEST_SUITE_P(Instantiation,
- ParseFlagFromAlmostOutOfRangeIntegerTest,
- Values(std::numeric_limits<int>::min(),
- std::numeric_limits<int>::max()));
-TEST_P(ParseFlagFromAlmostOutOfRangeIntegerTest, YieldsExpectedValue) {
- const auto expected = static_cast<absl::LogSeverity>(GetParam());
- const std::string to_parse = absl::StrCat(GetParam());
- absl::LogSeverity value;
- std::string error;
- ASSERT_THAT(absl::ParseFlag(to_parse, &value, &error), IsTrue()) << error;
- EXPECT_THAT(value, Eq(expected));
-}
-
-using ParseFlagFromIntegerMatchingEnumeratorTest =
- TestWithParam<std::tuple<absl::string_view, absl::LogSeverity>>;
-INSTANTIATE_TEST_SUITE_P(
- Instantiation, ParseFlagFromIntegerMatchingEnumeratorTest,
- Values(std::make_tuple("0", absl::LogSeverity::kInfo),
- std::make_tuple(" 0", absl::LogSeverity::kInfo),
- std::make_tuple("-0", absl::LogSeverity::kInfo),
- std::make_tuple("+0", absl::LogSeverity::kInfo),
- std::make_tuple("00", absl::LogSeverity::kInfo),
- std::make_tuple("0 ", absl::LogSeverity::kInfo),
- std::make_tuple("0x0", absl::LogSeverity::kInfo),
- std::make_tuple("1", absl::LogSeverity::kWarning),
- std::make_tuple("+1", absl::LogSeverity::kWarning),
- std::make_tuple("2", absl::LogSeverity::kError),
- std::make_tuple("3", absl::LogSeverity::kFatal)));
-TEST_P(ParseFlagFromIntegerMatchingEnumeratorTest, YieldsExpectedValue) {
- const absl::string_view to_parse = std::get<0>(GetParam());
- const absl::LogSeverity expected = std::get<1>(GetParam());
- absl::LogSeverity value;
- std::string error;
- ASSERT_THAT(absl::ParseFlag(to_parse, &value, &error), IsTrue()) << error;
- EXPECT_THAT(value, Eq(expected));
-}
-
-using ParseFlagFromOtherIntegerTest =
- TestWithParam<std::tuple<absl::string_view, int>>;
-INSTANTIATE_TEST_SUITE_P(Instantiation, ParseFlagFromOtherIntegerTest,
- Values(std::make_tuple("-1", -1),
- std::make_tuple("4", 4),
- std::make_tuple("010", 10),
- std::make_tuple("0x10", 16)));
-TEST_P(ParseFlagFromOtherIntegerTest, YieldsExpectedValue) {
- const absl::string_view to_parse = std::get<0>(GetParam());
- const auto expected = static_cast<absl::LogSeverity>(std::get<1>(GetParam()));
- absl::LogSeverity value;
- std::string error;
- ASSERT_THAT(absl::ParseFlag(to_parse, &value, &error), IsTrue()) << error;
- EXPECT_THAT(value, Eq(expected));
-}
-
-using ParseFlagFromEnumeratorTest =
- TestWithParam<std::tuple<absl::string_view, absl::LogSeverity>>;
-INSTANTIATE_TEST_SUITE_P(
- Instantiation, ParseFlagFromEnumeratorTest,
- Values(std::make_tuple("INFO", absl::LogSeverity::kInfo),
- std::make_tuple("info", absl::LogSeverity::kInfo),
- std::make_tuple("kInfo", absl::LogSeverity::kInfo),
- std::make_tuple("iNfO", absl::LogSeverity::kInfo),
- std::make_tuple("kInFo", absl::LogSeverity::kInfo),
- std::make_tuple("WARNING", absl::LogSeverity::kWarning),
- std::make_tuple("warning", absl::LogSeverity::kWarning),
- std::make_tuple("kWarning", absl::LogSeverity::kWarning),
- std::make_tuple("WaRnInG", absl::LogSeverity::kWarning),
- std::make_tuple("KwArNiNg", absl::LogSeverity::kWarning),
- std::make_tuple("ERROR", absl::LogSeverity::kError),
- std::make_tuple("error", absl::LogSeverity::kError),
- std::make_tuple("kError", absl::LogSeverity::kError),
- std::make_tuple("eRrOr", absl::LogSeverity::kError),
- std::make_tuple("kErRoR", absl::LogSeverity::kError),
- std::make_tuple("FATAL", absl::LogSeverity::kFatal),
- std::make_tuple("fatal", absl::LogSeverity::kFatal),
- std::make_tuple("kFatal", absl::LogSeverity::kFatal),
- std::make_tuple("FaTaL", absl::LogSeverity::kFatal),
- std::make_tuple("KfAtAl", absl::LogSeverity::kFatal)));
-TEST_P(ParseFlagFromEnumeratorTest, YieldsExpectedValue) {
- const absl::string_view to_parse = std::get<0>(GetParam());
- const absl::LogSeverity expected = std::get<1>(GetParam());
- absl::LogSeverity value;
- std::string error;
- ASSERT_THAT(absl::ParseFlag(to_parse, &value, &error), IsTrue()) << error;
- EXPECT_THAT(value, Eq(expected));
-}
-
-using ParseFlagFromGarbageTest = TestWithParam<absl::string_view>;
-INSTANTIATE_TEST_SUITE_P(Instantiation, ParseFlagFromGarbageTest,
- Values("", "\0", " ", "garbage", "kkinfo", "I"));
-TEST_P(ParseFlagFromGarbageTest, ReturnsError) {
- const absl::string_view to_parse = GetParam();
- absl::LogSeverity value;
- std::string error;
- EXPECT_THAT(absl::ParseFlag(to_parse, &value, &error), IsFalse()) << value;
-}
-
-using UnparseFlagToEnumeratorTest =
- TestWithParam<std::tuple<absl::LogSeverity, absl::string_view>>;
-INSTANTIATE_TEST_SUITE_P(
- Instantiation, UnparseFlagToEnumeratorTest,
- Values(std::make_tuple(absl::LogSeverity::kInfo, "INFO"),
- std::make_tuple(absl::LogSeverity::kWarning, "WARNING"),
- std::make_tuple(absl::LogSeverity::kError, "ERROR"),
- std::make_tuple(absl::LogSeverity::kFatal, "FATAL")));
-TEST_P(UnparseFlagToEnumeratorTest, ReturnsExpectedValueAndRoundTrips) {
- const absl::LogSeverity to_unparse = std::get<0>(GetParam());
- const absl::string_view expected = std::get<1>(GetParam());
- const std::string stringified_value = absl::UnparseFlag(to_unparse);
- EXPECT_THAT(stringified_value, Eq(expected));
- absl::LogSeverity reparsed_value;
- std::string error;
- EXPECT_THAT(absl::ParseFlag(stringified_value, &reparsed_value, &error),
- IsTrue());
- EXPECT_THAT(reparsed_value, Eq(to_unparse));
-}
-
-using UnparseFlagToOtherIntegerTest = TestWithParam<int>;
-INSTANTIATE_TEST_SUITE_P(Instantiation, UnparseFlagToOtherIntegerTest,
- Values(std::numeric_limits<int>::min(), -1, 4,
- std::numeric_limits<int>::max()));
-TEST_P(UnparseFlagToOtherIntegerTest, ReturnsExpectedValueAndRoundTrips) {
- const absl::LogSeverity to_unparse =
- static_cast<absl::LogSeverity>(GetParam());
- const std::string expected = absl::StrCat(GetParam());
- const std::string stringified_value = absl::UnparseFlag(to_unparse);
- EXPECT_THAT(stringified_value, Eq(expected));
- absl::LogSeverity reparsed_value;
- std::string error;
- EXPECT_THAT(absl::ParseFlag(stringified_value, &reparsed_value, &error),
- IsTrue());
- EXPECT_THAT(reparsed_value, Eq(to_unparse));
-}
-
-TEST(LogThresholdTest, LogSeverityAtLeastTest) {
- EXPECT_LT(absl::LogSeverity::kError, absl::LogSeverityAtLeast::kFatal);
- EXPECT_GT(absl::LogSeverityAtLeast::kError, absl::LogSeverity::kInfo);
-
- EXPECT_LE(absl::LogSeverityAtLeast::kInfo, absl::LogSeverity::kError);
- EXPECT_GE(absl::LogSeverity::kError, absl::LogSeverityAtLeast::kInfo);
-}
-
-TEST(LogThresholdTest, LogSeverityAtMostTest) {
- EXPECT_GT(absl::LogSeverity::kError, absl::LogSeverityAtMost::kWarning);
- EXPECT_LT(absl::LogSeverityAtMost::kError, absl::LogSeverity::kFatal);
-
- EXPECT_GE(absl::LogSeverityAtMost::kFatal, absl::LogSeverity::kError);
- EXPECT_LE(absl::LogSeverity::kWarning, absl::LogSeverityAtMost::kError);
-}
-
-TEST(LogThresholdTest, Extremes) {
- EXPECT_LT(absl::LogSeverity::kFatal, absl::LogSeverityAtLeast::kInfinity);
- EXPECT_GT(absl::LogSeverity::kInfo,
- absl::LogSeverityAtMost::kNegativeInfinity);
-}
-
-TEST(LogThresholdTest, Output) {
- EXPECT_THAT(StreamHelper(absl::LogSeverityAtLeast::kInfo), Eq(">=INFO"));
- EXPECT_THAT(StreamHelper(absl::LogSeverityAtLeast::kWarning),
- Eq(">=WARNING"));
- EXPECT_THAT(StreamHelper(absl::LogSeverityAtLeast::kError), Eq(">=ERROR"));
- EXPECT_THAT(StreamHelper(absl::LogSeverityAtLeast::kFatal), Eq(">=FATAL"));
- EXPECT_THAT(StreamHelper(absl::LogSeverityAtLeast::kInfinity),
- Eq("INFINITY"));
-
- EXPECT_THAT(StreamHelper(absl::LogSeverityAtMost::kInfo), Eq("<=INFO"));
- EXPECT_THAT(StreamHelper(absl::LogSeverityAtMost::kWarning), Eq("<=WARNING"));
- EXPECT_THAT(StreamHelper(absl::LogSeverityAtMost::kError), Eq("<=ERROR"));
- EXPECT_THAT(StreamHelper(absl::LogSeverityAtMost::kFatal), Eq("<=FATAL"));
- EXPECT_THAT(StreamHelper(absl::LogSeverityAtMost::kNegativeInfinity),
- Eq("NEGATIVE_INFINITY"));
-}
-
-} // namespace
diff --git a/third_party/abseil-cpp/absl/base/macros.h b/third_party/abseil-cpp/absl/base/macros.h
deleted file mode 100644
index 3e085a9..0000000
--- a/third_party/abseil-cpp/absl/base/macros.h
+++ /dev/null
@@ -1,158 +0,0 @@
-//
-// Copyright 2017 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.
-//
-// -----------------------------------------------------------------------------
-// File: macros.h
-// -----------------------------------------------------------------------------
-//
-// This header file defines the set of language macros used within Abseil code.
-// For the set of macros used to determine supported compilers and platforms,
-// see absl/base/config.h instead.
-//
-// This code is compiled directly on many platforms, including client
-// platforms like Windows, Mac, and embedded systems. Before making
-// any changes here, make sure that you're not breaking any platforms.
-
-#ifndef ABSL_BASE_MACROS_H_
-#define ABSL_BASE_MACROS_H_
-
-#include <cassert>
-#include <cstddef>
-
-#include "absl/base/attributes.h"
-#include "absl/base/config.h"
-#include "absl/base/optimization.h"
-#include "absl/base/port.h"
-
-// ABSL_ARRAYSIZE()
-//
-// Returns the number of elements in an array as a compile-time constant, which
-// can be used in defining new arrays. If you use this macro on a pointer by
-// mistake, you will get a compile-time error.
-#define ABSL_ARRAYSIZE(array) \
- (sizeof(::absl::macros_internal::ArraySizeHelper(array)))
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace macros_internal {
-// Note: this internal template function declaration is used by ABSL_ARRAYSIZE.
-// The function doesn't need a definition, as we only use its type.
-template <typename T, size_t N>
-auto ArraySizeHelper(const T (&array)[N]) -> char (&)[N];
-} // namespace macros_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-// ABSL_BAD_CALL_IF()
-//
-// Used on a function overload to trap bad calls: any call that matches the
-// overload will cause a compile-time error. This macro uses a clang-specific
-// "enable_if" attribute, as described at
-// https://clang.llvm.org/docs/AttributeReference.html#enable-if
-//
-// Overloads which use this macro should be bracketed by
-// `#ifdef ABSL_BAD_CALL_IF`.
-//
-// Example:
-//
-// int isdigit(int c);
-// #ifdef ABSL_BAD_CALL_IF
-// int isdigit(int c)
-// ABSL_BAD_CALL_IF(c <= -1 || c > 255,
-// "'c' must have the value of an unsigned char or EOF");
-// #endif // ABSL_BAD_CALL_IF
-#if ABSL_HAVE_ATTRIBUTE(enable_if)
-#define ABSL_BAD_CALL_IF(expr, msg) \
- __attribute__((enable_if(expr, "Bad call trap"), unavailable(msg)))
-#endif
-
-// ABSL_ASSERT()
-//
-// In C++11, `assert` can't be used portably within constexpr functions.
-// ABSL_ASSERT functions as a runtime assert but works in C++11 constexpr
-// functions. Example:
-//
-// constexpr double Divide(double a, double b) {
-// return ABSL_ASSERT(b != 0), a / b;
-// }
-//
-// This macro is inspired by
-// https://akrzemi1.wordpress.com/2017/05/18/asserts-in-constexpr-functions/
-#if defined(NDEBUG)
-#define ABSL_ASSERT(expr) \
- (false ? static_cast<void>(expr) : static_cast<void>(0))
-#else
-#define ABSL_ASSERT(expr) \
- (ABSL_PREDICT_TRUE((expr)) ? static_cast<void>(0) \
- : [] { assert(false && #expr); }()) // NOLINT
-#endif
-
-// `ABSL_INTERNAL_HARDENING_ABORT()` controls how `ABSL_HARDENING_ASSERT()`
-// aborts the program in release mode (when NDEBUG is defined). The
-// implementation should abort the program as quickly as possible and ideally it
-// should not be possible to ignore the abort request.
-#if (ABSL_HAVE_BUILTIN(__builtin_trap) && \
- ABSL_HAVE_BUILTIN(__builtin_unreachable)) || \
- (defined(__GNUC__) && !defined(__clang__))
-#define ABSL_INTERNAL_HARDENING_ABORT() \
- do { \
- __builtin_trap(); \
- __builtin_unreachable(); \
- } while (false)
-#else
-#define ABSL_INTERNAL_HARDENING_ABORT() abort()
-#endif
-
-// ABSL_HARDENING_ASSERT()
-//
-// `ABSL_HARDENING_ASSERT()` is like `ABSL_ASSERT()`, but used to implement
-// runtime assertions that should be enabled in hardened builds even when
-// `NDEBUG` is defined.
-//
-// When `NDEBUG` is not defined, `ABSL_HARDENING_ASSERT()` is identical to
-// `ABSL_ASSERT()`.
-//
-// See `ABSL_OPTION_HARDENED` in `absl/base/options.h` for more information on
-// hardened mode.
-#if ABSL_OPTION_HARDENED == 1 && defined(NDEBUG)
-#define ABSL_HARDENING_ASSERT(expr) \
- (ABSL_PREDICT_TRUE((expr)) ? static_cast<void>(0) \
- : [] { ABSL_INTERNAL_HARDENING_ABORT(); }())
-#else
-#define ABSL_HARDENING_ASSERT(expr) ABSL_ASSERT(expr)
-#endif
-
-#ifdef ABSL_HAVE_EXCEPTIONS
-#define ABSL_INTERNAL_TRY try
-#define ABSL_INTERNAL_CATCH_ANY catch (...)
-#define ABSL_INTERNAL_RETHROW do { throw; } while (false)
-#else // ABSL_HAVE_EXCEPTIONS
-#define ABSL_INTERNAL_TRY if (true)
-#define ABSL_INTERNAL_CATCH_ANY else if (false)
-#define ABSL_INTERNAL_RETHROW do {} while (false)
-#endif // ABSL_HAVE_EXCEPTIONS
-
-// `ABSL_INTERNAL_UNREACHABLE` is an unreachable statement. A program which
-// reaches one has undefined behavior, and the compiler may optimize
-// accordingly.
-#if defined(__GNUC__) || ABSL_HAVE_BUILTIN(__builtin_unreachable)
-#define ABSL_INTERNAL_UNREACHABLE __builtin_unreachable()
-#elif defined(_MSC_VER)
-#define ABSL_INTERNAL_UNREACHABLE __assume(0)
-#else
-#define ABSL_INTERNAL_UNREACHABLE
-#endif
-
-#endif // ABSL_BASE_MACROS_H_
diff --git a/third_party/abseil-cpp/absl/base/optimization.h b/third_party/abseil-cpp/absl/base/optimization.h
deleted file mode 100644
index d706100..0000000
--- a/third_party/abseil-cpp/absl/base/optimization.h
+++ /dev/null
@@ -1,252 +0,0 @@
-//
-// Copyright 2017 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.
-//
-// -----------------------------------------------------------------------------
-// File: optimization.h
-// -----------------------------------------------------------------------------
-//
-// This header file defines portable macros for performance optimization.
-
-#ifndef ABSL_BASE_OPTIMIZATION_H_
-#define ABSL_BASE_OPTIMIZATION_H_
-
-#include <assert.h>
-
-#include "absl/base/config.h"
-
-// ABSL_BLOCK_TAIL_CALL_OPTIMIZATION
-//
-// Instructs the compiler to avoid optimizing tail-call recursion. This macro is
-// useful when you wish to preserve the existing function order within a stack
-// trace for logging, debugging, or profiling purposes.
-//
-// Example:
-//
-// int f() {
-// int result = g();
-// ABSL_BLOCK_TAIL_CALL_OPTIMIZATION();
-// return result;
-// }
-#if defined(__pnacl__)
-#define ABSL_BLOCK_TAIL_CALL_OPTIMIZATION() if (volatile int x = 0) { (void)x; }
-#elif defined(__clang__)
-// Clang will not tail call given inline volatile assembly.
-#define ABSL_BLOCK_TAIL_CALL_OPTIMIZATION() __asm__ __volatile__("")
-#elif defined(__GNUC__)
-// GCC will not tail call given inline volatile assembly.
-#define ABSL_BLOCK_TAIL_CALL_OPTIMIZATION() __asm__ __volatile__("")
-#elif defined(_MSC_VER)
-#include <intrin.h>
-// The __nop() intrinsic blocks the optimisation.
-#define ABSL_BLOCK_TAIL_CALL_OPTIMIZATION() __nop()
-#else
-#define ABSL_BLOCK_TAIL_CALL_OPTIMIZATION() if (volatile int x = 0) { (void)x; }
-#endif
-
-// ABSL_CACHELINE_SIZE
-//
-// Explicitly defines the size of the L1 cache for purposes of alignment.
-// Setting the cacheline size allows you to specify that certain objects be
-// aligned on a cacheline boundary with `ABSL_CACHELINE_ALIGNED` declarations.
-// (See below.)
-//
-// NOTE: this macro should be replaced with the following C++17 features, when
-// those are generally available:
-//
-// * `std::hardware_constructive_interference_size`
-// * `std::hardware_destructive_interference_size`
-//
-// See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0154r1.html
-// for more information.
-#if defined(__GNUC__)
-// Cache line alignment
-#if defined(__i386__) || defined(__x86_64__)
-#define ABSL_CACHELINE_SIZE 64
-#elif defined(__powerpc64__)
-#define ABSL_CACHELINE_SIZE 128
-#elif defined(__aarch64__)
-// We would need to read special register ctr_el0 to find out L1 dcache size.
-// This value is a good estimate based on a real aarch64 machine.
-#define ABSL_CACHELINE_SIZE 64
-#elif defined(__arm__)
-// Cache line sizes for ARM: These values are not strictly correct since
-// cache line sizes depend on implementations, not architectures. There
-// are even implementations with cache line sizes configurable at boot
-// time.
-#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
-// A reasonable default guess. Note that overestimates tend to waste more
-// space, while underestimates tend to waste more time.
-#define ABSL_CACHELINE_SIZE 64
-#endif
-
-// ABSL_CACHELINE_ALIGNED
-//
-// Indicates that the declared object be cache aligned using
-// `ABSL_CACHELINE_SIZE` (see above). Cacheline aligning objects allows you to
-// load a set of related objects in the L1 cache for performance improvements.
-// Cacheline aligning objects properly allows constructive memory sharing and
-// prevents destructive (or "false") memory sharing.
-//
-// NOTE: callers should replace uses of this macro with `alignas()` using
-// `std::hardware_constructive_interference_size` and/or
-// `std::hardware_destructive_interference_size` when C++17 becomes available to
-// them.
-//
-// See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0154r1.html
-// for more information.
-//
-// On some compilers, `ABSL_CACHELINE_ALIGNED` expands to an `__attribute__`
-// or `__declspec` attribute. For compilers where this is not known to work,
-// the macro expands to nothing.
-//
-// No further guarantees are made here. The result of applying the macro
-// to variables and types is always implementation-defined.
-//
-// WARNING: It is easy to use this attribute incorrectly, even to the point
-// of causing bugs that are difficult to diagnose, crash, etc. It does not
-// of itself guarantee that objects are aligned to a cache line.
-//
-// NOTE: Some compilers are picky about the locations of annotations such as
-// this attribute, so prefer to put it at the beginning of your declaration.
-// For example,
-//
-// ABSL_CACHELINE_ALIGNED static Foo* foo = ...
-//
-// class ABSL_CACHELINE_ALIGNED Bar { ...
-//
-// Recommendations:
-//
-// 1) Consult compiler documentation; this comment is not kept in sync as
-// toolchains evolve.
-// 2) Verify your use has the intended effect. This often requires inspecting
-// the generated machine code.
-// 3) Prefer applying this attribute to individual variables. Avoid
-// applying it to types. This tends to localize the effect.
-#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
-
-// ABSL_PREDICT_TRUE, ABSL_PREDICT_FALSE
-//
-// Enables the compiler to prioritize compilation using static analysis for
-// likely paths within a boolean branch.
-//
-// Example:
-//
-// if (ABSL_PREDICT_TRUE(expression)) {
-// return result; // Faster if more likely
-// } else {
-// return 0;
-// }
-//
-// Compilers can use the information that a certain branch is not likely to be
-// taken (for instance, a CHECK failure) to optimize for the common case in
-// the absence of better information (ie. compiling gcc with `-fprofile-arcs`).
-//
-// Recommendation: Modern CPUs dynamically predict branch execution paths,
-// typically with accuracy greater than 97%. As a result, annotating every
-// branch in a codebase is likely counterproductive; however, annotating
-// specific branches that are both hot and consistently mispredicted is likely
-// to yield performance improvements.
-#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
-
-// ABSL_ASSUME(cond)
-//
-// Informs the compiler that a condition is always true and that it can assume
-// it to be true for optimization purposes.
-//
-// WARNING: If the condition is false, the program can produce undefined and
-// potentially dangerous behavior.
-//
-// In !NDEBUG mode, the condition is checked with an assert().
-//
-// NOTE: The expression must not have side effects, as it may only be evaluated
-// in some compilation modes and not others. Some compilers may issue a warning
-// if the compiler cannot prove the expression has no side effects. For example,
-// the expression should not use a function call since the compiler cannot prove
-// that a function call does not have side effects.
-//
-// Example:
-//
-// int x = ...;
-// ABSL_ASSUME(x >= 0);
-// // The compiler can optimize the division to a simple right shift using the
-// // assumption specified above.
-// int y = x / 16;
-//
-#if !defined(NDEBUG)
-#define ABSL_ASSUME(cond) assert(cond)
-#elif ABSL_HAVE_BUILTIN(__builtin_assume)
-#define ABSL_ASSUME(cond) __builtin_assume(cond)
-#elif defined(__GNUC__) || ABSL_HAVE_BUILTIN(__builtin_unreachable)
-#define ABSL_ASSUME(cond) \
- do { \
- if (!(cond)) __builtin_unreachable(); \
- } while (0)
-#elif defined(_MSC_VER)
-#define ABSL_ASSUME(cond) __assume(cond)
-#else
-#define ABSL_ASSUME(cond) \
- do { \
- static_cast<void>(false && (cond)); \
- } while (0)
-#endif
-
-// ABSL_INTERNAL_UNIQUE_SMALL_NAME(cond)
-// This macro forces small unique name on a static file level symbols like
-// static local variables or static functions. This is intended to be used in
-// macro definitions to optimize the cost of generated code. Do NOT use it on
-// symbols exported from translation unit since it may cause a link time
-// conflict.
-//
-// Example:
-//
-// #define MY_MACRO(txt)
-// namespace {
-// char VeryVeryLongVarName[] ABSL_INTERNAL_UNIQUE_SMALL_NAME() = txt;
-// const char* VeryVeryLongFuncName() ABSL_INTERNAL_UNIQUE_SMALL_NAME();
-// const char* VeryVeryLongFuncName() { return txt; }
-// }
-//
-
-#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 // ABSL_BASE_OPTIMIZATION_H_
diff --git a/third_party/abseil-cpp/absl/base/optimization_test.cc b/third_party/abseil-cpp/absl/base/optimization_test.cc
deleted file mode 100644
index e83369f..0000000
--- a/third_party/abseil-cpp/absl/base/optimization_test.cc
+++ /dev/null
@@ -1,129 +0,0 @@
-// 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/optimization.h"
-
-#include "gtest/gtest.h"
-#include "absl/types/optional.h"
-
-namespace {
-
-// Tests for the ABSL_PREDICT_TRUE and ABSL_PREDICT_FALSE macros.
-// The tests only verify that the macros are functionally correct - i.e. code
-// behaves as if they weren't used. They don't try to check their impact on
-// optimization.
-
-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) {
- // Verify that the expression is only evaluated once.
- 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) {
- // Verify that operator order inside and outside the macro behaves well.
- // These would fail for a naive '#define ABSL_PREDICT_TRUE(x) x'
- 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) {
- // Note: An optional's truth value is the value's existence, not its truth.
- 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 { // NOLINT(google-explicit-constructor)
- 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();
-}
-
-} // namespace
diff --git a/third_party/abseil-cpp/absl/base/options.h b/third_party/abseil-cpp/absl/base/options.h
deleted file mode 100644
index 9a15f2a..0000000
--- a/third_party/abseil-cpp/absl/base/options.h
+++ /dev/null
@@ -1,232 +0,0 @@
-// Copyright 2019 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.
-//
-// -----------------------------------------------------------------------------
-// File: options.h
-// -----------------------------------------------------------------------------
-//
-// This file contains Abseil configuration options for setting specific
-// implementations instead of letting Abseil determine which implementation to
-// use at compile-time. Setting these options may be useful for package or build
-// managers who wish to guarantee ABI stability within binary builds (which are
-// otherwise difficult to enforce).
-//
-// *** IMPORTANT NOTICE FOR PACKAGE MANAGERS: It is important that
-// maintainers of package managers who wish to package Abseil read and
-// understand this file! ***
-//
-// Abseil contains a number of possible configuration endpoints, based on
-// parameters such as the detected platform, language version, or command-line
-// flags used to invoke the underlying binary. As is the case with all
-// libraries, binaries which contain Abseil code must ensure that separate
-// packages use the same compiled copy of Abseil to avoid a diamond dependency
-// problem, which can occur if two packages built with different Abseil
-// configuration settings are linked together. Diamond dependency problems in
-// C++ may manifest as violations to the One Definition Rule (ODR) (resulting in
-// linker errors), or undefined behavior (resulting in crashes).
-//
-// Diamond dependency problems can be avoided if all packages utilize the same
-// exact version of Abseil. Building from source code with the same compilation
-// parameters is the easiest way to avoid such dependency problems. However, for
-// package managers who cannot control such compilation parameters, we are
-// providing the file to allow you to inject ABI (Application Binary Interface)
-// stability across builds. Settings options in this file will neither change
-// API nor ABI, providing a stable copy of Abseil between packages.
-//
-// Care must be taken to keep options within these configurations isolated
-// from any other dynamic settings, such as command-line flags which could alter
-// these options. This file is provided specifically to help build and package
-// managers provide a stable copy of Abseil within their libraries and binaries;
-// other developers should not have need to alter the contents of this file.
-//
-// -----------------------------------------------------------------------------
-// Usage
-// -----------------------------------------------------------------------------
-//
-// For any particular package release, set the appropriate definitions within
-// this file to whatever value makes the most sense for your package(s). Note
-// that, by default, most of these options, at the moment, affect the
-// implementation of types; future options may affect other implementation
-// details.
-//
-// NOTE: the defaults within this file all assume that Abseil can select the
-// proper Abseil implementation at compile-time, which will not be sufficient
-// to guarantee ABI stability to package managers.
-
-#ifndef ABSL_BASE_OPTIONS_H_
-#define ABSL_BASE_OPTIONS_H_
-
-// -----------------------------------------------------------------------------
-// Type Compatibility Options
-// -----------------------------------------------------------------------------
-//
-// ABSL_OPTION_USE_STD_ANY
-//
-// This option controls whether absl::any is implemented as an alias to
-// std::any, or as an independent implementation.
-//
-// A value of 0 means to use Abseil's implementation. This requires only C++11
-// support, and is expected to work on every toolchain we support.
-//
-// A value of 1 means to use an alias to std::any. This requires that all code
-// using Abseil is built in C++17 mode or later.
-//
-// A value of 2 means to detect the C++ version being used to compile Abseil,
-// and use an alias only if a working std::any is available. This option is
-// useful when you are building your entire program, including all of its
-// dependencies, from source. It should not be used otherwise -- for example,
-// if you are distributing Abseil in a binary package manager -- since in
-// mode 2, absl::any will name a different type, with a different mangled name
-// and binary layout, depending on the compiler flags passed by the end user.
-// For more info, see https://abseil.io/about/design/dropin-types.
-//
-// User code should not inspect this macro. To check in the preprocessor if
-// absl::any is a typedef of std::any, use the feature macro ABSL_USES_STD_ANY.
-
-#define ABSL_OPTION_USE_STD_ANY 0
-
-
-// ABSL_OPTION_USE_STD_OPTIONAL
-//
-// This option controls whether absl::optional is implemented as an alias to
-// std::optional, or as an independent implementation.
-//
-// A value of 0 means to use Abseil's implementation. This requires only C++11
-// support, and is expected to work on every toolchain we support.
-//
-// A value of 1 means to use an alias to std::optional. This requires that all
-// code using Abseil is built in C++17 mode or later.
-//
-// A value of 2 means to detect the C++ version being used to compile Abseil,
-// and use an alias only if a working std::optional is available. This option
-// is useful when you are building your program from source. It should not be
-// used otherwise -- for example, if you are distributing Abseil in a binary
-// package manager -- since in mode 2, absl::optional will name a different
-// type, with a different mangled name and binary layout, depending on the
-// compiler flags passed by the end user. For more info, see
-// https://abseil.io/about/design/dropin-types.
-
-// User code should not inspect this macro. To check in the preprocessor if
-// absl::optional is a typedef of std::optional, use the feature macro
-// ABSL_USES_STD_OPTIONAL.
-
-#define ABSL_OPTION_USE_STD_OPTIONAL 0
-
-
-// ABSL_OPTION_USE_STD_STRING_VIEW
-//
-// This option controls whether absl::string_view is implemented as an alias to
-// std::string_view, or as an independent implementation.
-//
-// A value of 0 means to use Abseil's implementation. This requires only C++11
-// support, and is expected to work on every toolchain we support.
-//
-// A value of 1 means to use an alias to std::string_view. This requires that
-// all code using Abseil is built in C++17 mode or later.
-//
-// A value of 2 means to detect the C++ version being used to compile Abseil,
-// and use an alias only if a working std::string_view is available. This
-// option is useful when you are building your program from source. It should
-// not be used otherwise -- for example, if you are distributing Abseil in a
-// binary package manager -- since in mode 2, absl::string_view will name a
-// different type, with a different mangled name and binary layout, depending on
-// the compiler flags passed by the end user. For more info, see
-// https://abseil.io/about/design/dropin-types.
-//
-// User code should not inspect this macro. To check in the preprocessor if
-// absl::string_view is a typedef of std::string_view, use the feature macro
-// ABSL_USES_STD_STRING_VIEW.
-
-#define ABSL_OPTION_USE_STD_STRING_VIEW 0
-
-// ABSL_OPTION_USE_STD_VARIANT
-//
-// This option controls whether absl::variant is implemented as an alias to
-// std::variant, or as an independent implementation.
-//
-// A value of 0 means to use Abseil's implementation. This requires only C++11
-// support, and is expected to work on every toolchain we support.
-//
-// A value of 1 means to use an alias to std::variant. This requires that all
-// code using Abseil is built in C++17 mode or later.
-//
-// A value of 2 means to detect the C++ version being used to compile Abseil,
-// and use an alias only if a working std::variant is available. This option
-// is useful when you are building your program from source. It should not be
-// used otherwise -- for example, if you are distributing Abseil in a binary
-// package manager -- since in mode 2, absl::variant will name a different
-// type, with a different mangled name and binary layout, depending on the
-// compiler flags passed by the end user. For more info, see
-// https://abseil.io/about/design/dropin-types.
-//
-// User code should not inspect this macro. To check in the preprocessor if
-// absl::variant is a typedef of std::variant, use the feature macro
-// ABSL_USES_STD_VARIANT.
-
-#define ABSL_OPTION_USE_STD_VARIANT 0
-
-
-// ABSL_OPTION_USE_INLINE_NAMESPACE
-// ABSL_OPTION_INLINE_NAMESPACE_NAME
-//
-// These options controls whether all entities in the absl namespace are
-// contained within an inner inline namespace. This does not affect the
-// user-visible API of Abseil, but it changes the mangled names of all symbols.
-//
-// This can be useful as a version tag if you are distributing Abseil in
-// precompiled form. This will prevent a binary library build of Abseil with
-// one inline namespace being used with headers configured with a different
-// inline namespace name. Binary packagers are reminded that Abseil does not
-// guarantee any ABI stability in Abseil, so any update of Abseil or
-// configuration change in such a binary package should be combined with a
-// new, unique value for the inline namespace name.
-//
-// A value of 0 means not to use inline namespaces.
-//
-// A value of 1 means to use an inline namespace with the given name inside
-// namespace absl. If this is set, ABSL_OPTION_INLINE_NAMESPACE_NAME must also
-// be changed to a new, unique identifier name. In particular "head" is not
-// allowed.
-
-#define ABSL_OPTION_USE_INLINE_NAMESPACE 0
-#define ABSL_OPTION_INLINE_NAMESPACE_NAME head
-
-// ABSL_OPTION_HARDENED
-//
-// This option enables a "hardened" build in release mode (in this context,
-// release mode is defined as a build where the `NDEBUG` macro is defined).
-//
-// A value of 0 means that "hardened" mode is not enabled.
-//
-// A value of 1 means that "hardened" mode is enabled.
-//
-// Hardened builds have additional security checks enabled when `NDEBUG` is
-// defined. Defining `NDEBUG` is normally used to turn `assert()` macro into a
-// no-op, as well as disabling other bespoke program consistency checks. By
-// defining ABSL_OPTION_HARDENED to 1, a select set of checks remain enabled in
-// release mode. These checks guard against programming errors that may lead to
-// security vulnerabilities. In release mode, when one of these programming
-// errors is encountered, the program will immediately abort, possibly without
-// any attempt at logging.
-//
-// The checks enabled by this option are not free; they do incur runtime cost.
-//
-// The checks enabled by this option are always active when `NDEBUG` is not
-// defined, even in the case when ABSL_OPTION_HARDENED is defined to 0. The
-// checks enabled by this option may abort the program in a different way and
-// log additional information when `NDEBUG` is not defined.
-
-#define ABSL_OPTION_HARDENED 1
-
-#endif // ABSL_BASE_OPTIONS_H_
diff --git a/third_party/abseil-cpp/absl/base/policy_checks.h b/third_party/abseil-cpp/absl/base/policy_checks.h
deleted file mode 100644
index 2626fb6..0000000
--- a/third_party/abseil-cpp/absl/base/policy_checks.h
+++ /dev/null
@@ -1,113 +0,0 @@
-// Copyright 2017 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.
-//
-// -----------------------------------------------------------------------------
-// File: policy_checks.h
-// -----------------------------------------------------------------------------
-//
-// This header enforces a minimum set of policies at build time, such as the
-// supported compiler and library versions. Unsupported configurations are
-// reported with `#error`. This enforcement is best effort, so successfully
-// compiling this header does not guarantee a supported configuration.
-
-#ifndef ABSL_BASE_POLICY_CHECKS_H_
-#define ABSL_BASE_POLICY_CHECKS_H_
-
-// Included for the __GLIBC_PREREQ macro used below.
-#include <limits.h>
-
-// Included for the _STLPORT_VERSION macro used below.
-#if defined(__cplusplus)
-#include <cstddef>
-#endif
-
-// -----------------------------------------------------------------------------
-// Operating System Check
-// -----------------------------------------------------------------------------
-
-#if defined(__CYGWIN__)
-#error "Cygwin is not supported."
-#endif
-
-// -----------------------------------------------------------------------------
-// Toolchain Check
-// -----------------------------------------------------------------------------
-
-// We support Visual Studio 2017 (MSVC++ 15.0) and later.
-// This minimum will go up.
-#if defined(_MSC_VER) && _MSC_VER < 1910 && !defined(__clang__)
-#error "This package requires Visual Studio 2017 (MSVC++ 15.0) or higher."
-#endif
-
-// We support gcc 5 and later.
-// This minimum will go up.
-#if defined(__GNUC__) && !defined(__clang__)
-#if __GNUC__ < 5
-#error "This package requires gcc 5 or higher."
-#endif
-#endif
-
-// We support Apple Xcode clang 4.2.1 (version 421.11.65) and later.
-// This corresponds to Apple Xcode version 4.5.
-// This minimum will go up.
-#if defined(__apple_build_version__) && __apple_build_version__ < 4211165
-#error "This package requires __apple_build_version__ of 4211165 or higher."
-#endif
-
-// -----------------------------------------------------------------------------
-// C++ Version Check
-// -----------------------------------------------------------------------------
-
-// Enforce C++14 as the minimum.
-#if defined(_MSVC_LANG)
-#if _MSVC_LANG < 201402L
-#error "C++ versions less than C++14 are not supported."
-#endif // _MSVC_LANG < 201402L
-#elif defined(__cplusplus)
-#if __cplusplus < 201402L
-#error "C++ versions less than C++14 are not supported."
-#endif // __cplusplus < 201402L
-#endif
-
-// -----------------------------------------------------------------------------
-// Standard Library Check
-// -----------------------------------------------------------------------------
-
-#if defined(_STLPORT_VERSION)
-#error "STLPort is not supported."
-#endif
-
-// -----------------------------------------------------------------------------
-// `char` Size Check
-// -----------------------------------------------------------------------------
-
-// Abseil currently assumes CHAR_BIT == 8. If you would like to use Abseil on a
-// platform where this is not the case, please provide us with the details about
-// your platform so we can consider relaxing this requirement.
-#if CHAR_BIT != 8
-#error "Abseil assumes CHAR_BIT == 8."
-#endif
-
-// -----------------------------------------------------------------------------
-// `int` Size Check
-// -----------------------------------------------------------------------------
-
-// Abseil currently assumes that an int is 4 bytes. If you would like to use
-// Abseil on a platform where this is not the case, please provide us with the
-// details about your platform so we can consider relaxing this requirement.
-#if INT_MAX < 2147483647
-#error "Abseil assumes that int is at least 4 bytes. "
-#endif
-
-#endif // ABSL_BASE_POLICY_CHECKS_H_
diff --git a/third_party/abseil-cpp/absl/base/port.h b/third_party/abseil-cpp/absl/base/port.h
deleted file mode 100644
index 5bc4d6c..0000000
--- a/third_party/abseil-cpp/absl/base/port.h
+++ /dev/null
@@ -1,25 +0,0 @@
-// Copyright 2017 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.
-//
-// This files is a forwarding header for other headers containing various
-// portability macros and functions.
-
-#ifndef ABSL_BASE_PORT_H_
-#define ABSL_BASE_PORT_H_
-
-#include "absl/base/attributes.h"
-#include "absl/base/config.h"
-#include "absl/base/optimization.h"
-
-#endif // ABSL_BASE_PORT_H_
diff --git a/third_party/abseil-cpp/absl/base/raw_logging_test.cc b/third_party/abseil-cpp/absl/base/raw_logging_test.cc
deleted file mode 100644
index 3d30bd3..0000000
--- a/third_party/abseil-cpp/absl/base/raw_logging_test.cc
+++ /dev/null
@@ -1,79 +0,0 @@
-// Copyright 2017 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.
-
-// This test serves primarily as a compilation test for base/raw_logging.h.
-// Raw logging testing is covered by logging_unittest.cc, which is not as
-// portable as this test.
-
-#include "absl/base/internal/raw_logging.h"
-
-#include <tuple>
-
-#include "gtest/gtest.h"
-#include "absl/strings/str_cat.h"
-
-namespace {
-
-TEST(RawLoggingCompilationTest, Log) {
- ABSL_RAW_LOG(INFO, "RAW INFO: %d", 1);
- ABSL_RAW_LOG(INFO, "RAW INFO: %d %d", 1, 2);
- ABSL_RAW_LOG(INFO, "RAW INFO: %d %d %d", 1, 2, 3);
- ABSL_RAW_LOG(INFO, "RAW INFO: %d %d %d %d", 1, 2, 3, 4);
- ABSL_RAW_LOG(INFO, "RAW INFO: %d %d %d %d %d", 1, 2, 3, 4, 5);
- ABSL_RAW_LOG(WARNING, "RAW WARNING: %d", 1);
- ABSL_RAW_LOG(ERROR, "RAW ERROR: %d", 1);
-}
-
-TEST(RawLoggingCompilationTest, PassingCheck) {
- ABSL_RAW_CHECK(true, "RAW CHECK");
-}
-
-// Not all platforms support output from raw log, so we don't verify any
-// particular output for RAW check failures (expecting the empty string
-// accomplishes this). This test is primarily a compilation test, but we
-// are verifying process death when EXPECT_DEATH works for a platform.
-const char kExpectedDeathOutput[] = "";
-
-TEST(RawLoggingDeathTest, FailingCheck) {
- EXPECT_DEATH_IF_SUPPORTED(ABSL_RAW_CHECK(1 == 0, "explanation"),
- kExpectedDeathOutput);
-}
-
-TEST(RawLoggingDeathTest, LogFatal) {
- EXPECT_DEATH_IF_SUPPORTED(ABSL_RAW_LOG(FATAL, "my dog has fleas"),
- kExpectedDeathOutput);
-}
-
-TEST(InternalLog, CompilationTest) {
- ABSL_INTERNAL_LOG(INFO, "Internal Log");
- std::string log_msg = "Internal Log";
- ABSL_INTERNAL_LOG(INFO, log_msg);
-
- ABSL_INTERNAL_LOG(INFO, log_msg + " 2");
-
- float d = 1.1f;
- ABSL_INTERNAL_LOG(INFO, absl::StrCat("Internal log ", 3, " + ", d));
-}
-
-TEST(InternalLogDeathTest, FailingCheck) {
- EXPECT_DEATH_IF_SUPPORTED(ABSL_INTERNAL_CHECK(1 == 0, "explanation"),
- kExpectedDeathOutput);
-}
-
-TEST(InternalLogDeathTest, LogFatal) {
- EXPECT_DEATH_IF_SUPPORTED(ABSL_INTERNAL_LOG(FATAL, "my dog has fleas"),
- kExpectedDeathOutput);
-}
-
-} // namespace
diff --git a/third_party/abseil-cpp/absl/base/spinlock_test_common.cc b/third_party/abseil-cpp/absl/base/spinlock_test_common.cc
deleted file mode 100644
index 52ecf58..0000000
--- a/third_party/abseil-cpp/absl/base/spinlock_test_common.cc
+++ /dev/null
@@ -1,272 +0,0 @@
-// Copyright 2017 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.
-
-// A bunch of threads repeatedly hash an array of ints protected by a
-// spinlock. If the spinlock is working properly, all elements of the
-// array should be equal at the end of the test.
-
-#include <cstdint>
-#include <limits>
-#include <random>
-#include <thread> // NOLINT(build/c++11)
-#include <type_traits>
-#include <vector>
-
-#include "gtest/gtest.h"
-#include "absl/base/attributes.h"
-#include "absl/base/config.h"
-#include "absl/base/internal/low_level_scheduling.h"
-#include "absl/base/internal/scheduling_mode.h"
-#include "absl/base/internal/spinlock.h"
-#include "absl/base/internal/sysinfo.h"
-#include "absl/base/macros.h"
-#include "absl/synchronization/blocking_counter.h"
-#include "absl/synchronization/notification.h"
-
-constexpr uint32_t kNumThreads = 10;
-constexpr int32_t kIters = 1000;
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-
-// This is defined outside of anonymous namespace so that it can be
-// a friend of SpinLock to access protected methods for testing.
-struct SpinLockTest {
- static uint32_t EncodeWaitCycles(int64_t wait_start_time,
- int64_t wait_end_time) {
- return SpinLock::EncodeWaitCycles(wait_start_time, wait_end_time);
- }
- static int64_t DecodeWaitCycles(uint32_t lock_value) {
- return SpinLock::DecodeWaitCycles(lock_value);
- }
-};
-
-namespace {
-
-static constexpr size_t kArrayLength = 10;
-static uint32_t values[kArrayLength];
-
-ABSL_CONST_INIT static SpinLock static_cooperative_spinlock(
- absl::kConstInit, base_internal::SCHEDULE_COOPERATIVE_AND_KERNEL);
-ABSL_CONST_INIT static SpinLock static_noncooperative_spinlock(
- absl::kConstInit, base_internal::SCHEDULE_KERNEL_ONLY);
-
-// Simple integer hash function based on the public domain lookup2 hash.
-// http://burtleburtle.net/bob/c/lookup2.c
-static uint32_t Hash32(uint32_t a, uint32_t c) {
- uint32_t b = 0x9e3779b9UL; // The golden ratio; an arbitrary value.
- a -= b; a -= c; a ^= (c >> 13);
- b -= c; b -= a; b ^= (a << 8);
- c -= a; c -= b; c ^= (b >> 13);
- a -= b; a -= c; a ^= (c >> 12);
- b -= c; b -= a; b ^= (a << 16);
- c -= a; c -= b; c ^= (b >> 5);
- a -= b; a -= c; a ^= (c >> 3);
- b -= c; b -= a; b ^= (a << 10);
- c -= a; c -= b; c ^= (b >> 15);
- return c;
-}
-
-static void TestFunction(uint32_t thread_salt, SpinLock* spinlock) {
- for (int i = 0; i < kIters; i++) {
- SpinLockHolder h(spinlock);
- for (size_t j = 0; j < kArrayLength; j++) {
- const size_t index = (j + thread_salt) % kArrayLength;
- values[index] = Hash32(values[index], thread_salt);
- std::this_thread::yield();
- }
- }
-}
-
-static void ThreadedTest(SpinLock* spinlock) {
- std::vector<std::thread> threads;
- threads.reserve(kNumThreads);
- for (uint32_t i = 0; i < kNumThreads; ++i) {
- threads.push_back(std::thread(TestFunction, i, spinlock));
- }
- for (auto& thread : threads) {
- thread.join();
- }
-
- SpinLockHolder h(spinlock);
- for (size_t i = 1; i < kArrayLength; i++) {
- EXPECT_EQ(values[0], values[i]);
- }
-}
-
-#ifndef ABSL_HAVE_THREAD_SANITIZER
-static_assert(std::is_trivially_destructible<SpinLock>(), "");
-#endif
-
-TEST(SpinLock, StackNonCooperativeDisablesScheduling) {
- SpinLock spinlock(base_internal::SCHEDULE_KERNEL_ONLY);
- spinlock.Lock();
- EXPECT_FALSE(base_internal::SchedulingGuard::ReschedulingIsAllowed());
- spinlock.Unlock();
-}
-
-TEST(SpinLock, StaticNonCooperativeDisablesScheduling) {
- static_noncooperative_spinlock.Lock();
- EXPECT_FALSE(base_internal::SchedulingGuard::ReschedulingIsAllowed());
- static_noncooperative_spinlock.Unlock();
-}
-
-TEST(SpinLock, WaitCyclesEncoding) {
- // These are implementation details not exported by SpinLock.
- const int kProfileTimestampShift = 7;
- const int kLockwordReservedShift = 3;
- const uint32_t kSpinLockSleeper = 8;
-
- // We should be able to encode up to (1^kMaxCycleBits - 1) without clamping
- // but the lower kProfileTimestampShift will be dropped.
- const int kMaxCyclesShift =
- 32 - kLockwordReservedShift + kProfileTimestampShift;
- const int64_t kMaxCycles = (int64_t{1} << kMaxCyclesShift) - 1;
-
- // These bits should be zero after encoding.
- const uint32_t kLockwordReservedMask = (1 << kLockwordReservedShift) - 1;
-
- // These bits are dropped when wait cycles are encoded.
- const int64_t kProfileTimestampMask = (1 << kProfileTimestampShift) - 1;
-
- // Test a bunch of random values
- std::default_random_engine generator;
- // Shift to avoid overflow below.
- std::uniform_int_distribution<int64_t> time_distribution(
- 0, std::numeric_limits<int64_t>::max() >> 3);
- std::uniform_int_distribution<int64_t> cycle_distribution(0, kMaxCycles);
-
- for (int i = 0; i < 100; i++) {
- int64_t start_time = time_distribution(generator);
- int64_t cycles = cycle_distribution(generator);
- int64_t end_time = start_time + cycles;
- uint32_t lock_value = SpinLockTest::EncodeWaitCycles(start_time, end_time);
- EXPECT_EQ(0u, lock_value & kLockwordReservedMask);
- int64_t decoded = SpinLockTest::DecodeWaitCycles(lock_value);
- EXPECT_EQ(0, decoded & kProfileTimestampMask);
- EXPECT_EQ(cycles & ~kProfileTimestampMask, decoded);
- }
-
- // Test corner cases
- int64_t start_time = time_distribution(generator);
- EXPECT_EQ(kSpinLockSleeper,
- SpinLockTest::EncodeWaitCycles(start_time, start_time));
- EXPECT_EQ(0, SpinLockTest::DecodeWaitCycles(0));
- EXPECT_EQ(0, SpinLockTest::DecodeWaitCycles(kLockwordReservedMask));
- EXPECT_EQ(kMaxCycles & ~kProfileTimestampMask,
- SpinLockTest::DecodeWaitCycles(~kLockwordReservedMask));
-
- // Check that we cannot produce kSpinLockSleeper during encoding.
- int64_t sleeper_cycles =
- kSpinLockSleeper << (kProfileTimestampShift - kLockwordReservedShift);
- uint32_t sleeper_value =
- SpinLockTest::EncodeWaitCycles(start_time, start_time + sleeper_cycles);
- EXPECT_NE(sleeper_value, kSpinLockSleeper);
-
- // Test clamping
- uint32_t max_value =
- SpinLockTest::EncodeWaitCycles(start_time, start_time + kMaxCycles);
- int64_t max_value_decoded = SpinLockTest::DecodeWaitCycles(max_value);
- int64_t expected_max_value_decoded = kMaxCycles & ~kProfileTimestampMask;
- EXPECT_EQ(expected_max_value_decoded, max_value_decoded);
-
- const int64_t step = (1 << kProfileTimestampShift);
- uint32_t after_max_value =
- SpinLockTest::EncodeWaitCycles(start_time, start_time + kMaxCycles + step);
- int64_t after_max_value_decoded =
- SpinLockTest::DecodeWaitCycles(after_max_value);
- EXPECT_EQ(expected_max_value_decoded, after_max_value_decoded);
-
- uint32_t before_max_value = SpinLockTest::EncodeWaitCycles(
- start_time, start_time + kMaxCycles - step);
- int64_t before_max_value_decoded =
- SpinLockTest::DecodeWaitCycles(before_max_value);
- EXPECT_GT(expected_max_value_decoded, before_max_value_decoded);
-}
-
-TEST(SpinLockWithThreads, StackSpinLock) {
- SpinLock spinlock;
- ThreadedTest(&spinlock);
-}
-
-TEST(SpinLockWithThreads, StackCooperativeSpinLock) {
- SpinLock spinlock(base_internal::SCHEDULE_COOPERATIVE_AND_KERNEL);
- ThreadedTest(&spinlock);
-}
-
-TEST(SpinLockWithThreads, StackNonCooperativeSpinLock) {
- SpinLock spinlock(base_internal::SCHEDULE_KERNEL_ONLY);
- ThreadedTest(&spinlock);
-}
-
-TEST(SpinLockWithThreads, StaticCooperativeSpinLock) {
- ThreadedTest(&static_cooperative_spinlock);
-}
-
-TEST(SpinLockWithThreads, StaticNonCooperativeSpinLock) {
- ThreadedTest(&static_noncooperative_spinlock);
-}
-
-TEST(SpinLockWithThreads, DoesNotDeadlock) {
- struct Helper {
- static void NotifyThenLock(Notification* locked, SpinLock* spinlock,
- BlockingCounter* b) {
- locked->WaitForNotification(); // Wait for LockThenWait() to hold "s".
- b->DecrementCount();
- SpinLockHolder l(spinlock);
- }
-
- static void LockThenWait(Notification* locked, SpinLock* spinlock,
- BlockingCounter* b) {
- SpinLockHolder l(spinlock);
- locked->Notify();
- b->Wait();
- }
-
- static void DeadlockTest(SpinLock* spinlock, int num_spinners) {
- Notification locked;
- BlockingCounter counter(num_spinners);
- std::vector<std::thread> threads;
-
- threads.push_back(
- std::thread(Helper::LockThenWait, &locked, spinlock, &counter));
- for (int i = 0; i < num_spinners; ++i) {
- threads.push_back(
- std::thread(Helper::NotifyThenLock, &locked, spinlock, &counter));
- }
-
- for (auto& thread : threads) {
- thread.join();
- }
- }
- };
-
- SpinLock stack_cooperative_spinlock(
- base_internal::SCHEDULE_COOPERATIVE_AND_KERNEL);
- SpinLock stack_noncooperative_spinlock(base_internal::SCHEDULE_KERNEL_ONLY);
- Helper::DeadlockTest(&stack_cooperative_spinlock,
- base_internal::NumCPUs() * 2);
- Helper::DeadlockTest(&stack_noncooperative_spinlock,
- base_internal::NumCPUs() * 2);
- Helper::DeadlockTest(&static_cooperative_spinlock,
- base_internal::NumCPUs() * 2);
- Helper::DeadlockTest(&static_noncooperative_spinlock,
- base_internal::NumCPUs() * 2);
-}
-
-} // namespace
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/base/thread_annotations.h b/third_party/abseil-cpp/absl/base/thread_annotations.h
deleted file mode 100644
index 4a3f3e3..0000000
--- a/third_party/abseil-cpp/absl/base/thread_annotations.h
+++ /dev/null
@@ -1,333 +0,0 @@
-// Copyright 2017 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.
-//
-// -----------------------------------------------------------------------------
-// File: thread_annotations.h
-// -----------------------------------------------------------------------------
-//
-// This header file contains macro definitions for thread safety annotations
-// that allow developers to document the locking policies of multi-threaded
-// code. The annotations can also help program analysis tools to identify
-// potential thread safety issues.
-//
-// These annotations are implemented using compiler attributes. Using the macros
-// defined here instead of raw attributes allow for portability and future
-// compatibility.
-//
-// When referring to mutexes in the arguments of the attributes, you should
-// use variable names or more complex expressions (e.g. my_object->mutex_)
-// that evaluate to a concrete mutex object whenever possible. If the mutex
-// you want to refer to is not in scope, you may use a member pointer
-// (e.g. &MyClass::mutex_) to refer to a mutex in some (unknown) object.
-
-#ifndef ABSL_BASE_THREAD_ANNOTATIONS_H_
-#define ABSL_BASE_THREAD_ANNOTATIONS_H_
-
-#include "absl/base/attributes.h"
-#include "absl/base/config.h"
-
-// ABSL_GUARDED_BY()
-//
-// Documents if a shared field or global variable needs to be protected by a
-// mutex. ABSL_GUARDED_BY() allows the user to specify a particular mutex that
-// should be held when accessing the annotated variable.
-//
-// Although this annotation (and ABSL_PT_GUARDED_BY, below) cannot be applied to
-// local variables, a local variable and its associated mutex can often be
-// combined into a small class or struct, thereby allowing the annotation.
-//
-// Example:
-//
-// class Foo {
-// Mutex mu_;
-// int p1_ ABSL_GUARDED_BY(mu_);
-// ...
-// };
-#if ABSL_HAVE_ATTRIBUTE(guarded_by)
-#define ABSL_GUARDED_BY(x) __attribute__((guarded_by(x)))
-#else
-#define ABSL_GUARDED_BY(x)
-#endif
-
-// ABSL_PT_GUARDED_BY()
-//
-// Documents if the memory location pointed to by a pointer should be guarded
-// by a mutex when dereferencing the pointer.
-//
-// Example:
-// class Foo {
-// Mutex mu_;
-// int *p1_ ABSL_PT_GUARDED_BY(mu_);
-// ...
-// };
-//
-// Note that a pointer variable to a shared memory location could itself be a
-// shared variable.
-//
-// Example:
-//
-// // `q_`, guarded by `mu1_`, points to a shared memory location that is
-// // guarded by `mu2_`:
-// int *q_ ABSL_GUARDED_BY(mu1_) ABSL_PT_GUARDED_BY(mu2_);
-#if ABSL_HAVE_ATTRIBUTE(pt_guarded_by)
-#define ABSL_PT_GUARDED_BY(x) __attribute__((pt_guarded_by(x)))
-#else
-#define ABSL_PT_GUARDED_BY(x)
-#endif
-
-// ABSL_ACQUIRED_AFTER() / ABSL_ACQUIRED_BEFORE()
-//
-// Documents the acquisition order between locks that can be held
-// simultaneously by a thread. For any two locks that need to be annotated
-// to establish an acquisition order, only one of them needs the annotation.
-// (i.e. You don't have to annotate both locks with both ABSL_ACQUIRED_AFTER
-// and ABSL_ACQUIRED_BEFORE.)
-//
-// As with ABSL_GUARDED_BY, this is only applicable to mutexes that are shared
-// fields or global variables.
-//
-// Example:
-//
-// Mutex m1_;
-// Mutex m2_ ABSL_ACQUIRED_AFTER(m1_);
-#if ABSL_HAVE_ATTRIBUTE(acquired_after)
-#define ABSL_ACQUIRED_AFTER(...) __attribute__((acquired_after(__VA_ARGS__)))
-#else
-#define ABSL_ACQUIRED_AFTER(...)
-#endif
-
-#if ABSL_HAVE_ATTRIBUTE(acquired_before)
-#define ABSL_ACQUIRED_BEFORE(...) __attribute__((acquired_before(__VA_ARGS__)))
-#else
-#define ABSL_ACQUIRED_BEFORE(...)
-#endif
-
-// ABSL_EXCLUSIVE_LOCKS_REQUIRED() / ABSL_SHARED_LOCKS_REQUIRED()
-//
-// Documents a function that expects a mutex to be held prior to entry.
-// The mutex is expected to be held both on entry to, and exit from, the
-// function.
-//
-// An exclusive lock allows read-write access to the guarded data member(s), and
-// only one thread can acquire a lock exclusively at any one time. A shared lock
-// allows read-only access, and any number of threads can acquire a shared lock
-// concurrently.
-//
-// Generally, non-const methods should be annotated with
-// ABSL_EXCLUSIVE_LOCKS_REQUIRED, while const methods should be annotated with
-// ABSL_SHARED_LOCKS_REQUIRED.
-//
-// Example:
-//
-// Mutex mu1, mu2;
-// int a ABSL_GUARDED_BY(mu1);
-// int b ABSL_GUARDED_BY(mu2);
-//
-// void foo() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu1, mu2) { ... }
-// void bar() const ABSL_SHARED_LOCKS_REQUIRED(mu1, mu2) { ... }
-#if ABSL_HAVE_ATTRIBUTE(exclusive_locks_required)
-#define ABSL_EXCLUSIVE_LOCKS_REQUIRED(...) \
- __attribute__((exclusive_locks_required(__VA_ARGS__)))
-#else
-#define ABSL_EXCLUSIVE_LOCKS_REQUIRED(...)
-#endif
-
-#if ABSL_HAVE_ATTRIBUTE(shared_locks_required)
-#define ABSL_SHARED_LOCKS_REQUIRED(...) \
- __attribute__((shared_locks_required(__VA_ARGS__)))
-#else
-#define ABSL_SHARED_LOCKS_REQUIRED(...)
-#endif
-
-// ABSL_LOCKS_EXCLUDED()
-//
-// Documents the locks that cannot be held by callers of this function, as they
-// might be acquired by this function (Abseil's `Mutex` locks are
-// non-reentrant).
-#if ABSL_HAVE_ATTRIBUTE(locks_excluded)
-#define ABSL_LOCKS_EXCLUDED(...) __attribute__((locks_excluded(__VA_ARGS__)))
-#else
-#define ABSL_LOCKS_EXCLUDED(...)
-#endif
-
-// ABSL_LOCK_RETURNED()
-//
-// Documents a function that returns a mutex without acquiring it. For example,
-// a public getter method that returns a pointer to a private mutex should
-// be annotated with ABSL_LOCK_RETURNED.
-#if ABSL_HAVE_ATTRIBUTE(lock_returned)
-#define ABSL_LOCK_RETURNED(x) __attribute__((lock_returned(x)))
-#else
-#define ABSL_LOCK_RETURNED(x)
-#endif
-
-// ABSL_LOCKABLE
-//
-// Documents if a class/type is a lockable type (such as the `Mutex` class).
-#if ABSL_HAVE_ATTRIBUTE(lockable)
-#define ABSL_LOCKABLE __attribute__((lockable))
-#else
-#define ABSL_LOCKABLE
-#endif
-
-// ABSL_SCOPED_LOCKABLE
-//
-// Documents if a class does RAII locking (such as the `MutexLock` class).
-// The constructor should use `LOCK_FUNCTION()` to specify the mutex that is
-// acquired, and the destructor should use `UNLOCK_FUNCTION()` with no
-// arguments; the analysis will assume that the destructor unlocks whatever the
-// constructor locked.
-#if ABSL_HAVE_ATTRIBUTE(scoped_lockable)
-#define ABSL_SCOPED_LOCKABLE __attribute__((scoped_lockable))
-#else
-#define ABSL_SCOPED_LOCKABLE
-#endif
-
-// ABSL_EXCLUSIVE_LOCK_FUNCTION()
-//
-// Documents functions that acquire a lock in the body of a function, and do
-// not release it.
-#if ABSL_HAVE_ATTRIBUTE(exclusive_lock_function)
-#define ABSL_EXCLUSIVE_LOCK_FUNCTION(...) \
- __attribute__((exclusive_lock_function(__VA_ARGS__)))
-#else
-#define ABSL_EXCLUSIVE_LOCK_FUNCTION(...)
-#endif
-
-// ABSL_SHARED_LOCK_FUNCTION()
-//
-// Documents functions that acquire a shared (reader) lock in the body of a
-// function, and do not release it.
-#if ABSL_HAVE_ATTRIBUTE(shared_lock_function)
-#define ABSL_SHARED_LOCK_FUNCTION(...) \
- __attribute__((shared_lock_function(__VA_ARGS__)))
-#else
-#define ABSL_SHARED_LOCK_FUNCTION(...)
-#endif
-
-// ABSL_UNLOCK_FUNCTION()
-//
-// Documents functions that expect a lock to be held on entry to the function,
-// and release it in the body of the function.
-#if ABSL_HAVE_ATTRIBUTE(unlock_function)
-#define ABSL_UNLOCK_FUNCTION(...) __attribute__((unlock_function(__VA_ARGS__)))
-#else
-#define ABSL_UNLOCK_FUNCTION(...)
-#endif
-
-// ABSL_EXCLUSIVE_TRYLOCK_FUNCTION() / ABSL_SHARED_TRYLOCK_FUNCTION()
-//
-// Documents functions that try to acquire a lock, and return success or failure
-// (or a non-boolean value that can be interpreted as a boolean).
-// The first argument should be `true` for functions that return `true` on
-// success, or `false` for functions that return `false` on success. The second
-// argument specifies the mutex that is locked on success. If unspecified, this
-// mutex is assumed to be `this`.
-#if ABSL_HAVE_ATTRIBUTE(exclusive_trylock_function)
-#define ABSL_EXCLUSIVE_TRYLOCK_FUNCTION(...) \
- __attribute__((exclusive_trylock_function(__VA_ARGS__)))
-#else
-#define ABSL_EXCLUSIVE_TRYLOCK_FUNCTION(...)
-#endif
-
-#if ABSL_HAVE_ATTRIBUTE(shared_trylock_function)
-#define ABSL_SHARED_TRYLOCK_FUNCTION(...) \
- __attribute__((shared_trylock_function(__VA_ARGS__)))
-#else
-#define ABSL_SHARED_TRYLOCK_FUNCTION(...)
-#endif
-
-// ABSL_ASSERT_EXCLUSIVE_LOCK() / ABSL_ASSERT_SHARED_LOCK()
-//
-// Documents functions that dynamically check to see if a lock is held, and fail
-// if it is not held.
-#if ABSL_HAVE_ATTRIBUTE(assert_exclusive_lock)
-#define ABSL_ASSERT_EXCLUSIVE_LOCK(...) \
- __attribute__((assert_exclusive_lock(__VA_ARGS__)))
-#else
-#define ABSL_ASSERT_EXCLUSIVE_LOCK(...)
-#endif
-
-#if ABSL_HAVE_ATTRIBUTE(assert_shared_lock)
-#define ABSL_ASSERT_SHARED_LOCK(...) \
- __attribute__((assert_shared_lock(__VA_ARGS__)))
-#else
-#define ABSL_ASSERT_SHARED_LOCK(...)
-#endif
-
-// ABSL_NO_THREAD_SAFETY_ANALYSIS
-//
-// Turns off thread safety checking within the body of a particular function.
-// This annotation is used to mark functions that are known to be correct, but
-// the locking behavior is more complicated than the analyzer can handle.
-#if ABSL_HAVE_ATTRIBUTE(no_thread_safety_analysis)
-#define ABSL_NO_THREAD_SAFETY_ANALYSIS \
- __attribute__((no_thread_safety_analysis))
-#else
-#define ABSL_NO_THREAD_SAFETY_ANALYSIS
-#endif
-
-//------------------------------------------------------------------------------
-// Tool-Supplied Annotations
-//------------------------------------------------------------------------------
-
-// ABSL_TS_UNCHECKED should be placed around lock expressions that are not valid
-// C++ syntax, but which are present for documentation purposes. These
-// annotations will be ignored by the analysis.
-#define ABSL_TS_UNCHECKED(x) ""
-
-// ABSL_TS_FIXME is used to mark lock expressions that are not valid C++ syntax.
-// It is used by automated tools to mark and disable invalid expressions.
-// The annotation should either be fixed, or changed to ABSL_TS_UNCHECKED.
-#define ABSL_TS_FIXME(x) ""
-
-// Like ABSL_NO_THREAD_SAFETY_ANALYSIS, this turns off checking within the body
-// of a particular function. However, this attribute is used to mark functions
-// that are incorrect and need to be fixed. It is used by automated tools to
-// avoid breaking the build when the analysis is updated.
-// Code owners are expected to eventually fix the routine.
-#define ABSL_NO_THREAD_SAFETY_ANALYSIS_FIXME ABSL_NO_THREAD_SAFETY_ANALYSIS
-
-// Similar to ABSL_NO_THREAD_SAFETY_ANALYSIS_FIXME, this macro marks a
-// ABSL_GUARDED_BY annotation that needs to be fixed, because it is producing
-// thread safety warning. It disables the ABSL_GUARDED_BY.
-#define ABSL_GUARDED_BY_FIXME(x)
-
-// Disables warnings for a single read operation. This can be used to avoid
-// warnings when it is known that the read is not actually involved in a race,
-// but the compiler cannot confirm that.
-#define ABSL_TS_UNCHECKED_READ(x) absl::base_internal::ts_unchecked_read(x)
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace base_internal {
-
-// Takes a reference to a guarded data member, and returns an unguarded
-// reference.
-// Do not use this function directly, use ABSL_TS_UNCHECKED_READ instead.
-template <typename T>
-inline const T& ts_unchecked_read(const T& v) ABSL_NO_THREAD_SAFETY_ANALYSIS {
- return v;
-}
-
-template <typename T>
-inline T& ts_unchecked_read(T& v) ABSL_NO_THREAD_SAFETY_ANALYSIS {
- return v;
-}
-
-} // namespace base_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_BASE_THREAD_ANNOTATIONS_H_
diff --git a/third_party/abseil-cpp/absl/base/throw_delegate_test.cc b/third_party/abseil-cpp/absl/base/throw_delegate_test.cc
deleted file mode 100644
index 5ba4ce5..0000000
--- a/third_party/abseil-cpp/absl/base/throw_delegate_test.cc
+++ /dev/null
@@ -1,107 +0,0 @@
-// Copyright 2017 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/throw_delegate.h"
-
-#include <functional>
-#include <new>
-#include <stdexcept>
-
-#include "absl/base/config.h"
-#include "gtest/gtest.h"
-
-namespace {
-
-using absl::base_internal::ThrowStdLogicError;
-using absl::base_internal::ThrowStdInvalidArgument;
-using absl::base_internal::ThrowStdDomainError;
-using absl::base_internal::ThrowStdLengthError;
-using absl::base_internal::ThrowStdOutOfRange;
-using absl::base_internal::ThrowStdRuntimeError;
-using absl::base_internal::ThrowStdRangeError;
-using absl::base_internal::ThrowStdOverflowError;
-using absl::base_internal::ThrowStdUnderflowError;
-using absl::base_internal::ThrowStdBadFunctionCall;
-using absl::base_internal::ThrowStdBadAlloc;
-
-constexpr const char* what_arg = "The quick brown fox jumps over the lazy dog";
-
-template <typename E>
-void ExpectThrowChar(void (*f)(const char*)) {
-#ifdef ABSL_HAVE_EXCEPTIONS
- try {
- f(what_arg);
- FAIL() << "Didn't throw";
- } catch (const E& e) {
- EXPECT_STREQ(e.what(), what_arg);
- }
-#else
- EXPECT_DEATH_IF_SUPPORTED(f(what_arg), what_arg);
-#endif
-}
-
-template <typename E>
-void ExpectThrowString(void (*f)(const std::string&)) {
-#ifdef ABSL_HAVE_EXCEPTIONS
- try {
- f(what_arg);
- FAIL() << "Didn't throw";
- } catch (const E& e) {
- EXPECT_STREQ(e.what(), what_arg);
- }
-#else
- EXPECT_DEATH_IF_SUPPORTED(f(what_arg), what_arg);
-#endif
-}
-
-template <typename E>
-void ExpectThrowNoWhat(void (*f)()) {
-#ifdef ABSL_HAVE_EXCEPTIONS
- try {
- f();
- FAIL() << "Didn't throw";
- } catch (const E& e) {
- }
-#else
- EXPECT_DEATH_IF_SUPPORTED(f(), "");
-#endif
-}
-
-TEST(ThrowHelper, Test) {
- // Not using EXPECT_THROW because we want to check the .what() message too.
- ExpectThrowChar<std::logic_error>(ThrowStdLogicError);
- ExpectThrowChar<std::invalid_argument>(ThrowStdInvalidArgument);
- ExpectThrowChar<std::domain_error>(ThrowStdDomainError);
- ExpectThrowChar<std::length_error>(ThrowStdLengthError);
- ExpectThrowChar<std::out_of_range>(ThrowStdOutOfRange);
- ExpectThrowChar<std::runtime_error>(ThrowStdRuntimeError);
- ExpectThrowChar<std::range_error>(ThrowStdRangeError);
- ExpectThrowChar<std::overflow_error>(ThrowStdOverflowError);
- ExpectThrowChar<std::underflow_error>(ThrowStdUnderflowError);
-
- ExpectThrowString<std::logic_error>(ThrowStdLogicError);
- ExpectThrowString<std::invalid_argument>(ThrowStdInvalidArgument);
- ExpectThrowString<std::domain_error>(ThrowStdDomainError);
- ExpectThrowString<std::length_error>(ThrowStdLengthError);
- ExpectThrowString<std::out_of_range>(ThrowStdOutOfRange);
- ExpectThrowString<std::runtime_error>(ThrowStdRuntimeError);
- ExpectThrowString<std::range_error>(ThrowStdRangeError);
- ExpectThrowString<std::overflow_error>(ThrowStdOverflowError);
- ExpectThrowString<std::underflow_error>(ThrowStdUnderflowError);
-
- ExpectThrowNoWhat<std::bad_function_call>(ThrowStdBadFunctionCall);
- ExpectThrowNoWhat<std::bad_alloc>(ThrowStdBadAlloc);
-}
-
-} // namespace
diff --git a/third_party/abseil-cpp/absl/cleanup/BUILD.bazel b/third_party/abseil-cpp/absl/cleanup/BUILD.bazel
deleted file mode 100644
index 2154d9f..0000000
--- a/third_party/abseil-cpp/absl/cleanup/BUILD.bazel
+++ /dev/null
@@ -1,65 +0,0 @@
-# Copyright 2021 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.
-
-load(
- "//absl:copts/configure_copts.bzl",
- "ABSL_DEFAULT_COPTS",
- "ABSL_DEFAULT_LINKOPTS",
- "ABSL_TEST_COPTS",
-)
-
-package(default_visibility = ["//visibility:public"])
-
-licenses(["notice"])
-
-cc_library(
- name = "cleanup_internal",
- hdrs = ["internal/cleanup.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- "//absl/base:base_internal",
- "//absl/base:core_headers",
- "//absl/utility",
- ],
-)
-
-cc_library(
- name = "cleanup",
- hdrs = [
- "cleanup.h",
- ],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":cleanup_internal",
- "//absl/base:config",
- "//absl/base:core_headers",
- ],
-)
-
-cc_test(
- name = "cleanup_test",
- size = "small",
- srcs = [
- "cleanup_test.cc",
- ],
- copts = ABSL_TEST_COPTS,
- deps = [
- ":cleanup",
- "//absl/base:config",
- "//absl/utility",
- "@com_google_googletest//:gtest_main",
- ],
-)
diff --git a/third_party/abseil-cpp/absl/cleanup/BUILD.gn b/third_party/abseil-cpp/absl/cleanup/BUILD.gn
deleted file mode 100644
index 3d3fa88..0000000
--- a/third_party/abseil-cpp/absl/cleanup/BUILD.gn
+++ /dev/null
@@ -1,33 +0,0 @@
-# Copyright 2021 The Chromium Authors
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-import("//third_party/abseil-cpp/absl.gni")
-
-absl_source_set("cleanup_internal") {
- public = [ "internal/cleanup.h" ]
- deps = [
- "//third_party/abseil-cpp/absl/base:base_internal",
- "//third_party/abseil-cpp/absl/base:core_headers",
- "//third_party/abseil-cpp/absl/utility",
- ]
- visibility = [ "//third_party/abseil-cpp/absl/*" ]
-}
-
-absl_source_set("cleanup") {
- public = [ "cleanup.h" ]
- deps = [
- ":cleanup_internal",
- "//third_party/abseil-cpp/absl/base:config",
- "//third_party/abseil-cpp/absl/base:core_headers",
- ]
-}
-
-absl_test("cleanup_test") {
- sources = [ "cleanup_test.cc" ]
- deps = [
- ":cleanup",
- "//third_party/abseil-cpp/absl/base:config",
- "//third_party/abseil-cpp/absl/utility",
- ]
-}
diff --git a/third_party/abseil-cpp/absl/cleanup/CMakeLists.txt b/third_party/abseil-cpp/absl/cleanup/CMakeLists.txt
deleted file mode 100644
index f5af40b..0000000
--- a/third_party/abseil-cpp/absl/cleanup/CMakeLists.txt
+++ /dev/null
@@ -1,56 +0,0 @@
-# Copyright 2021 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.
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- cleanup_internal
- HDRS
- "internal/cleanup.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::base_internal
- absl::core_headers
- absl::utility
- PUBLIC
-)
-
-absl_cc_library(
- NAME
- cleanup
- HDRS
- "cleanup.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::cleanup_internal
- absl::config
- absl::core_headers
- PUBLIC
-)
-
-absl_cc_test(
- NAME
- cleanup_test
- SRCS
- "cleanup_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::cleanup
- absl::config
- absl::utility
- GTest::gmock_main
-)
diff --git a/third_party/abseil-cpp/absl/cleanup/cleanup.h b/third_party/abseil-cpp/absl/cleanup/cleanup.h
deleted file mode 100644
index 960ccd0..0000000
--- a/third_party/abseil-cpp/absl/cleanup/cleanup.h
+++ /dev/null
@@ -1,140 +0,0 @@
-// Copyright 2021 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.
-//
-// -----------------------------------------------------------------------------
-// File: cleanup.h
-// -----------------------------------------------------------------------------
-//
-// `absl::Cleanup` implements the scope guard idiom, invoking the contained
-// callback's `operator()() &&` on scope exit.
-//
-// Example:
-//
-// ```
-// absl::Status CopyGoodData(const char* source_path, const char* sink_path) {
-// FILE* source_file = fopen(source_path, "r");
-// if (source_file == nullptr) {
-// return absl::NotFoundError("No source file"); // No cleanups execute
-// }
-//
-// // C++17 style cleanup using class template argument deduction
-// absl::Cleanup source_closer = [source_file] { fclose(source_file); };
-//
-// FILE* sink_file = fopen(sink_path, "w");
-// if (sink_file == nullptr) {
-// return absl::NotFoundError("No sink file"); // First cleanup executes
-// }
-//
-// // C++11 style cleanup using the factory function
-// auto sink_closer = absl::MakeCleanup([sink_file] { fclose(sink_file); });
-//
-// Data data;
-// while (ReadData(source_file, &data)) {
-// if (!data.IsGood()) {
-// absl::Status result = absl::FailedPreconditionError("Read bad data");
-// return result; // Both cleanups execute
-// }
-// SaveData(sink_file, &data);
-// }
-//
-// return absl::OkStatus(); // Both cleanups execute
-// }
-// ```
-//
-// Methods:
-//
-// `std::move(cleanup).Cancel()` will prevent the callback from executing.
-//
-// `std::move(cleanup).Invoke()` will execute the callback early, before
-// destruction, and prevent the callback from executing in the destructor.
-//
-// Usage:
-//
-// `absl::Cleanup` is not an interface type. It is only intended to be used
-// within the body of a function. It is not a value type and instead models a
-// control flow construct. Check out `defer` in Golang for something similar.
-
-#ifndef ABSL_CLEANUP_CLEANUP_H_
-#define ABSL_CLEANUP_CLEANUP_H_
-
-#include <utility>
-
-#include "absl/base/config.h"
-#include "absl/base/macros.h"
-#include "absl/cleanup/internal/cleanup.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-
-template <typename Arg, typename Callback = void()>
-class ABSL_MUST_USE_RESULT Cleanup final {
- static_assert(cleanup_internal::WasDeduced<Arg>(),
- "Explicit template parameters are not supported.");
-
- static_assert(cleanup_internal::ReturnsVoid<Callback>(),
- "Callbacks that return values are not supported.");
-
- public:
- Cleanup(Callback callback) : storage_(std::move(callback)) {} // NOLINT
-
- Cleanup(Cleanup&& other) = default;
-
- void Cancel() && {
- ABSL_HARDENING_ASSERT(storage_.IsCallbackEngaged());
- storage_.DestroyCallback();
- }
-
- void Invoke() && {
- ABSL_HARDENING_ASSERT(storage_.IsCallbackEngaged());
- storage_.InvokeCallback();
- storage_.DestroyCallback();
- }
-
- ~Cleanup() {
- if (storage_.IsCallbackEngaged()) {
- storage_.InvokeCallback();
- storage_.DestroyCallback();
- }
- }
-
- private:
- cleanup_internal::Storage<Callback> storage_;
-};
-
-// `absl::Cleanup c = /* callback */;`
-//
-// C++17 type deduction API for creating an instance of `absl::Cleanup`
-#if defined(ABSL_HAVE_CLASS_TEMPLATE_ARGUMENT_DEDUCTION)
-template <typename Callback>
-Cleanup(Callback callback) -> Cleanup<cleanup_internal::Tag, Callback>;
-#endif // defined(ABSL_HAVE_CLASS_TEMPLATE_ARGUMENT_DEDUCTION)
-
-// `auto c = absl::MakeCleanup(/* callback */);`
-//
-// C++11 type deduction API for creating an instance of `absl::Cleanup`
-template <typename... Args, typename Callback>
-absl::Cleanup<cleanup_internal::Tag, Callback> MakeCleanup(Callback callback) {
- static_assert(cleanup_internal::WasDeduced<cleanup_internal::Tag, Args...>(),
- "Explicit template parameters are not supported.");
-
- static_assert(cleanup_internal::ReturnsVoid<Callback>(),
- "Callbacks that return values are not supported.");
-
- return {std::move(callback)};
-}
-
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CLEANUP_CLEANUP_H_
diff --git a/third_party/abseil-cpp/absl/cleanup/cleanup_test.cc b/third_party/abseil-cpp/absl/cleanup/cleanup_test.cc
deleted file mode 100644
index 46b8858..0000000
--- a/third_party/abseil-cpp/absl/cleanup/cleanup_test.cc
+++ /dev/null
@@ -1,311 +0,0 @@
-// Copyright 2021 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/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));
- }
-};
-
-// `FunctorClass` is a type used for testing `absl::Cleanup`. It is intended to
-// represent users that make their own move-only callback types outside of
-// `std::function` and lambda literals.
-class FunctorClass {
- using Callback = std::function<void()>;
-
- public:
- explicit FunctorClass(Callback callback) : callback_(std::move(callback)) {}
-
- FunctorClass(FunctorClass&& other)
- : callback_(absl::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 // defined(ABSL_HAVE_CLASS_TEMPLATE_ARGUMENT_DEDUCTION)
-
-TYPED_TEST(CleanupTest, BasicUsage) {
- bool called = false;
-
- {
- auto cleanup =
- absl::MakeCleanup(TypeParam::AsCallback([&called] { called = true; }));
- EXPECT_FALSE(called); // Constructor shouldn't invoke the callback
- }
-
- EXPECT_TRUE(called); // Destructor should invoke the callback
-}
-
-TYPED_TEST(CleanupTest, BasicUsageWithFunctionPointer) {
- fn_ptr_called = false;
-
- {
- auto cleanup = absl::MakeCleanup(TypeParam::AsCallback(&FnPtrFunction));
- EXPECT_FALSE(fn_ptr_called); // Constructor shouldn't invoke the callback
- }
-
- EXPECT_TRUE(fn_ptr_called); // Destructor should invoke the callback
-}
-
-TYPED_TEST(CleanupTest, Cancel) {
- bool called = false;
-
- {
- auto cleanup =
- absl::MakeCleanup(TypeParam::AsCallback([&called] { called = true; }));
- EXPECT_FALSE(called); // Constructor shouldn't invoke the callback
-
- std::move(cleanup).Cancel();
- EXPECT_FALSE(called); // Cancel shouldn't invoke the callback
- }
-
- EXPECT_FALSE(called); // Destructor shouldn't invoke the callback
-}
-
-TYPED_TEST(CleanupTest, Invoke) {
- bool called = false;
-
- {
- auto cleanup =
- absl::MakeCleanup(TypeParam::AsCallback([&called] { called = true; }));
- EXPECT_FALSE(called); // Constructor shouldn't invoke the callback
-
- std::move(cleanup).Invoke();
- EXPECT_TRUE(called); // Invoke should invoke the callback
-
- called = false; // Reset tracker before destructor runs
- }
-
- EXPECT_FALSE(called); // Destructor shouldn't invoke the callback
-}
-
-TYPED_TEST(CleanupTest, Move) {
- bool called = false;
-
- {
- auto moved_from_cleanup =
- absl::MakeCleanup(TypeParam::AsCallback([&called] { called = true; }));
- EXPECT_FALSE(called); // Constructor shouldn't invoke the callback
-
- {
- auto moved_to_cleanup = std::move(moved_from_cleanup);
- EXPECT_FALSE(called); // Move shouldn't invoke the callback
- }
-
- EXPECT_TRUE(called); // Destructor should invoke the callback
-
- called = false; // Reset tracker before destructor runs
- }
-
- EXPECT_FALSE(called); // Destructor shouldn't invoke the callback
-}
-
-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); // Engaged cleanup destroys
-}
-
-TYPED_TEST(CleanupTest, CancelDestroys) {
- {
- auto cleanup =
- absl::MakeCleanup(TypeParam::AsCallback(DestructionCounter()));
- DestructionCount = 0;
-
- std::move(cleanup).Cancel();
- EXPECT_EQ(DestructionCount, 1); // Cancel destroys
- }
-
- EXPECT_EQ(DestructionCount, 1); // Canceled cleanup does not double destroy
-}
-
-TYPED_TEST(CleanupTest, InvokeDestroys) {
- {
- auto cleanup =
- absl::MakeCleanup(TypeParam::AsCallback(DestructionCounter()));
- DestructionCount = 0;
-
- std::move(cleanup).Invoke();
- EXPECT_EQ(DestructionCount, 1); // Invoke destroys
- }
-
- EXPECT_EQ(DestructionCount, 1); // Invoked cleanup does not double destroy
-}
-
-} // namespace
diff --git a/third_party/abseil-cpp/absl/cleanup/internal/cleanup.h b/third_party/abseil-cpp/absl/cleanup/internal/cleanup.h
deleted file mode 100644
index 2783fcb..0000000
--- a/third_party/abseil-cpp/absl/cleanup/internal/cleanup.h
+++ /dev/null
@@ -1,100 +0,0 @@
-// Copyright 2021 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_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) {
- // Placement-new into a character buffer is used for eager destruction when
- // the cleanup is invoked or cancelled. To ensure this optimizes well, the
- // behavior is implemented locally instead of using an absl::optional.
- ::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)];
-};
-
-} // namespace cleanup_internal
-
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CLEANUP_INTERNAL_CLEANUP_H_
diff --git a/third_party/abseil-cpp/absl/container/BUILD.bazel b/third_party/abseil-cpp/absl/container/BUILD.bazel
deleted file mode 100644
index 70febdd..0000000
--- a/third_party/abseil-cpp/absl/container/BUILD.bazel
+++ /dev/null
@@ -1,1027 +0,0 @@
-#
-# Copyright 2017 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.
-#
-
-load(
- "//absl:copts/configure_copts.bzl",
- "ABSL_DEFAULT_COPTS",
- "ABSL_DEFAULT_LINKOPTS",
- "ABSL_TEST_COPTS",
-)
-
-package(default_visibility = ["//visibility:public"])
-
-licenses(["notice"])
-
-cc_library(
- name = "compressed_tuple",
- hdrs = ["internal/compressed_tuple.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- "//absl/utility",
- ],
-)
-
-cc_test(
- name = "compressed_tuple_test",
- srcs = ["internal/compressed_tuple_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":compressed_tuple",
- ":test_instance_tracker",
- "//absl/memory",
- "//absl/types:any",
- "//absl/types:optional",
- "//absl/utility",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_library(
- name = "fixed_array",
- hdrs = ["fixed_array.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":compressed_tuple",
- "//absl/algorithm",
- "//absl/base:config",
- "//absl/base:core_headers",
- "//absl/base:dynamic_annotations",
- "//absl/base:throw_delegate",
- "//absl/memory",
- ],
-)
-
-cc_test(
- name = "fixed_array_test",
- srcs = ["fixed_array_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":counting_allocator",
- ":fixed_array",
- "//absl/base:config",
- "//absl/base:exception_testing",
- "//absl/hash:hash_testing",
- "//absl/memory",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_test(
- name = "fixed_array_exception_safety_test",
- srcs = ["fixed_array_exception_safety_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":fixed_array",
- "//absl/base:config",
- "//absl/base:exception_safety_testing",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_binary(
- name = "fixed_array_benchmark",
- testonly = 1,
- srcs = ["fixed_array_benchmark.cc"],
- copts = ABSL_TEST_COPTS + ["$(STACK_FRAME_UNLIMITED)"],
- linkopts = ABSL_DEFAULT_LINKOPTS,
- tags = ["benchmark"],
- deps = [
- ":fixed_array",
- "@com_github_google_benchmark//:benchmark_main",
- ],
-)
-
-cc_library(
- name = "inlined_vector_internal",
- hdrs = ["internal/inlined_vector.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":compressed_tuple",
- "//absl/base:core_headers",
- "//absl/memory",
- "//absl/meta:type_traits",
- "//absl/types:span",
- ],
-)
-
-cc_library(
- name = "inlined_vector",
- hdrs = ["inlined_vector.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":inlined_vector_internal",
- "//absl/algorithm",
- "//absl/base:core_headers",
- "//absl/base:throw_delegate",
- "//absl/memory",
- "//absl/meta:type_traits",
- ],
-)
-
-cc_library(
- name = "counting_allocator",
- testonly = 1,
- hdrs = ["internal/counting_allocator.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- visibility = ["//visibility:private"],
- deps = ["//absl/base:config"],
-)
-
-cc_test(
- name = "inlined_vector_test",
- srcs = ["inlined_vector_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":counting_allocator",
- ":inlined_vector",
- ":test_instance_tracker",
- "//absl/base:config",
- "//absl/base:core_headers",
- "//absl/base:exception_testing",
- "//absl/base:raw_logging_internal",
- "//absl/hash:hash_testing",
- "//absl/memory",
- "//absl/strings",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_binary(
- name = "inlined_vector_benchmark",
- testonly = 1,
- srcs = ["inlined_vector_benchmark.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- tags = ["benchmark"],
- deps = [
- ":inlined_vector",
- "//absl/base:core_headers",
- "//absl/base:raw_logging_internal",
- "//absl/strings",
- "@com_github_google_benchmark//:benchmark_main",
- ],
-)
-
-cc_test(
- name = "inlined_vector_exception_safety_test",
- srcs = ["inlined_vector_exception_safety_test.cc"],
- copts = ABSL_TEST_COPTS,
- deps = [
- ":inlined_vector",
- "//absl/base:config",
- "//absl/base:exception_safety_testing",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_library(
- name = "test_instance_tracker",
- testonly = 1,
- srcs = ["internal/test_instance_tracker.cc"],
- hdrs = ["internal/test_instance_tracker.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- visibility = [
- "//absl:__subpackages__",
- ],
- deps = ["//absl/types:compare"],
-)
-
-cc_test(
- name = "test_instance_tracker_test",
- srcs = ["internal/test_instance_tracker_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":test_instance_tracker",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-NOTEST_TAGS_MOBILE = [
- "no_test_android_arm",
- "no_test_android_arm64",
- "no_test_android_x86",
- "no_test_ios_x86_64",
-]
-
-cc_library(
- name = "flat_hash_map",
- hdrs = ["flat_hash_map.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":container_memory",
- ":hash_function_defaults",
- ":raw_hash_map",
- "//absl/algorithm:container",
- "//absl/base:core_headers",
- "//absl/memory",
- ],
-)
-
-cc_test(
- name = "flat_hash_map_test",
- srcs = ["flat_hash_map_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- tags = ["no_test_loonix"],
- deps = [
- ":flat_hash_map",
- ":hash_generator_testing",
- ":unordered_map_constructor_test",
- ":unordered_map_lookup_test",
- ":unordered_map_members_test",
- ":unordered_map_modifiers_test",
- "//absl/base:raw_logging_internal",
- "//absl/types:any",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_library(
- name = "flat_hash_set",
- hdrs = ["flat_hash_set.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":container_memory",
- ":hash_function_defaults",
- ":raw_hash_set",
- "//absl/algorithm:container",
- "//absl/base:core_headers",
- "//absl/memory",
- ],
-)
-
-cc_test(
- name = "flat_hash_set_test",
- srcs = ["flat_hash_set_test.cc"],
- copts = ABSL_TEST_COPTS + ["-DUNORDERED_SET_CXX17"],
- linkopts = ABSL_DEFAULT_LINKOPTS,
- tags = ["no_test_loonix"],
- deps = [
- ":flat_hash_set",
- ":hash_generator_testing",
- ":unordered_set_constructor_test",
- ":unordered_set_lookup_test",
- ":unordered_set_members_test",
- ":unordered_set_modifiers_test",
- "//absl/base:raw_logging_internal",
- "//absl/memory",
- "//absl/strings",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_library(
- name = "node_hash_map",
- hdrs = ["node_hash_map.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":container_memory",
- ":hash_function_defaults",
- ":node_slot_policy",
- ":raw_hash_map",
- "//absl/algorithm:container",
- "//absl/base:core_headers",
- "//absl/memory",
- ],
-)
-
-cc_test(
- name = "node_hash_map_test",
- srcs = ["node_hash_map_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- tags = ["no_test_loonix"],
- deps = [
- ":hash_generator_testing",
- ":node_hash_map",
- ":tracked",
- ":unordered_map_constructor_test",
- ":unordered_map_lookup_test",
- ":unordered_map_members_test",
- ":unordered_map_modifiers_test",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_library(
- name = "node_hash_set",
- hdrs = ["node_hash_set.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":hash_function_defaults",
- ":node_slot_policy",
- ":raw_hash_set",
- "//absl/algorithm:container",
- "//absl/base:core_headers",
- "//absl/memory",
- ],
-)
-
-cc_test(
- name = "node_hash_set_test",
- srcs = ["node_hash_set_test.cc"],
- copts = ABSL_TEST_COPTS + ["-DUNORDERED_SET_CXX17"],
- linkopts = ABSL_DEFAULT_LINKOPTS,
- tags = ["no_test_loonix"],
- deps = [
- ":node_hash_set",
- ":unordered_set_constructor_test",
- ":unordered_set_lookup_test",
- ":unordered_set_members_test",
- ":unordered_set_modifiers_test",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_library(
- name = "container_memory",
- hdrs = ["internal/container_memory.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- "//absl/base:config",
- "//absl/memory",
- "//absl/meta:type_traits",
- "//absl/utility",
- ],
-)
-
-cc_test(
- name = "container_memory_test",
- srcs = ["internal/container_memory_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- tags = ["no_test_loonix"],
- deps = [
- ":container_memory",
- ":test_instance_tracker",
- "//absl/strings",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_library(
- name = "hash_function_defaults",
- hdrs = ["internal/hash_function_defaults.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- "//absl/base:config",
- "//absl/hash",
- "//absl/strings",
- "//absl/strings:cord",
- ],
-)
-
-cc_test(
- name = "hash_function_defaults_test",
- srcs = ["internal/hash_function_defaults_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- tags = NOTEST_TAGS_MOBILE + ["no_test_loonix"],
- deps = [
- ":hash_function_defaults",
- "//absl/hash",
- "//absl/random",
- "//absl/strings",
- "//absl/strings:cord",
- "//absl/strings:cord_test_helpers",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_library(
- name = "hash_generator_testing",
- testonly = 1,
- srcs = ["internal/hash_generator_testing.cc"],
- hdrs = ["internal/hash_generator_testing.h"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":hash_policy_testing",
- "//absl/memory",
- "//absl/meta:type_traits",
- "//absl/strings",
- ],
-)
-
-cc_library(
- name = "hash_policy_testing",
- testonly = 1,
- hdrs = ["internal/hash_policy_testing.h"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- "//absl/hash",
- "//absl/strings",
- ],
-)
-
-cc_test(
- name = "hash_policy_testing_test",
- srcs = ["internal/hash_policy_testing_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":hash_policy_testing",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_library(
- name = "hash_policy_traits",
- hdrs = ["internal/hash_policy_traits.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":common_policy_traits",
- "//absl/meta:type_traits",
- ],
-)
-
-cc_test(
- name = "hash_policy_traits_test",
- srcs = ["internal/hash_policy_traits_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":hash_policy_traits",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_library(
- name = "common_policy_traits",
- hdrs = ["internal/common_policy_traits.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- visibility = ["//visibility:private"],
- deps = ["//absl/meta:type_traits"],
-)
-
-cc_test(
- name = "common_policy_traits_test",
- srcs = ["internal/common_policy_traits_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":common_policy_traits",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_library(
- name = "hashtable_debug",
- hdrs = ["internal/hashtable_debug.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":hashtable_debug_hooks",
- ],
-)
-
-cc_library(
- name = "hashtable_debug_hooks",
- hdrs = ["internal/hashtable_debug_hooks.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- "//absl/base:config",
- ],
-)
-
-cc_library(
- name = "hashtablez_sampler",
- srcs = [
- "internal/hashtablez_sampler.cc",
- "internal/hashtablez_sampler_force_weak_definition.cc",
- ],
- hdrs = ["internal/hashtablez_sampler.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- "//absl/base",
- "//absl/base:config",
- "//absl/base:core_headers",
- "//absl/debugging:stacktrace",
- "//absl/memory",
- "//absl/profiling:exponential_biased",
- "//absl/profiling:sample_recorder",
- "//absl/synchronization",
- "//absl/utility",
- ],
-)
-
-cc_test(
- name = "hashtablez_sampler_test",
- srcs = ["internal/hashtablez_sampler_test.cc"],
- linkopts = ABSL_DEFAULT_LINKOPTS,
- tags = [
- "no_test_wasm",
- ],
- deps = [
- ":hashtablez_sampler",
- "//absl/base:config",
- "//absl/base:core_headers",
- "//absl/profiling:sample_recorder",
- "//absl/synchronization",
- "//absl/synchronization:thread_pool",
- "//absl/time",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_library(
- name = "node_slot_policy",
- hdrs = ["internal/node_slot_policy.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = ["//absl/base:config"],
-)
-
-cc_test(
- name = "node_slot_policy_test",
- srcs = ["internal/node_slot_policy_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":hash_policy_traits",
- ":node_slot_policy",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_library(
- name = "raw_hash_map",
- hdrs = ["internal/raw_hash_map.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":container_memory",
- ":raw_hash_set",
- "//absl/base:throw_delegate",
- ],
-)
-
-cc_library(
- name = "common",
- hdrs = ["internal/common.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- "//absl/meta:type_traits",
- "//absl/types:optional",
- ],
-)
-
-cc_library(
- name = "raw_hash_set",
- srcs = ["internal/raw_hash_set.cc"],
- hdrs = ["internal/raw_hash_set.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":common",
- ":compressed_tuple",
- ":container_memory",
- ":hash_policy_traits",
- ":hashtable_debug_hooks",
- ":hashtablez_sampler",
- "//absl/base:config",
- "//absl/base:core_headers",
- "//absl/base:endian",
- "//absl/base:prefetch",
- "//absl/memory",
- "//absl/meta:type_traits",
- "//absl/numeric:bits",
- "//absl/utility",
- ],
-)
-
-cc_test(
- name = "raw_hash_set_test",
- srcs = ["internal/raw_hash_set_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkstatic = 1,
- tags = NOTEST_TAGS_MOBILE + [
- "no_test_loonix",
- # TODO(b/237097643): investigate race and remove
- "noarm_gemu",
- ],
- deps = [
- ":container_memory",
- ":flat_hash_map",
- ":flat_hash_set",
- ":hash_function_defaults",
- ":hash_policy_testing",
- ":hashtable_debug",
- ":raw_hash_set",
- "//absl/base",
- "//absl/base:config",
- "//absl/base:core_headers",
- "//absl/base:prefetch",
- "//absl/base:raw_logging_internal",
- "//absl/log",
- "//absl/strings",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_binary(
- name = "raw_hash_set_benchmark",
- testonly = 1,
- srcs = ["internal/raw_hash_set_benchmark.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- tags = ["benchmark"],
- visibility = ["//visibility:private"],
- deps = [
- ":hash_function_defaults",
- ":raw_hash_set",
- "//absl/base:raw_logging_internal",
- "//absl/strings:str_format",
- "@com_github_google_benchmark//:benchmark_main",
- ],
-)
-
-cc_binary(
- name = "raw_hash_set_probe_benchmark",
- testonly = 1,
- srcs = ["internal/raw_hash_set_probe_benchmark.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = select({
- "//conditions:default": [],
- }) + ABSL_DEFAULT_LINKOPTS,
- tags = ["benchmark"],
- visibility = ["//visibility:private"],
- deps = [
- ":flat_hash_map",
- ":hash_function_defaults",
- ":hashtable_debug",
- ":raw_hash_set",
- "//absl/random",
- "//absl/random:distributions",
- "//absl/strings",
- "//absl/strings:str_format",
- ],
-)
-
-cc_test(
- name = "raw_hash_set_allocator_test",
- size = "small",
- srcs = ["internal/raw_hash_set_allocator_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":raw_hash_set",
- ":tracked",
- "//absl/base:core_headers",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_library(
- name = "layout",
- hdrs = ["internal/layout.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- "//absl/base:config",
- "//absl/base:core_headers",
- "//absl/meta:type_traits",
- "//absl/strings",
- "//absl/types:span",
- "//absl/utility",
- ],
-)
-
-cc_test(
- name = "layout_test",
- size = "small",
- srcs = ["internal/layout_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- tags = NOTEST_TAGS_MOBILE + ["no_test_loonix"],
- visibility = ["//visibility:private"],
- deps = [
- ":layout",
- "//absl/base:config",
- "//absl/base:core_headers",
- "//absl/base:raw_logging_internal",
- "//absl/types:span",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_binary(
- name = "layout_benchmark",
- testonly = 1,
- srcs = ["internal/layout_benchmark.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- tags = ["benchmark"],
- visibility = ["//visibility:private"],
- deps = [
- ":layout",
- "//absl/base:core_headers",
- "//absl/base:raw_logging_internal",
- "@com_github_google_benchmark//:benchmark_main",
- ],
-)
-
-cc_library(
- name = "tracked",
- testonly = 1,
- hdrs = ["internal/tracked.h"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- "//absl/base:config",
- ],
-)
-
-cc_library(
- name = "unordered_map_constructor_test",
- testonly = 1,
- hdrs = ["internal/unordered_map_constructor_test.h"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":hash_generator_testing",
- ":hash_policy_testing",
- "@com_google_googletest//:gtest",
- ],
-)
-
-cc_library(
- name = "unordered_map_lookup_test",
- testonly = 1,
- hdrs = ["internal/unordered_map_lookup_test.h"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":hash_generator_testing",
- ":hash_policy_testing",
- "@com_google_googletest//:gtest",
- ],
-)
-
-cc_library(
- name = "unordered_map_modifiers_test",
- testonly = 1,
- hdrs = ["internal/unordered_map_modifiers_test.h"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":hash_generator_testing",
- ":hash_policy_testing",
- "@com_google_googletest//:gtest",
- ],
-)
-
-cc_library(
- name = "unordered_set_constructor_test",
- testonly = 1,
- hdrs = ["internal/unordered_set_constructor_test.h"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":hash_generator_testing",
- ":hash_policy_testing",
- "//absl/meta:type_traits",
- "@com_google_googletest//:gtest",
- ],
-)
-
-cc_library(
- name = "unordered_set_members_test",
- testonly = 1,
- hdrs = ["internal/unordered_set_members_test.h"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- "//absl/meta:type_traits",
- "@com_google_googletest//:gtest",
- ],
-)
-
-cc_library(
- name = "unordered_map_members_test",
- testonly = 1,
- hdrs = ["internal/unordered_map_members_test.h"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- "//absl/meta:type_traits",
- "@com_google_googletest//:gtest",
- ],
-)
-
-cc_library(
- name = "unordered_set_lookup_test",
- testonly = 1,
- hdrs = ["internal/unordered_set_lookup_test.h"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":hash_generator_testing",
- ":hash_policy_testing",
- "@com_google_googletest//:gtest",
- ],
-)
-
-cc_library(
- name = "unordered_set_modifiers_test",
- testonly = 1,
- hdrs = ["internal/unordered_set_modifiers_test.h"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":hash_generator_testing",
- ":hash_policy_testing",
- "@com_google_googletest//:gtest",
- ],
-)
-
-cc_test(
- name = "unordered_set_test",
- srcs = ["internal/unordered_set_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- tags = ["no_test_loonix"],
- deps = [
- ":unordered_set_constructor_test",
- ":unordered_set_lookup_test",
- ":unordered_set_members_test",
- ":unordered_set_modifiers_test",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_test(
- name = "unordered_map_test",
- srcs = ["internal/unordered_map_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- tags = ["no_test_loonix"],
- deps = [
- ":unordered_map_constructor_test",
- ":unordered_map_lookup_test",
- ":unordered_map_members_test",
- ":unordered_map_modifiers_test",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_test(
- name = "sample_element_size_test",
- srcs = ["sample_element_size_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- tags = ["no_test_loonix"],
- visibility = ["//visibility:private"],
- deps = [
- ":flat_hash_map",
- ":flat_hash_set",
- ":node_hash_map",
- ":node_hash_set",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_library(
- name = "btree",
- srcs = [
- "internal/btree.h",
- "internal/btree_container.h",
- ],
- hdrs = [
- "btree_map.h",
- "btree_set.h",
- ],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- visibility = ["//visibility:public"],
- deps = [
- ":common",
- ":common_policy_traits",
- ":compressed_tuple",
- ":container_memory",
- ":layout",
- "//absl/base:core_headers",
- "//absl/base:raw_logging_internal",
- "//absl/base:throw_delegate",
- "//absl/memory",
- "//absl/meta:type_traits",
- "//absl/strings",
- "//absl/strings:cord",
- "//absl/types:compare",
- "//absl/utility",
- ],
-)
-
-cc_library(
- name = "btree_test_common",
- testonly = 1,
- hdrs = ["btree_test.h"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- visibility = ["//visibility:private"],
- deps = [
- ":btree",
- ":flat_hash_set",
- "//absl/strings",
- "//absl/strings:cord",
- "//absl/time",
- ],
-)
-
-cc_test(
- name = "btree_test",
- size = "large",
- srcs = [
- "btree_test.cc",
- ],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- shard_count = 10,
- tags = [
- "no_test:os:ios",
- "no_test_ios",
- "no_test_wasm",
- ],
- visibility = ["//visibility:private"],
- deps = [
- ":btree",
- ":btree_test_common",
- ":counting_allocator",
- ":test_instance_tracker",
- "//absl/algorithm:container",
- "//absl/base:core_headers",
- "//absl/base:raw_logging_internal",
- "//absl/flags:flag",
- "//absl/hash:hash_testing",
- "//absl/memory",
- "//absl/random",
- "//absl/strings",
- "//absl/types:compare",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_binary(
- name = "btree_benchmark",
- testonly = 1,
- srcs = [
- "btree_benchmark.cc",
- ],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- tags = ["benchmark"],
- visibility = ["//visibility:private"],
- deps = [
- ":btree",
- ":btree_test_common",
- ":flat_hash_map",
- ":flat_hash_set",
- ":hashtable_debug",
- "//absl/algorithm:container",
- "//absl/base:raw_logging_internal",
- "//absl/hash",
- "//absl/log",
- "//absl/memory",
- "//absl/random",
- "//absl/strings:cord",
- "//absl/strings:str_format",
- "//absl/time",
- "@com_github_google_benchmark//:benchmark_main",
- ],
-)
diff --git a/third_party/abseil-cpp/absl/container/BUILD.gn b/third_party/abseil-cpp/absl/container/BUILD.gn
deleted file mode 100644
index c01011f..0000000
--- a/third_party/abseil-cpp/absl/container/BUILD.gn
+++ /dev/null
@@ -1,401 +0,0 @@
-# Copyright 2018 The Chromium Authors
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-import("//third_party/abseil-cpp/absl.gni")
-
-absl_source_set("compressed_tuple") {
- public = [ "internal/compressed_tuple.h" ]
- deps = [ "//third_party/abseil-cpp/absl/utility" ]
-}
-
-absl_source_set("fixed_array") {
- public = [ "fixed_array.h" ]
- deps = [
- ":compressed_tuple",
- "//third_party/abseil-cpp/absl/algorithm",
- "//third_party/abseil-cpp/absl/base:config",
- "//third_party/abseil-cpp/absl/base:core_headers",
- "//third_party/abseil-cpp/absl/base:dynamic_annotations",
- "//third_party/abseil-cpp/absl/base:throw_delegate",
- "//third_party/abseil-cpp/absl/memory",
- ]
-}
-
-absl_source_set("inlined_vector_internal") {
- public = [ "internal/inlined_vector.h" ]
- deps = [
- ":compressed_tuple",
- "//third_party/abseil-cpp/absl/base:core_headers",
- "//third_party/abseil-cpp/absl/memory",
- "//third_party/abseil-cpp/absl/meta:type_traits",
- "//third_party/abseil-cpp/absl/types:span",
- ]
-}
-
-absl_source_set("inlined_vector") {
- public = [ "inlined_vector.h" ]
- deps = [
- ":inlined_vector_internal",
- "//third_party/abseil-cpp/absl/algorithm",
- "//third_party/abseil-cpp/absl/base:core_headers",
- "//third_party/abseil-cpp/absl/base:throw_delegate",
- "//third_party/abseil-cpp/absl/memory",
- "//third_party/abseil-cpp/absl/meta:type_traits",
- ]
-}
-
-absl_source_set("counting_allocator") {
- testonly = true
- public = [ "internal/counting_allocator.h" ]
- deps = [ "//third_party/abseil-cpp/absl/base:config" ]
- visibility = [ ":*" ]
-}
-
-absl_source_set("test_instance_tracker") {
- testonly = true
- sources = [ "internal/test_instance_tracker.cc" ]
- public = [ "internal/test_instance_tracker.h" ]
- deps = [ "//third_party/abseil-cpp/absl/types:compare" ]
- visibility = [ "//third_party/abseil-cpp/absl/*" ]
-}
-
-absl_source_set("flat_hash_map") {
- public = [ "flat_hash_map.h" ]
- deps = [
- ":container_memory",
- ":hash_function_defaults",
- ":raw_hash_map",
- "//third_party/abseil-cpp/absl/algorithm:container",
- "//third_party/abseil-cpp/absl/base:core_headers",
- "//third_party/abseil-cpp/absl/memory",
- ]
-}
-
-absl_source_set("flat_hash_set") {
- public = [ "flat_hash_set.h" ]
- deps = [
- ":container_memory",
- ":hash_function_defaults",
- ":raw_hash_set",
- "//third_party/abseil-cpp/absl/algorithm:container",
- "//third_party/abseil-cpp/absl/base:core_headers",
- "//third_party/abseil-cpp/absl/memory",
- ]
-}
-
-absl_source_set("node_hash_map") {
- public = [ "node_hash_map.h" ]
- deps = [
- ":container_memory",
- ":hash_function_defaults",
- ":node_slot_policy",
- ":raw_hash_map",
- "//third_party/abseil-cpp/absl/algorithm:container",
- "//third_party/abseil-cpp/absl/base:core_headers",
- "//third_party/abseil-cpp/absl/memory",
- ]
-}
-
-absl_source_set("node_hash_set") {
- public = [ "node_hash_set.h" ]
- deps = [
- ":container_memory",
- ":hash_function_defaults",
- ":node_slot_policy",
- ":raw_hash_set",
- "//third_party/abseil-cpp/absl/algorithm:container",
- "//third_party/abseil-cpp/absl/base:core_headers",
- "//third_party/abseil-cpp/absl/memory",
- ]
-}
-
-absl_source_set("container_memory") {
- public = [ "internal/container_memory.h" ]
- deps = [
- "//third_party/abseil-cpp/absl/base:config",
- "//third_party/abseil-cpp/absl/memory",
- "//third_party/abseil-cpp/absl/meta:type_traits",
- "//third_party/abseil-cpp/absl/utility",
- ]
-}
-
-absl_source_set("hash_function_defaults") {
- public = [ "internal/hash_function_defaults.h" ]
- deps = [
- "//third_party/abseil-cpp/absl/base:config",
- "//third_party/abseil-cpp/absl/hash",
- "//third_party/abseil-cpp/absl/strings",
- "//third_party/abseil-cpp/absl/strings:cord",
- ]
-}
-
-absl_source_set("hash_generator_testing") {
- testonly = true
- sources = [ "internal/hash_generator_testing.cc" ]
- public = [ "internal/hash_generator_testing.h" ]
- deps = [
- ":hash_policy_testing",
- "//third_party/abseil-cpp/absl/memory",
- "//third_party/abseil-cpp/absl/meta:type_traits",
- "//third_party/abseil-cpp/absl/strings",
- ]
-}
-
-absl_source_set("hash_policy_testing") {
- testonly = true
- public = [ "internal/hash_policy_testing.h" ]
- deps = [
- "//third_party/abseil-cpp/absl/hash",
- "//third_party/abseil-cpp/absl/strings",
- ]
-}
-
-absl_source_set("hash_policy_traits") {
- public = [ "internal/hash_policy_traits.h" ]
- deps = [
- ":common_policy_traits",
- "//third_party/abseil-cpp/absl/meta:type_traits",
- ]
-}
-
-absl_source_set("common_policy_traits") {
- public = [ "internal/common_policy_traits.h" ]
- visibility = [ "//third_party/abseil-cpp/absl/container:*" ]
- deps = [ "//third_party/abseil-cpp/absl/meta:type_traits" ]
-}
-
-absl_test("common_policy_traits_test") {
- sources = [ "internal/common_policy_traits_test.cc" ]
- deps = [ ":common_policy_traits" ]
-}
-
-absl_source_set("hashtable_debug") {
- public = [ "internal/hashtable_debug.h" ]
- deps = [ ":hashtable_debug_hooks" ]
-}
-
-absl_source_set("hashtable_debug_hooks") {
- public = [ "internal/hashtable_debug_hooks.h" ]
- deps = [ "//third_party/abseil-cpp/absl/base:config" ]
-}
-
-absl_source_set("hashtablez_sampler") {
- public = [ "internal/hashtablez_sampler.h" ]
- sources = [
- "internal/hashtablez_sampler.cc",
- "internal/hashtablez_sampler_force_weak_definition.cc",
- ]
- deps = [
- "//third_party/abseil-cpp/absl/base",
- "//third_party/abseil-cpp/absl/base:config",
- "//third_party/abseil-cpp/absl/base:core_headers",
- "//third_party/abseil-cpp/absl/debugging:stacktrace",
- "//third_party/abseil-cpp/absl/memory",
- "//third_party/abseil-cpp/absl/profiling:exponential_biased",
- "//third_party/abseil-cpp/absl/profiling:sample_recorder",
- "//third_party/abseil-cpp/absl/synchronization",
- "//third_party/abseil-cpp/absl/utility",
- ]
-}
-
-absl_source_set("node_slot_policy") {
- public = [ "internal/node_slot_policy.h" ]
- deps = [ "//third_party/abseil-cpp/absl/base:config" ]
-}
-
-absl_test("node_slot_policy_test") {
- sources = [ "internal/node_slot_policy_test.cc" ]
- deps = [
- ":hash_policy_traits",
- ":node_slot_policy",
- ]
-}
-
-absl_source_set("raw_hash_map") {
- public = [ "internal/raw_hash_map.h" ]
- deps = [
- ":container_memory",
- ":raw_hash_set",
- "//third_party/abseil-cpp/absl/base:throw_delegate",
- ]
-}
-
-absl_source_set("common") {
- public = [ "internal/common.h" ]
- deps = [
- "//third_party/abseil-cpp/absl/meta:type_traits",
- "//third_party/abseil-cpp/absl/types:optional",
- ]
-}
-
-absl_source_set("raw_hash_set") {
- sources = [ "internal/raw_hash_set.cc" ]
- public = [ "internal/raw_hash_set.h" ]
- deps = [
- ":common",
- ":compressed_tuple",
- ":container_memory",
- ":hash_policy_traits",
- ":hashtable_debug_hooks",
- ":hashtablez_sampler",
- "//third_party/abseil-cpp/absl/base:config",
- "//third_party/abseil-cpp/absl/base:core_headers",
- "//third_party/abseil-cpp/absl/base:endian",
- "//third_party/abseil-cpp/absl/base:prefetch",
- "//third_party/abseil-cpp/absl/memory",
- "//third_party/abseil-cpp/absl/meta:type_traits",
- "//third_party/abseil-cpp/absl/numeric:bits",
- "//third_party/abseil-cpp/absl/utility",
- ]
-}
-
-absl_source_set("layout") {
- public = [ "internal/layout.h" ]
- deps = [
- "//third_party/abseil-cpp/absl/base:config",
- "//third_party/abseil-cpp/absl/base:core_headers",
- "//third_party/abseil-cpp/absl/meta:type_traits",
- "//third_party/abseil-cpp/absl/strings",
- "//third_party/abseil-cpp/absl/types:span",
- "//third_party/abseil-cpp/absl/utility",
- ]
-}
-
-absl_source_set("tracked") {
- testonly = true
- public = [ "internal/tracked.h" ]
- deps = [ "//third_party/abseil-cpp/absl/base:config" ]
-}
-
-absl_source_set("unordered_map_constructor_test") {
- testonly = true
- public = [ "internal/unordered_map_constructor_test.h" ]
- deps = [
- ":hash_generator_testing",
- ":hash_policy_testing",
- "//third_party/googletest:gtest",
- ]
-}
-
-absl_source_set("unordered_map_lookup_test") {
- testonly = true
- public = [ "internal/unordered_map_lookup_test.h" ]
- deps = [
- ":hash_generator_testing",
- ":hash_policy_testing",
- "//third_party/googletest:gtest",
- ]
-}
-
-absl_source_set("unordered_map_modifiers_test") {
- testonly = true
- public = [ "internal/unordered_map_modifiers_test.h" ]
- deps = [
- ":hash_generator_testing",
- ":hash_policy_testing",
- "//third_party/googletest:gtest",
- ]
-}
-
-absl_source_set("unordered_set_constructor_test") {
- testonly = true
- public = [ "internal/unordered_set_constructor_test.h" ]
- deps = [
- ":hash_generator_testing",
- ":hash_policy_testing",
- "//third_party/abseil-cpp/absl/meta:type_traits",
- "//third_party/googletest:gtest",
- ]
-}
-
-absl_source_set("unordered_set_members_test") {
- testonly = true
- public = [ "internal/unordered_set_members_test.h" ]
- deps = [
- "//third_party/abseil-cpp/absl/meta:type_traits",
- "//third_party/googletest:gtest",
- ]
-}
-
-absl_source_set("unordered_map_members_test") {
- testonly = true
- public = [ "internal/unordered_map_members_test.h" ]
- deps = [
- "//third_party/abseil-cpp/absl/meta:type_traits",
- "//third_party/googletest:gtest",
- ]
-}
-
-absl_source_set("unordered_set_lookup_test") {
- testonly = true
- public = [ "internal/unordered_set_lookup_test.h" ]
- deps = [
- ":hash_generator_testing",
- ":hash_policy_testing",
- "//third_party/googletest:gtest",
- ]
-}
-
-absl_source_set("unordered_set_modifiers_test") {
- testonly = true
- public = [ "internal/unordered_set_modifiers_test.h" ]
- deps = [
- ":hash_generator_testing",
- ":hash_policy_testing",
- "//third_party/googletest:gtest",
- ]
-}
-
-absl_test("sample_element_size_test") {
- public = [ "sample_element_size_test.cc" ]
- deps = [
- ":flat_hash_map",
- ":flat_hash_set",
- ":node_hash_map",
- ":node_hash_set",
- ]
-}
-
-absl_source_set("btree") {
- sources = [
- "internal/btree.h",
- "internal/btree_container.h",
- ]
- public = [
- "btree_map.h",
- "btree_set.h",
- ]
- deps = [
- ":common",
- ":common_policy_traits",
- ":compressed_tuple",
- ":container_memory",
- ":layout",
- "//third_party/abseil-cpp/absl/base:core_headers",
- "//third_party/abseil-cpp/absl/base:raw_logging_internal",
- "//third_party/abseil-cpp/absl/base:throw_delegate",
- "//third_party/abseil-cpp/absl/memory",
- "//third_party/abseil-cpp/absl/meta:type_traits",
- "//third_party/abseil-cpp/absl/strings",
- "//third_party/abseil-cpp/absl/strings:cord",
- "//third_party/abseil-cpp/absl/types:compare",
- "//third_party/abseil-cpp/absl/utility",
- ]
-}
-
-absl_test("inlined_vector_test") {
- sources = [ "inlined_vector_test.cc" ]
- deps = [
- ":counting_allocator",
- ":inlined_vector",
- ":test_instance_tracker",
- "//third_party/abseil-cpp/absl/base:config",
- "//third_party/abseil-cpp/absl/base:core_headers",
- "//third_party/abseil-cpp/absl/base:exception_testing",
- "//third_party/abseil-cpp/absl/base:raw_logging_internal",
- "//third_party/abseil-cpp/absl/hash:hash_testing",
- "//third_party/abseil-cpp/absl/memory",
- "//third_party/abseil-cpp/absl/strings",
- ]
-}
diff --git a/third_party/abseil-cpp/absl/container/CMakeLists.txt b/third_party/abseil-cpp/absl/container/CMakeLists.txt
deleted file mode 100644
index b3776ae..0000000
--- a/third_party/abseil-cpp/absl/container/CMakeLists.txt
+++ /dev/null
@@ -1,966 +0,0 @@
-#
-# Copyright 2017 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.
-#
-
-absl_cc_library(
- NAME
- btree
- HDRS
- "btree_map.h"
- "btree_set.h"
- "internal/btree.h"
- "internal/btree_container.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- LINKOPTS
- ${ABSL_DEFAULT_LINKOPTS}
- DEPS
- absl::container_common
- absl::common_policy_traits
- absl::compare
- absl::compressed_tuple
- absl::container_memory
- absl::cord
- absl::core_headers
- absl::layout
- absl::memory
- absl::raw_logging_internal
- absl::strings
- absl::throw_delegate
- absl::type_traits
- absl::utility
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- btree_test_common
- hdrs
- "btree_test.h"
- COPTS
- ${ABSL_TEST_COPTS}
- LINKOPTS
- ${ABSL_DEFAULT_LINKOPTS}
- DEPS
- absl::btree
- absl::cord
- absl::flat_hash_set
- absl::strings
- absl::time
- TESTONLY
-)
-
-absl_cc_test(
- NAME
- btree_test
- SRCS
- "btree_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- LINKOPTS
- ${ABSL_DEFAULT_LINKOPTS}
- DEPS
- absl::algorithm_container
- absl::btree
- absl::btree_test_common
- absl::compare
- absl::core_headers
- absl::counting_allocator
- absl::flags
- absl::hash_testing
- absl::random_random
- absl::raw_logging_internal
- absl::strings
- absl::test_instance_tracker
- GTest::gmock_main
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- compressed_tuple
- HDRS
- "internal/compressed_tuple.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::utility
- PUBLIC
-)
-
-absl_cc_test(
- NAME
- compressed_tuple_test
- SRCS
- "internal/compressed_tuple_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::any
- absl::compressed_tuple
- absl::memory
- absl::optional
- absl::test_instance_tracker
- absl::utility
- GTest::gmock_main
-)
-
-absl_cc_library(
- NAME
- fixed_array
- HDRS
- "fixed_array.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::compressed_tuple
- absl::algorithm
- absl::config
- absl::core_headers
- absl::dynamic_annotations
- absl::throw_delegate
- absl::memory
- PUBLIC
-)
-
-absl_cc_test(
- NAME
- fixed_array_test
- SRCS
- "fixed_array_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::fixed_array
- absl::counting_allocator
- absl::config
- absl::exception_testing
- absl::hash_testing
- absl::memory
- GTest::gmock_main
-)
-
-absl_cc_test(
- NAME
- fixed_array_exception_safety_test
- SRCS
- "fixed_array_exception_safety_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::fixed_array
- absl::config
- absl::exception_safety_testing
- GTest::gmock_main
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- inlined_vector_internal
- HDRS
- "internal/inlined_vector.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::compressed_tuple
- absl::core_headers
- absl::memory
- absl::span
- absl::type_traits
- PUBLIC
-)
-
-absl_cc_library(
- NAME
- inlined_vector
- HDRS
- "inlined_vector.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::algorithm
- absl::core_headers
- absl::inlined_vector_internal
- absl::throw_delegate
- absl::memory
- absl::type_traits
- PUBLIC
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- counting_allocator
- HDRS
- "internal/counting_allocator.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::config
-)
-
-absl_cc_test(
- NAME
- inlined_vector_test
- SRCS
- "inlined_vector_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::counting_allocator
- absl::inlined_vector
- absl::test_instance_tracker
- absl::config
- absl::core_headers
- absl::exception_testing
- absl::hash_testing
- absl::memory
- absl::raw_logging_internal
- absl::strings
- GTest::gmock_main
-)
-
-absl_cc_test(
- NAME
- inlined_vector_exception_safety_test
- SRCS
- "inlined_vector_exception_safety_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::inlined_vector
- absl::config
- absl::exception_safety_testing
- GTest::gmock_main
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- test_instance_tracker
- HDRS
- "internal/test_instance_tracker.h"
- SRCS
- "internal/test_instance_tracker.cc"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::compare
- TESTONLY
-)
-
-absl_cc_test(
- NAME
- test_instance_tracker_test
- SRCS
- "internal/test_instance_tracker_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::test_instance_tracker
- GTest::gmock_main
-)
-
-absl_cc_library(
- NAME
- flat_hash_map
- HDRS
- "flat_hash_map.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::container_memory
- absl::core_headers
- absl::hash_function_defaults
- absl::raw_hash_map
- absl::algorithm_container
- absl::memory
- PUBLIC
-)
-
-absl_cc_test(
- NAME
- flat_hash_map_test
- SRCS
- "flat_hash_map_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::flat_hash_map
- absl::hash_generator_testing
- absl::unordered_map_constructor_test
- absl::unordered_map_lookup_test
- absl::unordered_map_members_test
- absl::unordered_map_modifiers_test
- absl::any
- absl::raw_logging_internal
- GTest::gmock_main
-)
-
-absl_cc_library(
- NAME
- flat_hash_set
- HDRS
- "flat_hash_set.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::container_memory
- absl::hash_function_defaults
- absl::raw_hash_set
- absl::algorithm_container
- absl::core_headers
- absl::memory
- PUBLIC
-)
-
-absl_cc_test(
- NAME
- flat_hash_set_test
- SRCS
- "flat_hash_set_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- "-DUNORDERED_SET_CXX17"
- DEPS
- absl::flat_hash_set
- absl::hash_generator_testing
- absl::unordered_set_constructor_test
- absl::unordered_set_lookup_test
- absl::unordered_set_members_test
- absl::unordered_set_modifiers_test
- absl::memory
- absl::raw_logging_internal
- absl::strings
- GTest::gmock_main
-)
-
-absl_cc_library(
- NAME
- node_hash_map
- HDRS
- "node_hash_map.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::container_memory
- absl::core_headers
- absl::hash_function_defaults
- absl::node_slot_policy
- absl::raw_hash_map
- absl::algorithm_container
- absl::memory
- PUBLIC
-)
-
-absl_cc_test(
- NAME
- node_hash_map_test
- SRCS
- "node_hash_map_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::hash_generator_testing
- absl::node_hash_map
- absl::tracked
- absl::unordered_map_constructor_test
- absl::unordered_map_lookup_test
- absl::unordered_map_members_test
- absl::unordered_map_modifiers_test
- GTest::gmock_main
-)
-
-absl_cc_library(
- NAME
- node_hash_set
- HDRS
- "node_hash_set.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::core_headers
- absl::hash_function_defaults
- absl::node_slot_policy
- absl::raw_hash_set
- absl::algorithm_container
- absl::memory
- PUBLIC
-)
-
-absl_cc_test(
- NAME
- node_hash_set_test
- SRCS
- "node_hash_set_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- "-DUNORDERED_SET_CXX17"
- DEPS
- absl::hash_generator_testing
- absl::node_hash_set
- absl::unordered_set_constructor_test
- absl::unordered_set_lookup_test
- absl::unordered_set_members_test
- absl::unordered_set_modifiers_test
- GTest::gmock_main
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- container_memory
- HDRS
- "internal/container_memory.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::config
- absl::memory
- absl::type_traits
- absl::utility
- PUBLIC
-)
-
-absl_cc_test(
- NAME
- container_memory_test
- SRCS
- "internal/container_memory_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::container_memory
- absl::strings
- absl::test_instance_tracker
- GTest::gmock_main
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- hash_function_defaults
- HDRS
- "internal/hash_function_defaults.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::config
- absl::cord
- absl::hash
- absl::strings
- PUBLIC
-)
-
-absl_cc_test(
- NAME
- hash_function_defaults_test
- SRCS
- "internal/hash_function_defaults_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::cord
- absl::cord_test_helpers
- absl::hash_function_defaults
- absl::hash
- absl::random_random
- absl::strings
- GTest::gmock_main
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- hash_generator_testing
- HDRS
- "internal/hash_generator_testing.h"
- SRCS
- "internal/hash_generator_testing.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::hash_policy_testing
- absl::memory
- absl::meta
- absl::strings
- TESTONLY
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- hash_policy_testing
- HDRS
- "internal/hash_policy_testing.h"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::hash
- absl::strings
- TESTONLY
-)
-
-absl_cc_test(
- NAME
- hash_policy_testing_test
- SRCS
- "internal/hash_policy_testing_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::hash_policy_testing
- GTest::gmock_main
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- hash_policy_traits
- HDRS
- "internal/hash_policy_traits.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::common_policy_traits
- absl::meta
- PUBLIC
-)
-
-absl_cc_test(
- NAME
- hash_policy_traits_test
- SRCS
- "internal/hash_policy_traits_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::hash_policy_traits
- GTest::gmock_main
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- common_policy_traits
- HDRS
- "internal/common_policy_traits.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::meta
- PUBLIC
-)
-
-absl_cc_test(
- NAME
- common_policy_traits_test
- SRCS
- "internal/common_policy_traits_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::common_policy_traits
- GTest::gmock_main
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- hashtablez_sampler
- HDRS
- "internal/hashtablez_sampler.h"
- SRCS
- "internal/hashtablez_sampler.cc"
- "internal/hashtablez_sampler_force_weak_definition.cc"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::base
- absl::config
- absl::exponential_biased
- absl::sample_recorder
- absl::synchronization
-)
-
-absl_cc_test(
- NAME
- hashtablez_sampler_test
- SRCS
- "internal/hashtablez_sampler_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::config
- absl::hashtablez_sampler
- GTest::gmock_main
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- hashtable_debug
- HDRS
- "internal/hashtable_debug.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::hashtable_debug_hooks
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- hashtable_debug_hooks
- HDRS
- "internal/hashtable_debug_hooks.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::config
- PUBLIC
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- node_slot_policy
- HDRS
- "internal/node_slot_policy.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::config
- PUBLIC
-)
-
-absl_cc_test(
- NAME
- node_slot_policy_test
- SRCS
- "internal/node_slot_policy_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::hash_policy_traits
- absl::node_slot_policy
- GTest::gmock_main
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- raw_hash_map
- HDRS
- "internal/raw_hash_map.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::container_memory
- absl::raw_hash_set
- absl::throw_delegate
- PUBLIC
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- container_common
- HDRS
- "internal/common.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::type_traits
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- raw_hash_set
- HDRS
- "internal/raw_hash_set.h"
- SRCS
- "internal/raw_hash_set.cc"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::bits
- absl::compressed_tuple
- absl::config
- absl::container_common
- absl::container_memory
- absl::core_headers
- absl::endian
- absl::hash_policy_traits
- absl::hashtable_debug_hooks
- absl::memory
- absl::meta
- absl::optional
- absl::prefetch
- absl::utility
- absl::hashtablez_sampler
- PUBLIC
-)
-
-absl_cc_test(
- NAME
- raw_hash_set_test
- SRCS
- "internal/raw_hash_set_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::container_memory
- absl::flat_hash_map
- absl::flat_hash_set
- absl::hash_function_defaults
- absl::hash_policy_testing
- absl::hashtable_debug
- absl::raw_hash_set
- absl::base
- absl::config
- absl::log
- absl::core_headers
- absl::prefetch
- absl::raw_logging_internal
- absl::strings
- GTest::gmock_main
-)
-
-absl_cc_test(
- NAME
- raw_hash_set_allocator_test
- SRCS
- "internal/raw_hash_set_allocator_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::raw_hash_set
- absl::tracked
- absl::core_headers
- GTest::gmock_main
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- layout
- HDRS
- "internal/layout.h"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::config
- absl::core_headers
- absl::meta
- absl::strings
- absl::span
- absl::utility
- PUBLIC
-)
-
-absl_cc_test(
- NAME
- layout_test
- SRCS
- "internal/layout_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::layout
- absl::config
- absl::core_headers
- absl::raw_logging_internal
- absl::span
- GTest::gmock_main
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- tracked
- HDRS
- "internal/tracked.h"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::config
- TESTONLY
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- unordered_map_constructor_test
- HDRS
- "internal/unordered_map_constructor_test.h"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::hash_generator_testing
- absl::hash_policy_testing
- GTest::gmock
- TESTONLY
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- unordered_map_lookup_test
- HDRS
- "internal/unordered_map_lookup_test.h"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::hash_generator_testing
- absl::hash_policy_testing
- GTest::gmock
- TESTONLY
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- unordered_map_members_test
- HDRS
- "internal/unordered_map_members_test.h"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::type_traits
- GTest::gmock
- TESTONLY
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- unordered_map_modifiers_test
- HDRS
- "internal/unordered_map_modifiers_test.h"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::hash_generator_testing
- absl::hash_policy_testing
- GTest::gmock
- TESTONLY
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- unordered_set_constructor_test
- HDRS
- "internal/unordered_set_constructor_test.h"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::hash_generator_testing
- absl::hash_policy_testing
- GTest::gmock
- TESTONLY
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- unordered_set_lookup_test
- HDRS
- "internal/unordered_set_lookup_test.h"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::hash_generator_testing
- absl::hash_policy_testing
- GTest::gmock
- TESTONLY
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- unordered_set_members_test
- HDRS
- "internal/unordered_set_members_test.h"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::type_traits
- GTest::gmock
- TESTONLY
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- unordered_set_modifiers_test
- HDRS
- "internal/unordered_set_modifiers_test.h"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::hash_generator_testing
- absl::hash_policy_testing
- GTest::gmock
- TESTONLY
-)
-
-absl_cc_test(
- NAME
- unordered_set_test
- SRCS
- "internal/unordered_set_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::unordered_set_constructor_test
- absl::unordered_set_lookup_test
- absl::unordered_set_members_test
- absl::unordered_set_modifiers_test
- GTest::gmock_main
-)
-
-absl_cc_test(
- NAME
- unordered_map_test
- SRCS
- "internal/unordered_map_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::unordered_map_constructor_test
- absl::unordered_map_lookup_test
- absl::unordered_map_members_test
- absl::unordered_map_modifiers_test
- GTest::gmock_main
-)
-
-absl_cc_test(
- NAME
- sample_element_size_test
- SRCS
- "sample_element_size_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::flat_hash_map
- absl::flat_hash_set
- absl::node_hash_map
- absl::node_hash_set
- GTest::gmock_main
-)
diff --git a/third_party/abseil-cpp/absl/container/btree_benchmark.cc b/third_party/abseil-cpp/absl/container/btree_benchmark.cc
deleted file mode 100644
index 0d26fd4..0000000
--- a/third_party/abseil-cpp/absl/container/btree_benchmark.cc
+++ /dev/null
@@ -1,764 +0,0 @@
-// Copyright 2018 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 <stdint.h>
-
-#include <algorithm>
-#include <functional>
-#include <map>
-#include <numeric>
-#include <random>
-#include <set>
-#include <string>
-#include <type_traits>
-#include <unordered_map>
-#include <unordered_set>
-#include <vector>
-
-#include "benchmark/benchmark.h"
-#include "absl/algorithm/container.h"
-#include "absl/base/internal/raw_logging.h"
-#include "absl/container/btree_map.h"
-#include "absl/container/btree_set.h"
-#include "absl/container/btree_test.h"
-#include "absl/container/flat_hash_map.h"
-#include "absl/container/flat_hash_set.h"
-#include "absl/container/internal/hashtable_debug.h"
-#include "absl/hash/hash.h"
-#include "absl/log/log.h"
-#include "absl/memory/memory.h"
-#include "absl/random/random.h"
-#include "absl/strings/cord.h"
-#include "absl/strings/str_format.h"
-#include "absl/time/time.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-namespace {
-
-constexpr size_t kBenchmarkValues = 1 << 20;
-
-// How many times we add and remove sub-batches in one batch of *AddRem
-// benchmarks.
-constexpr size_t kAddRemBatchSize = 1 << 2;
-
-// Generates n values in the range [0, 4 * n].
-template <typename V>
-std::vector<V> GenerateValues(int n) {
- constexpr int kSeed = 23;
- return GenerateValuesWithSeed<V>(n, 4 * n, kSeed);
-}
-
-// Benchmark insertion of values into a container.
-template <typename T>
-void BM_InsertImpl(benchmark::State& state, bool sorted) {
- using V = typename remove_pair_const<typename T::value_type>::type;
- typename KeyOfValue<typename T::key_type, V>::type key_of_value;
-
- std::vector<V> values = GenerateValues<V>(kBenchmarkValues);
- if (sorted) {
- std::sort(values.begin(), values.end());
- }
- T container(values.begin(), values.end());
-
- // Remove and re-insert 10% of the keys per batch.
- const int batch_size = (kBenchmarkValues + 9) / 10;
- while (state.KeepRunningBatch(batch_size)) {
- state.PauseTiming();
- const auto i = static_cast<int>(state.iterations());
-
- for (int j = i; j < i + batch_size; j++) {
- int x = j % kBenchmarkValues;
- container.erase(key_of_value(values[x]));
- }
-
- state.ResumeTiming();
-
- for (int j = i; j < i + batch_size; j++) {
- int x = j % kBenchmarkValues;
- container.insert(values[x]);
- }
- }
-}
-
-template <typename T>
-void BM_Insert(benchmark::State& state) {
- BM_InsertImpl<T>(state, false);
-}
-
-template <typename T>
-void BM_InsertSorted(benchmark::State& state) {
- BM_InsertImpl<T>(state, true);
-}
-
-// Benchmark inserting the first few elements in a container. In b-tree, this is
-// when the root node grows.
-template <typename T>
-void BM_InsertSmall(benchmark::State& state) {
- using V = typename remove_pair_const<typename T::value_type>::type;
-
- const int kSize = 8;
- std::vector<V> values = GenerateValues<V>(kSize);
- T container;
-
- while (state.KeepRunningBatch(kSize)) {
- for (int i = 0; i < kSize; ++i) {
- benchmark::DoNotOptimize(container.insert(values[i]));
- }
- state.PauseTiming();
- // Do not measure the time it takes to clear the container.
- container.clear();
- state.ResumeTiming();
- }
-}
-
-template <typename T>
-void BM_LookupImpl(benchmark::State& state, bool sorted) {
- using V = typename remove_pair_const<typename T::value_type>::type;
- typename KeyOfValue<typename T::key_type, V>::type key_of_value;
-
- std::vector<V> values = GenerateValues<V>(kBenchmarkValues);
- if (sorted) {
- std::sort(values.begin(), values.end());
- }
- T container(values.begin(), values.end());
-
- while (state.KeepRunning()) {
- int idx = state.iterations() % kBenchmarkValues;
- benchmark::DoNotOptimize(container.find(key_of_value(values[idx])));
- }
-}
-
-// Benchmark lookup of values in a container.
-template <typename T>
-void BM_Lookup(benchmark::State& state) {
- BM_LookupImpl<T>(state, false);
-}
-
-// Benchmark lookup of values in a full container, meaning that values
-// are inserted in-order to take advantage of biased insertion, which
-// yields a full tree.
-template <typename T>
-void BM_FullLookup(benchmark::State& state) {
- BM_LookupImpl<T>(state, true);
-}
-
-// Benchmark erasing values from a container.
-template <typename T>
-void BM_Erase(benchmark::State& state) {
- using V = typename remove_pair_const<typename T::value_type>::type;
- typename KeyOfValue<typename T::key_type, V>::type key_of_value;
- std::vector<V> values = GenerateValues<V>(kBenchmarkValues);
- T container(values.begin(), values.end());
-
- // Remove and re-insert 10% of the keys per batch.
- const int batch_size = (kBenchmarkValues + 9) / 10;
- while (state.KeepRunningBatch(batch_size)) {
- const int i = state.iterations();
-
- for (int j = i; j < i + batch_size; j++) {
- int x = j % kBenchmarkValues;
- container.erase(key_of_value(values[x]));
- }
-
- state.PauseTiming();
- for (int j = i; j < i + batch_size; j++) {
- int x = j % kBenchmarkValues;
- container.insert(values[x]);
- }
- state.ResumeTiming();
- }
-}
-
-// Benchmark erasing multiple values from a container.
-template <typename T>
-void BM_EraseRange(benchmark::State& state) {
- using V = typename remove_pair_const<typename T::value_type>::type;
- typename KeyOfValue<typename T::key_type, V>::type key_of_value;
- std::vector<V> values = GenerateValues<V>(kBenchmarkValues);
- T container(values.begin(), values.end());
-
- // Remove and re-insert 10% of the keys per batch.
- const int batch_size = (kBenchmarkValues + 9) / 10;
- while (state.KeepRunningBatch(batch_size)) {
- const int i = state.iterations();
-
- const int start_index = i % kBenchmarkValues;
-
- state.PauseTiming();
- {
- std::vector<V> removed;
- removed.reserve(batch_size);
- auto itr = container.find(key_of_value(values[start_index]));
- auto start = itr;
- for (int j = 0; j < batch_size; j++) {
- if (itr == container.end()) {
- state.ResumeTiming();
- container.erase(start, itr);
- state.PauseTiming();
- itr = container.begin();
- start = itr;
- }
- removed.push_back(*itr++);
- }
-
- state.ResumeTiming();
- container.erase(start, itr);
- state.PauseTiming();
-
- container.insert(removed.begin(), removed.end());
- }
- state.ResumeTiming();
- }
-}
-
-// Predicate that erases every other element. We can't use a lambda because
-// C++11 doesn't support generic lambdas.
-// TODO(b/207389011): consider adding benchmarks that remove different fractions
-// of keys (e.g. 10%, 90%).
-struct EraseIfPred {
- uint64_t i = 0;
- template <typename T>
- bool operator()(const T&) {
- return ++i % 2;
- }
-};
-
-// Benchmark erasing multiple values from a container with a predicate.
-template <typename T>
-void BM_EraseIf(benchmark::State& state) {
- using V = typename remove_pair_const<typename T::value_type>::type;
- std::vector<V> values = GenerateValues<V>(kBenchmarkValues);
-
- // Removes half of the keys per batch.
- const int batch_size = (kBenchmarkValues + 1) / 2;
- EraseIfPred pred;
- while (state.KeepRunningBatch(batch_size)) {
- state.PauseTiming();
- {
- T container(values.begin(), values.end());
- state.ResumeTiming();
- erase_if(container, pred);
- benchmark::DoNotOptimize(container);
- state.PauseTiming();
- }
- state.ResumeTiming();
- }
-}
-
-// Benchmark steady-state insert (into first half of range) and remove (from
-// second half of range), treating the container approximately like a queue with
-// log-time access for all elements. This benchmark does not test the case where
-// insertion and removal happen in the same region of the tree. This benchmark
-// counts two value constructors.
-template <typename T>
-void BM_QueueAddRem(benchmark::State& state) {
- using V = typename remove_pair_const<typename T::value_type>::type;
- typename KeyOfValue<typename T::key_type, V>::type key_of_value;
-
- ABSL_RAW_CHECK(kBenchmarkValues % 2 == 0, "for performance");
-
- T container;
-
- const size_t half = kBenchmarkValues / 2;
- std::vector<int> remove_keys(half);
- std::vector<int> add_keys(half);
-
- // We want to do the exact same work repeatedly, and the benchmark can end
- // after a different number of iterations depending on the speed of the
- // individual run so we use a large batch size here and ensure that we do
- // deterministic work every batch.
- while (state.KeepRunningBatch(half * kAddRemBatchSize)) {
- state.PauseTiming();
-
- container.clear();
-
- for (size_t i = 0; i < half; ++i) {
- remove_keys[i] = i;
- add_keys[i] = i;
- }
- constexpr int kSeed = 5;
- std::mt19937_64 rand(kSeed);
- std::shuffle(remove_keys.begin(), remove_keys.end(), rand);
- std::shuffle(add_keys.begin(), add_keys.end(), rand);
-
- // Note needs lazy generation of values.
- Generator<V> g(kBenchmarkValues * kAddRemBatchSize);
-
- for (size_t i = 0; i < half; ++i) {
- container.insert(g(add_keys[i]));
- container.insert(g(half + remove_keys[i]));
- }
-
- // There are three parts each of size "half":
- // 1 is being deleted from [offset - half, offset)
- // 2 is standing [offset, offset + half)
- // 3 is being inserted into [offset + half, offset + 2 * half)
- size_t offset = 0;
-
- for (size_t i = 0; i < kAddRemBatchSize; ++i) {
- std::shuffle(remove_keys.begin(), remove_keys.end(), rand);
- std::shuffle(add_keys.begin(), add_keys.end(), rand);
- offset += half;
-
- state.ResumeTiming();
- for (size_t idx = 0; idx < half; ++idx) {
- container.erase(key_of_value(g(offset - half + remove_keys[idx])));
- container.insert(g(offset + half + add_keys[idx]));
- }
- state.PauseTiming();
- }
- state.ResumeTiming();
- }
-}
-
-// Mixed insertion and deletion in the same range using pre-constructed values.
-template <typename T>
-void BM_MixedAddRem(benchmark::State& state) {
- using V = typename remove_pair_const<typename T::value_type>::type;
- typename KeyOfValue<typename T::key_type, V>::type key_of_value;
-
- ABSL_RAW_CHECK(kBenchmarkValues % 2 == 0, "for performance");
-
- T container;
-
- // Create two random shuffles
- std::vector<int> remove_keys(kBenchmarkValues);
- std::vector<int> add_keys(kBenchmarkValues);
-
- // We want to do the exact same work repeatedly, and the benchmark can end
- // after a different number of iterations depending on the speed of the
- // individual run so we use a large batch size here and ensure that we do
- // deterministic work every batch.
- while (state.KeepRunningBatch(kBenchmarkValues * kAddRemBatchSize)) {
- state.PauseTiming();
-
- container.clear();
-
- constexpr int kSeed = 7;
- std::mt19937_64 rand(kSeed);
-
- std::vector<V> values = GenerateValues<V>(kBenchmarkValues * 2);
-
- // Insert the first half of the values (already in random order)
- container.insert(values.begin(), values.begin() + kBenchmarkValues);
-
- // Insert the first half of the values (already in random order)
- for (size_t i = 0; i < kBenchmarkValues; ++i) {
- // remove_keys and add_keys will be swapped before each round,
- // therefore fill add_keys here w/ the keys being inserted, so
- // they'll be the first to be removed.
- remove_keys[i] = i + kBenchmarkValues;
- add_keys[i] = i;
- }
-
- for (size_t i = 0; i < kAddRemBatchSize; ++i) {
- remove_keys.swap(add_keys);
- std::shuffle(remove_keys.begin(), remove_keys.end(), rand);
- std::shuffle(add_keys.begin(), add_keys.end(), rand);
-
- state.ResumeTiming();
- for (size_t idx = 0; idx < kBenchmarkValues; ++idx) {
- container.erase(key_of_value(values[remove_keys[idx]]));
- container.insert(values[add_keys[idx]]);
- }
- state.PauseTiming();
- }
- state.ResumeTiming();
- }
-}
-
-// Insertion at end, removal from the beginning. This benchmark
-// counts two value constructors.
-// TODO(ezb): we could add a GenerateNext version of generator that could reduce
-// noise for string-like types.
-template <typename T>
-void BM_Fifo(benchmark::State& state) {
- using V = typename remove_pair_const<typename T::value_type>::type;
-
- T container;
- // Need lazy generation of values as state.max_iterations is large.
- Generator<V> g(kBenchmarkValues + state.max_iterations);
-
- for (int i = 0; i < kBenchmarkValues; i++) {
- container.insert(g(i));
- }
-
- while (state.KeepRunning()) {
- container.erase(container.begin());
- container.insert(container.end(), g(state.iterations() + kBenchmarkValues));
- }
-}
-
-// Iteration (forward) through the tree
-template <typename T>
-void BM_FwdIter(benchmark::State& state) {
- using V = typename remove_pair_const<typename T::value_type>::type;
- using R = typename T::value_type const*;
-
- std::vector<V> values = GenerateValues<V>(kBenchmarkValues);
- T container(values.begin(), values.end());
-
- auto iter = container.end();
-
- R r = nullptr;
-
- while (state.KeepRunning()) {
- if (iter == container.end()) iter = container.begin();
- r = &(*iter);
- ++iter;
- }
-
- benchmark::DoNotOptimize(r);
-}
-
-// Benchmark random range-construction of a container.
-template <typename T>
-void BM_RangeConstructionImpl(benchmark::State& state, bool sorted) {
- using V = typename remove_pair_const<typename T::value_type>::type;
-
- std::vector<V> values = GenerateValues<V>(kBenchmarkValues);
- if (sorted) {
- std::sort(values.begin(), values.end());
- }
- {
- T container(values.begin(), values.end());
- }
-
- while (state.KeepRunning()) {
- T container(values.begin(), values.end());
- benchmark::DoNotOptimize(container);
- }
-}
-
-template <typename T>
-void BM_InsertRangeRandom(benchmark::State& state) {
- BM_RangeConstructionImpl<T>(state, false);
-}
-
-template <typename T>
-void BM_InsertRangeSorted(benchmark::State& state) {
- BM_RangeConstructionImpl<T>(state, true);
-}
-
-#define STL_ORDERED_TYPES(value) \
- using stl_set_##value = std::set<value>; \
- using stl_map_##value = std::map<value, intptr_t>; \
- using stl_multiset_##value = std::multiset<value>; \
- using stl_multimap_##value = std::multimap<value, intptr_t>
-
-using StdString = std::string;
-STL_ORDERED_TYPES(int32_t);
-STL_ORDERED_TYPES(int64_t);
-STL_ORDERED_TYPES(StdString);
-STL_ORDERED_TYPES(Cord);
-STL_ORDERED_TYPES(Time);
-
-#define STL_UNORDERED_TYPES(value) \
- using stl_unordered_set_##value = std::unordered_set<value>; \
- using stl_unordered_map_##value = std::unordered_map<value, intptr_t>; \
- using flat_hash_set_##value = flat_hash_set<value>; \
- using flat_hash_map_##value = flat_hash_map<value, intptr_t>; \
- using stl_unordered_multiset_##value = std::unordered_multiset<value>; \
- using stl_unordered_multimap_##value = \
- std::unordered_multimap<value, intptr_t>
-
-#define STL_UNORDERED_TYPES_CUSTOM_HASH(value, hash) \
- using stl_unordered_set_##value = std::unordered_set<value, hash>; \
- using stl_unordered_map_##value = std::unordered_map<value, intptr_t, hash>; \
- using flat_hash_set_##value = flat_hash_set<value, hash>; \
- using flat_hash_map_##value = flat_hash_map<value, intptr_t, hash>; \
- using stl_unordered_multiset_##value = std::unordered_multiset<value, hash>; \
- using stl_unordered_multimap_##value = \
- std::unordered_multimap<value, intptr_t, hash>
-
-STL_UNORDERED_TYPES_CUSTOM_HASH(Cord, absl::Hash<absl::Cord>);
-
-STL_UNORDERED_TYPES(int32_t);
-STL_UNORDERED_TYPES(int64_t);
-STL_UNORDERED_TYPES(StdString);
-STL_UNORDERED_TYPES_CUSTOM_HASH(Time, absl::Hash<absl::Time>);
-
-#define BTREE_TYPES(value) \
- using btree_256_set_##value = \
- btree_set<value, std::less<value>, std::allocator<value>>; \
- using btree_256_map_##value = \
- btree_map<value, intptr_t, std::less<value>, \
- std::allocator<std::pair<const value, intptr_t>>>; \
- using btree_256_multiset_##value = \
- btree_multiset<value, std::less<value>, std::allocator<value>>; \
- using btree_256_multimap_##value = \
- btree_multimap<value, intptr_t, std::less<value>, \
- std::allocator<std::pair<const value, intptr_t>>>
-
-BTREE_TYPES(int32_t);
-BTREE_TYPES(int64_t);
-BTREE_TYPES(StdString);
-BTREE_TYPES(Cord);
-BTREE_TYPES(Time);
-
-#define MY_BENCHMARK4(type, func) \
- void BM_##type##_##func(benchmark::State& state) { BM_##func<type>(state); } \
- BENCHMARK(BM_##type##_##func)
-
-#define MY_BENCHMARK3_STL(type) \
- MY_BENCHMARK4(type, Insert); \
- MY_BENCHMARK4(type, InsertSorted); \
- MY_BENCHMARK4(type, InsertSmall); \
- MY_BENCHMARK4(type, Lookup); \
- MY_BENCHMARK4(type, FullLookup); \
- MY_BENCHMARK4(type, Erase); \
- MY_BENCHMARK4(type, EraseRange); \
- MY_BENCHMARK4(type, QueueAddRem); \
- MY_BENCHMARK4(type, MixedAddRem); \
- MY_BENCHMARK4(type, Fifo); \
- MY_BENCHMARK4(type, FwdIter); \
- MY_BENCHMARK4(type, InsertRangeRandom); \
- MY_BENCHMARK4(type, InsertRangeSorted)
-
-#define MY_BENCHMARK3(type) \
- MY_BENCHMARK4(type, EraseIf); \
- MY_BENCHMARK3_STL(type)
-
-#define MY_BENCHMARK2_SUPPORTS_MULTI_ONLY(type) \
- MY_BENCHMARK3_STL(stl_##type); \
- MY_BENCHMARK3_STL(stl_unordered_##type); \
- MY_BENCHMARK3(btree_256_##type)
-
-#define MY_BENCHMARK2(type) \
- MY_BENCHMARK2_SUPPORTS_MULTI_ONLY(type); \
- MY_BENCHMARK3(flat_hash_##type)
-
-// Define MULTI_TESTING to see benchmarks for multi-containers also.
-//
-// You can use --copt=-DMULTI_TESTING.
-#ifdef MULTI_TESTING
-#define MY_BENCHMARK(type) \
- MY_BENCHMARK2(set_##type); \
- MY_BENCHMARK2(map_##type); \
- MY_BENCHMARK2_SUPPORTS_MULTI_ONLY(multiset_##type); \
- MY_BENCHMARK2_SUPPORTS_MULTI_ONLY(multimap_##type)
-#else
-#define MY_BENCHMARK(type) \
- MY_BENCHMARK2(set_##type); \
- MY_BENCHMARK2(map_##type)
-#endif
-
-MY_BENCHMARK(int32_t);
-MY_BENCHMARK(int64_t);
-MY_BENCHMARK(StdString);
-MY_BENCHMARK(Cord);
-MY_BENCHMARK(Time);
-
-// Define a type whose size and cost of moving are independently customizable.
-// When sizeof(value_type) increases, we expect btree to no longer have as much
-// cache-locality advantage over STL. When cost of moving increases, we expect
-// btree to actually do more work than STL because it has to move values around
-// and STL doesn't have to.
-template <int Size, int Copies>
-struct BigType {
- BigType() : BigType(0) {}
- explicit BigType(int x) { std::iota(values.begin(), values.end(), x); }
-
- void Copy(const BigType& other) {
- for (int i = 0; i < Size && i < Copies; ++i) values[i] = other.values[i];
- // If Copies > Size, do extra copies.
- for (int i = Size, idx = 0; i < Copies; ++i) {
- int64_t tmp = other.values[idx];
- benchmark::DoNotOptimize(tmp);
- idx = idx + 1 == Size ? 0 : idx + 1;
- }
- }
-
- BigType(const BigType& other) { Copy(other); }
- BigType& operator=(const BigType& other) {
- Copy(other);
- return *this;
- }
-
- // Compare only the first Copies elements if Copies is less than Size.
- bool operator<(const BigType& other) const {
- return std::lexicographical_compare(
- values.begin(), values.begin() + std::min(Size, Copies),
- other.values.begin(), other.values.begin() + std::min(Size, Copies));
- }
- bool operator==(const BigType& other) const {
- return std::equal(values.begin(), values.begin() + std::min(Size, Copies),
- other.values.begin());
- }
-
- // Support absl::Hash.
- template <typename State>
- friend State AbslHashValue(State h, const BigType& b) {
- for (int i = 0; i < Size && i < Copies; ++i)
- h = State::combine(std::move(h), b.values[i]);
- return h;
- }
-
- std::array<int64_t, Size> values;
-};
-
-#define BIG_TYPE_BENCHMARKS(SIZE, COPIES) \
- using stl_set_size##SIZE##copies##COPIES = std::set<BigType<SIZE, COPIES>>; \
- using stl_map_size##SIZE##copies##COPIES = \
- std::map<BigType<SIZE, COPIES>, intptr_t>; \
- using stl_multiset_size##SIZE##copies##COPIES = \
- std::multiset<BigType<SIZE, COPIES>>; \
- using stl_multimap_size##SIZE##copies##COPIES = \
- std::multimap<BigType<SIZE, COPIES>, intptr_t>; \
- using stl_unordered_set_size##SIZE##copies##COPIES = \
- std::unordered_set<BigType<SIZE, COPIES>, \
- absl::Hash<BigType<SIZE, COPIES>>>; \
- using stl_unordered_map_size##SIZE##copies##COPIES = \
- std::unordered_map<BigType<SIZE, COPIES>, intptr_t, \
- absl::Hash<BigType<SIZE, COPIES>>>; \
- using flat_hash_set_size##SIZE##copies##COPIES = \
- flat_hash_set<BigType<SIZE, COPIES>>; \
- using flat_hash_map_size##SIZE##copies##COPIES = \
- flat_hash_map<BigType<SIZE, COPIES>, intptr_t>; \
- using stl_unordered_multiset_size##SIZE##copies##COPIES = \
- std::unordered_multiset<BigType<SIZE, COPIES>, \
- absl::Hash<BigType<SIZE, COPIES>>>; \
- using stl_unordered_multimap_size##SIZE##copies##COPIES = \
- std::unordered_multimap<BigType<SIZE, COPIES>, intptr_t, \
- absl::Hash<BigType<SIZE, COPIES>>>; \
- using btree_256_set_size##SIZE##copies##COPIES = \
- btree_set<BigType<SIZE, COPIES>>; \
- using btree_256_map_size##SIZE##copies##COPIES = \
- btree_map<BigType<SIZE, COPIES>, intptr_t>; \
- using btree_256_multiset_size##SIZE##copies##COPIES = \
- btree_multiset<BigType<SIZE, COPIES>>; \
- using btree_256_multimap_size##SIZE##copies##COPIES = \
- btree_multimap<BigType<SIZE, COPIES>, intptr_t>; \
- MY_BENCHMARK(size##SIZE##copies##COPIES)
-
-// Define BIG_TYPE_TESTING to see benchmarks for more big types.
-//
-// You can use --copt=-DBIG_TYPE_TESTING.
-#ifndef NODESIZE_TESTING
-#ifdef BIG_TYPE_TESTING
-BIG_TYPE_BENCHMARKS(1, 4);
-BIG_TYPE_BENCHMARKS(4, 1);
-BIG_TYPE_BENCHMARKS(4, 4);
-BIG_TYPE_BENCHMARKS(1, 8);
-BIG_TYPE_BENCHMARKS(8, 1);
-BIG_TYPE_BENCHMARKS(8, 8);
-BIG_TYPE_BENCHMARKS(1, 16);
-BIG_TYPE_BENCHMARKS(16, 1);
-BIG_TYPE_BENCHMARKS(16, 16);
-BIG_TYPE_BENCHMARKS(1, 32);
-BIG_TYPE_BENCHMARKS(32, 1);
-BIG_TYPE_BENCHMARKS(32, 32);
-#else
-BIG_TYPE_BENCHMARKS(32, 32);
-#endif
-#endif
-
-// Benchmark using unique_ptrs to large value types. In order to be able to use
-// the same benchmark code as the other types, use a type that holds a
-// unique_ptr and has a copy constructor.
-template <int Size>
-struct BigTypePtr {
- BigTypePtr() : BigTypePtr(0) {}
- explicit BigTypePtr(int x) {
- ptr = absl::make_unique<BigType<Size, Size>>(x);
- }
- BigTypePtr(const BigTypePtr& other) {
- ptr = absl::make_unique<BigType<Size, Size>>(*other.ptr);
- }
- BigTypePtr(BigTypePtr&& other) noexcept = default;
- BigTypePtr& operator=(const BigTypePtr& other) {
- ptr = absl::make_unique<BigType<Size, Size>>(*other.ptr);
- }
- BigTypePtr& operator=(BigTypePtr&& other) noexcept = default;
-
- bool operator<(const BigTypePtr& other) const { return *ptr < *other.ptr; }
- bool operator==(const BigTypePtr& other) const { return *ptr == *other.ptr; }
-
- std::unique_ptr<BigType<Size, Size>> ptr;
-};
-
-template <int Size>
-double ContainerInfo(const btree_set<BigTypePtr<Size>>& b) {
- const double bytes_used =
- b.bytes_used() + b.size() * sizeof(BigType<Size, Size>);
- const double bytes_per_value = bytes_used / b.size();
- BtreeContainerInfoLog(b, bytes_used, bytes_per_value);
- return bytes_per_value;
-}
-template <int Size>
-double ContainerInfo(const btree_map<int, BigTypePtr<Size>>& b) {
- const double bytes_used =
- b.bytes_used() + b.size() * sizeof(BigType<Size, Size>);
- const double bytes_per_value = bytes_used / b.size();
- BtreeContainerInfoLog(b, bytes_used, bytes_per_value);
- return bytes_per_value;
-}
-
-#define BIG_TYPE_PTR_BENCHMARKS(SIZE) \
- using stl_set_size##SIZE##copies##SIZE##ptr = std::set<BigType<SIZE, SIZE>>; \
- using stl_map_size##SIZE##copies##SIZE##ptr = \
- std::map<int, BigType<SIZE, SIZE>>; \
- using stl_unordered_set_size##SIZE##copies##SIZE##ptr = \
- std::unordered_set<BigType<SIZE, SIZE>, \
- absl::Hash<BigType<SIZE, SIZE>>>; \
- using stl_unordered_map_size##SIZE##copies##SIZE##ptr = \
- std::unordered_map<int, BigType<SIZE, SIZE>>; \
- using flat_hash_set_size##SIZE##copies##SIZE##ptr = \
- flat_hash_set<BigType<SIZE, SIZE>>; \
- using flat_hash_map_size##SIZE##copies##SIZE##ptr = \
- flat_hash_map<int, BigTypePtr<SIZE>>; \
- using btree_256_set_size##SIZE##copies##SIZE##ptr = \
- btree_set<BigTypePtr<SIZE>>; \
- using btree_256_map_size##SIZE##copies##SIZE##ptr = \
- btree_map<int, BigTypePtr<SIZE>>; \
- MY_BENCHMARK3_STL(stl_set_size##SIZE##copies##SIZE##ptr); \
- MY_BENCHMARK3_STL(stl_unordered_set_size##SIZE##copies##SIZE##ptr); \
- MY_BENCHMARK3(flat_hash_set_size##SIZE##copies##SIZE##ptr); \
- MY_BENCHMARK3(btree_256_set_size##SIZE##copies##SIZE##ptr); \
- MY_BENCHMARK3_STL(stl_map_size##SIZE##copies##SIZE##ptr); \
- MY_BENCHMARK3_STL(stl_unordered_map_size##SIZE##copies##SIZE##ptr); \
- MY_BENCHMARK3(flat_hash_map_size##SIZE##copies##SIZE##ptr); \
- MY_BENCHMARK3(btree_256_map_size##SIZE##copies##SIZE##ptr)
-
-BIG_TYPE_PTR_BENCHMARKS(32);
-
-void BM_BtreeSet_IteratorSubtraction(benchmark::State& state) {
- absl::InsecureBitGen bitgen;
- std::vector<int> vec;
- // Randomize the set's insertion order so the nodes aren't all full.
- vec.reserve(state.range(0));
- for (int i = 0; i < state.range(0); ++i) vec.push_back(i);
- absl::c_shuffle(vec, bitgen);
-
- absl::btree_set<int> set;
- for (int i : vec) set.insert(i);
-
- size_t distance = absl::Uniform(bitgen, 0u, set.size());
- while (state.KeepRunningBatch(distance)) {
- size_t end = absl::Uniform(bitgen, distance, set.size());
- size_t begin = end - distance;
- benchmark::DoNotOptimize(set.find(static_cast<int>(end)) -
- set.find(static_cast<int>(begin)));
- distance = absl::Uniform(bitgen, 0u, set.size());
- }
-}
-
-BENCHMARK(BM_BtreeSet_IteratorSubtraction)->Range(1 << 10, 1 << 20);
-
-} // namespace
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/container/btree_map.h b/third_party/abseil-cpp/absl/container/btree_map.h
deleted file mode 100644
index 819a925..0000000
--- a/third_party/abseil-cpp/absl/container/btree_map.h
+++ /dev/null
@@ -1,855 +0,0 @@
-// Copyright 2018 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.
-//
-// -----------------------------------------------------------------------------
-// File: btree_map.h
-// -----------------------------------------------------------------------------
-//
-// This header file defines B-tree maps: sorted associative containers mapping
-// keys to values.
-//
-// * `absl::btree_map<>`
-// * `absl::btree_multimap<>`
-//
-// These B-tree types are similar to the corresponding types in the STL
-// (`std::map` and `std::multimap`) and generally conform to the STL interfaces
-// of those types. However, because they are implemented using B-trees, they
-// are more efficient in most situations.
-//
-// Unlike `std::map` and `std::multimap`, which are commonly implemented using
-// red-black tree nodes, B-tree maps use more generic B-tree nodes able to hold
-// multiple values per node. Holding multiple values per node often makes
-// B-tree maps perform better than their `std::map` counterparts, because
-// multiple entries can be checked within the same cache hit.
-//
-// However, these types should not be considered drop-in replacements for
-// `std::map` and `std::multimap` as there are some API differences, which are
-// noted in this header file. The most consequential differences with respect to
-// migrating to b-tree from the STL types are listed in the next paragraph.
-// Other API differences are minor.
-//
-// Importantly, insertions and deletions may invalidate outstanding iterators,
-// pointers, and references to elements. Such invalidations are typically only
-// an issue if insertion and deletion operations are interleaved with the use of
-// more than one iterator, pointer, or reference simultaneously. For this
-// reason, `insert()` and `erase()` return a valid iterator at the current
-// position (and `extract()` cannot be used in this way). Another important
-// difference is that key-types must be copy-constructible.
-//
-// Another API difference is that btree iterators can be subtracted, and this
-// is faster than using std::distance.
-
-#ifndef ABSL_CONTAINER_BTREE_MAP_H_
-#define ABSL_CONTAINER_BTREE_MAP_H_
-
-#include "absl/container/internal/btree.h" // IWYU pragma: export
-#include "absl/container/internal/btree_container.h" // IWYU pragma: export
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-
-namespace container_internal {
-
-template <typename Key, typename Data, typename Compare, typename Alloc,
- int TargetNodeSize, bool IsMulti>
-struct map_params;
-
-} // namespace container_internal
-
-// absl::btree_map<>
-//
-// An `absl::btree_map<K, V>` is an ordered associative container of
-// unique keys and associated values designed to be a more efficient replacement
-// for `std::map` (in most cases).
-//
-// Keys are sorted using an (optional) comparison function, which defaults to
-// `std::less<K>`.
-//
-// An `absl::btree_map<K, V>` uses a default allocator of
-// `std::allocator<std::pair<const K, V>>` to allocate (and deallocate)
-// nodes, and construct and destruct values within those nodes. You may
-// instead specify a custom allocator `A` (which in turn requires specifying a
-// custom comparator `C`) as in `absl::btree_map<K, V, C, A>`.
-//
-template <typename Key, typename Value, typename Compare = std::less<Key>,
- typename Alloc = std::allocator<std::pair<const Key, Value>>>
-class btree_map
- : public container_internal::btree_map_container<
- container_internal::btree<container_internal::map_params<
- Key, Value, Compare, Alloc, /*TargetNodeSize=*/256,
- /*IsMulti=*/false>>> {
- using Base = typename btree_map::btree_map_container;
-
- public:
- // Constructors and Assignment Operators
- //
- // A `btree_map` supports the same overload set as `std::map`
- // for construction and assignment:
- //
- // * Default constructor
- //
- // absl::btree_map<int, std::string> map1;
- //
- // * Initializer List constructor
- //
- // absl::btree_map<int, std::string> map2 =
- // {{1, "huey"}, {2, "dewey"}, {3, "louie"},};
- //
- // * Copy constructor
- //
- // absl::btree_map<int, std::string> map3(map2);
- //
- // * Copy assignment operator
- //
- // absl::btree_map<int, std::string> map4;
- // map4 = map3;
- //
- // * Move constructor
- //
- // // Move is guaranteed efficient
- // absl::btree_map<int, std::string> map5(std::move(map4));
- //
- // * Move assignment operator
- //
- // // May be efficient if allocators are compatible
- // absl::btree_map<int, std::string> map6;
- // map6 = std::move(map5);
- //
- // * Range constructor
- //
- // std::vector<std::pair<int, std::string>> v = {{1, "a"}, {2, "b"}};
- // absl::btree_map<int, std::string> map7(v.begin(), v.end());
- btree_map() {}
- using Base::Base;
-
- // btree_map::begin()
- //
- // Returns an iterator to the beginning of the `btree_map`.
- using Base::begin;
-
- // btree_map::cbegin()
- //
- // Returns a const iterator to the beginning of the `btree_map`.
- using Base::cbegin;
-
- // btree_map::end()
- //
- // Returns an iterator to the end of the `btree_map`.
- using Base::end;
-
- // btree_map::cend()
- //
- // Returns a const iterator to the end of the `btree_map`.
- using Base::cend;
-
- // btree_map::empty()
- //
- // Returns whether or not the `btree_map` is empty.
- using Base::empty;
-
- // btree_map::max_size()
- //
- // Returns the largest theoretical possible number of elements within a
- // `btree_map` under current memory constraints. This value can be thought
- // of as the largest value of `std::distance(begin(), end())` for a
- // `btree_map<Key, T>`.
- using Base::max_size;
-
- // btree_map::size()
- //
- // Returns the number of elements currently within the `btree_map`.
- using Base::size;
-
- // btree_map::clear()
- //
- // Removes all elements from the `btree_map`. Invalidates any references,
- // pointers, or iterators referring to contained elements.
- using Base::clear;
-
- // btree_map::erase()
- //
- // Erases elements within the `btree_map`. If an erase occurs, any references,
- // pointers, or iterators are invalidated.
- // Overloads are listed below.
- //
- // iterator erase(iterator position):
- // iterator erase(const_iterator position):
- //
- // Erases the element at `position` of the `btree_map`, returning
- // the iterator pointing to the element after the one that was erased
- // (or end() if none exists).
- //
- // iterator erase(const_iterator first, const_iterator last):
- //
- // Erases the elements in the open interval [`first`, `last`), returning
- // the iterator pointing to the element after the interval that was erased
- // (or end() if none exists).
- //
- // template <typename K> size_type erase(const K& key):
- //
- // Erases the element with the matching key, if it exists, returning the
- // number of elements erased (0 or 1).
- using Base::erase;
-
- // btree_map::insert()
- //
- // Inserts an element of the specified value into the `btree_map`,
- // returning an iterator pointing to the newly inserted element, provided that
- // an element with the given key does not already exist. If an insertion
- // occurs, any references, pointers, or iterators are invalidated.
- // Overloads are listed below.
- //
- // std::pair<iterator,bool> insert(const value_type& value):
- //
- // Inserts a value into the `btree_map`. Returns a pair consisting of an
- // iterator to the inserted element (or to the element that prevented the
- // insertion) and a bool denoting whether the insertion took place.
- //
- // std::pair<iterator,bool> insert(value_type&& value):
- //
- // Inserts a moveable value into the `btree_map`. Returns a pair
- // consisting of an iterator to the inserted element (or to the element that
- // prevented the insertion) and a bool denoting whether the insertion took
- // place.
- //
- // iterator insert(const_iterator hint, const value_type& value):
- // iterator insert(const_iterator hint, value_type&& value):
- //
- // Inserts a value, using the position of `hint` as a non-binding suggestion
- // for where to begin the insertion search. Returns an iterator to the
- // inserted element, or to the existing element that prevented the
- // insertion.
- //
- // void insert(InputIterator first, InputIterator last):
- //
- // Inserts a range of values [`first`, `last`).
- //
- // void insert(std::initializer_list<init_type> ilist):
- //
- // Inserts the elements within the initializer list `ilist`.
- using Base::insert;
-
- // btree_map::insert_or_assign()
- //
- // Inserts an element of the specified value into the `btree_map` provided
- // that a value with the given key does not already exist, or replaces the
- // corresponding mapped type with the forwarded `obj` argument if a key for
- // that value already exists, returning an iterator pointing to the newly
- // inserted element. Overloads are listed below.
- //
- // pair<iterator, bool> insert_or_assign(const key_type& k, M&& obj):
- // pair<iterator, bool> insert_or_assign(key_type&& k, M&& obj):
- //
- // Inserts/Assigns (or moves) the element of the specified key into the
- // `btree_map`. If the returned bool is true, insertion took place, and if
- // it's false, assignment took place.
- //
- // iterator insert_or_assign(const_iterator hint,
- // const key_type& k, M&& obj):
- // iterator insert_or_assign(const_iterator hint, key_type&& k, M&& obj):
- //
- // Inserts/Assigns (or moves) the element of the specified key into the
- // `btree_map` using the position of `hint` as a non-binding suggestion
- // for where to begin the insertion search.
- using Base::insert_or_assign;
-
- // btree_map::emplace()
- //
- // Inserts an element of the specified value by constructing it in-place
- // within the `btree_map`, provided that no element with the given key
- // already exists.
- //
- // The element may be constructed even if there already is an element with the
- // key in the container, in which case the newly constructed element will be
- // destroyed immediately. Prefer `try_emplace()` unless your key is not
- // copyable or moveable.
- //
- // If an insertion occurs, any references, pointers, or iterators are
- // invalidated.
- using Base::emplace;
-
- // btree_map::emplace_hint()
- //
- // Inserts an element of the specified value by constructing it in-place
- // within the `btree_map`, using the position of `hint` as a non-binding
- // suggestion for where to begin the insertion search, and only inserts
- // provided that no element with the given key already exists.
- //
- // The element may be constructed even if there already is an element with the
- // key in the container, in which case the newly constructed element will be
- // destroyed immediately. Prefer `try_emplace()` unless your key is not
- // copyable or moveable.
- //
- // If an insertion occurs, any references, pointers, or iterators are
- // invalidated.
- using Base::emplace_hint;
-
- // btree_map::try_emplace()
- //
- // Inserts an element of the specified value by constructing it in-place
- // within the `btree_map`, provided that no element with the given key
- // already exists. Unlike `emplace()`, if an element with the given key
- // already exists, we guarantee that no element is constructed.
- //
- // If an insertion occurs, any references, pointers, or iterators are
- // invalidated.
- //
- // Overloads are listed below.
- //
- // std::pair<iterator, bool> try_emplace(const key_type& k, Args&&... args):
- // std::pair<iterator, bool> try_emplace(key_type&& k, Args&&... args):
- //
- // Inserts (via copy or move) the element of the specified key into the
- // `btree_map`.
- //
- // iterator try_emplace(const_iterator hint,
- // const key_type& k, Args&&... args):
- // iterator try_emplace(const_iterator hint, key_type&& k, Args&&... args):
- //
- // Inserts (via copy or move) the element of the specified key into the
- // `btree_map` using the position of `hint` as a non-binding suggestion
- // for where to begin the insertion search.
- using Base::try_emplace;
-
- // btree_map::extract()
- //
- // Extracts the indicated element, erasing it in the process, and returns it
- // as a C++17-compatible node handle. Any references, pointers, or iterators
- // are invalidated. Overloads are listed below.
- //
- // node_type extract(const_iterator position):
- //
- // Extracts the element at the indicated position and returns a node handle
- // owning that extracted data.
- //
- // template <typename K> node_type extract(const K& k):
- //
- // Extracts the element with the key matching the passed key value and
- // returns a node handle owning that extracted data. If the `btree_map`
- // does not contain an element with a matching key, this function returns an
- // empty node handle.
- //
- // NOTE: when compiled in an earlier version of C++ than C++17,
- // `node_type::key()` returns a const reference to the key instead of a
- // mutable reference. We cannot safely return a mutable reference without
- // std::launder (which is not available before C++17).
- //
- // NOTE: In this context, `node_type` refers to the C++17 concept of a
- // move-only type that owns and provides access to the elements in associative
- // containers (https://en.cppreference.com/w/cpp/container/node_handle).
- // It does NOT refer to the data layout of the underlying btree.
- using Base::extract;
-
- // btree_map::merge()
- //
- // Extracts elements from a given `source` btree_map into this
- // `btree_map`. If the destination `btree_map` already contains an
- // element with an equivalent key, that element is not extracted.
- using Base::merge;
-
- // btree_map::swap(btree_map& other)
- //
- // Exchanges the contents of this `btree_map` with those of the `other`
- // btree_map, avoiding invocation of any move, copy, or swap operations on
- // individual elements.
- //
- // All iterators and references on the `btree_map` remain valid, excepting
- // for the past-the-end iterator, which is invalidated.
- using Base::swap;
-
- // btree_map::at()
- //
- // Returns a reference to the mapped value of the element with key equivalent
- // to the passed key.
- using Base::at;
-
- // btree_map::contains()
- //
- // template <typename K> bool contains(const K& key) const:
- //
- // Determines whether an element comparing equal to the given `key` exists
- // within the `btree_map`, returning `true` if so or `false` otherwise.
- //
- // Supports heterogeneous lookup, provided that the map has a compatible
- // heterogeneous comparator.
- using Base::contains;
-
- // btree_map::count()
- //
- // template <typename K> size_type count(const K& key) const:
- //
- // Returns the number of elements comparing equal to the given `key` within
- // the `btree_map`. Note that this function will return either `1` or `0`
- // since duplicate elements are not allowed within a `btree_map`.
- //
- // Supports heterogeneous lookup, provided that the map has a compatible
- // heterogeneous comparator.
- using Base::count;
-
- // btree_map::equal_range()
- //
- // Returns a half-open range [first, last), defined by a `std::pair` of two
- // iterators, containing all elements with the passed key in the `btree_map`.
- using Base::equal_range;
-
- // btree_map::find()
- //
- // template <typename K> iterator find(const K& key):
- // template <typename K> const_iterator find(const K& key) const:
- //
- // Finds an element with the passed `key` within the `btree_map`.
- //
- // Supports heterogeneous lookup, provided that the map has a compatible
- // heterogeneous comparator.
- using Base::find;
-
- // btree_map::lower_bound()
- //
- // template <typename K> iterator lower_bound(const K& key):
- // template <typename K> const_iterator lower_bound(const K& key) const:
- //
- // Finds the first element with a key that is not less than `key` within the
- // `btree_map`.
- //
- // Supports heterogeneous lookup, provided that the map has a compatible
- // heterogeneous comparator.
- using Base::lower_bound;
-
- // btree_map::upper_bound()
- //
- // template <typename K> iterator upper_bound(const K& key):
- // template <typename K> const_iterator upper_bound(const K& key) const:
- //
- // Finds the first element with a key that is greater than `key` within the
- // `btree_map`.
- //
- // Supports heterogeneous lookup, provided that the map has a compatible
- // heterogeneous comparator.
- using Base::upper_bound;
-
- // btree_map::operator[]()
- //
- // Returns a reference to the value mapped to the passed key within the
- // `btree_map`, performing an `insert()` if the key does not already
- // exist.
- //
- // If an insertion occurs, any references, pointers, or iterators are
- // invalidated. Otherwise iterators are not affected and references are not
- // invalidated. Overloads are listed below.
- //
- // T& operator[](key_type&& key):
- // T& operator[](const key_type& key):
- //
- // Inserts a value_type object constructed in-place if the element with the
- // given key does not exist.
- using Base::operator[];
-
- // btree_map::get_allocator()
- //
- // Returns the allocator function associated with this `btree_map`.
- using Base::get_allocator;
-
- // btree_map::key_comp();
- //
- // Returns the key comparator associated with this `btree_map`.
- using Base::key_comp;
-
- // btree_map::value_comp();
- //
- // Returns the value comparator associated with this `btree_map`.
- using Base::value_comp;
-};
-
-// absl::swap(absl::btree_map<>, absl::btree_map<>)
-//
-// Swaps the contents of two `absl::btree_map` containers.
-template <typename K, typename V, typename C, typename A>
-void swap(btree_map<K, V, C, A> &x, btree_map<K, V, C, A> &y) {
- return x.swap(y);
-}
-
-// absl::erase_if(absl::btree_map<>, Pred)
-//
-// Erases all elements that satisfy the predicate pred from the container.
-// Returns the number of erased elements.
-template <typename K, typename V, typename C, typename A, typename Pred>
-typename btree_map<K, V, C, A>::size_type erase_if(
- btree_map<K, V, C, A> &map, Pred pred) {
- return container_internal::btree_access::erase_if(map, std::move(pred));
-}
-
-// absl::btree_multimap
-//
-// An `absl::btree_multimap<K, V>` is an ordered associative container of
-// keys and associated values designed to be a more efficient replacement for
-// `std::multimap` (in most cases). Unlike `absl::btree_map`, a B-tree multimap
-// allows multiple elements with equivalent keys.
-//
-// Keys are sorted using an (optional) comparison function, which defaults to
-// `std::less<K>`.
-//
-// An `absl::btree_multimap<K, V>` uses a default allocator of
-// `std::allocator<std::pair<const K, V>>` to allocate (and deallocate)
-// nodes, and construct and destruct values within those nodes. You may
-// instead specify a custom allocator `A` (which in turn requires specifying a
-// custom comparator `C`) as in `absl::btree_multimap<K, V, C, A>`.
-//
-template <typename Key, typename Value, typename Compare = std::less<Key>,
- typename Alloc = std::allocator<std::pair<const Key, Value>>>
-class btree_multimap
- : public container_internal::btree_multimap_container<
- container_internal::btree<container_internal::map_params<
- Key, Value, Compare, Alloc, /*TargetNodeSize=*/256,
- /*IsMulti=*/true>>> {
- using Base = typename btree_multimap::btree_multimap_container;
-
- public:
- // Constructors and Assignment Operators
- //
- // A `btree_multimap` supports the same overload set as `std::multimap`
- // for construction and assignment:
- //
- // * Default constructor
- //
- // absl::btree_multimap<int, std::string> map1;
- //
- // * Initializer List constructor
- //
- // absl::btree_multimap<int, std::string> map2 =
- // {{1, "huey"}, {2, "dewey"}, {3, "louie"},};
- //
- // * Copy constructor
- //
- // absl::btree_multimap<int, std::string> map3(map2);
- //
- // * Copy assignment operator
- //
- // absl::btree_multimap<int, std::string> map4;
- // map4 = map3;
- //
- // * Move constructor
- //
- // // Move is guaranteed efficient
- // absl::btree_multimap<int, std::string> map5(std::move(map4));
- //
- // * Move assignment operator
- //
- // // May be efficient if allocators are compatible
- // absl::btree_multimap<int, std::string> map6;
- // map6 = std::move(map5);
- //
- // * Range constructor
- //
- // std::vector<std::pair<int, std::string>> v = {{1, "a"}, {2, "b"}};
- // absl::btree_multimap<int, std::string> map7(v.begin(), v.end());
- btree_multimap() {}
- using Base::Base;
-
- // btree_multimap::begin()
- //
- // Returns an iterator to the beginning of the `btree_multimap`.
- using Base::begin;
-
- // btree_multimap::cbegin()
- //
- // Returns a const iterator to the beginning of the `btree_multimap`.
- using Base::cbegin;
-
- // btree_multimap::end()
- //
- // Returns an iterator to the end of the `btree_multimap`.
- using Base::end;
-
- // btree_multimap::cend()
- //
- // Returns a const iterator to the end of the `btree_multimap`.
- using Base::cend;
-
- // btree_multimap::empty()
- //
- // Returns whether or not the `btree_multimap` is empty.
- using Base::empty;
-
- // btree_multimap::max_size()
- //
- // Returns the largest theoretical possible number of elements within a
- // `btree_multimap` under current memory constraints. This value can be
- // thought of as the largest value of `std::distance(begin(), end())` for a
- // `btree_multimap<Key, T>`.
- using Base::max_size;
-
- // btree_multimap::size()
- //
- // Returns the number of elements currently within the `btree_multimap`.
- using Base::size;
-
- // btree_multimap::clear()
- //
- // Removes all elements from the `btree_multimap`. Invalidates any references,
- // pointers, or iterators referring to contained elements.
- using Base::clear;
-
- // btree_multimap::erase()
- //
- // Erases elements within the `btree_multimap`. If an erase occurs, any
- // references, pointers, or iterators are invalidated.
- // Overloads are listed below.
- //
- // iterator erase(iterator position):
- // iterator erase(const_iterator position):
- //
- // Erases the element at `position` of the `btree_multimap`, returning
- // the iterator pointing to the element after the one that was erased
- // (or end() if none exists).
- //
- // iterator erase(const_iterator first, const_iterator last):
- //
- // Erases the elements in the open interval [`first`, `last`), returning
- // the iterator pointing to the element after the interval that was erased
- // (or end() if none exists).
- //
- // template <typename K> size_type erase(const K& key):
- //
- // Erases the elements matching the key, if any exist, returning the
- // number of elements erased.
- using Base::erase;
-
- // btree_multimap::insert()
- //
- // Inserts an element of the specified value into the `btree_multimap`,
- // returning an iterator pointing to the newly inserted element.
- // Any references, pointers, or iterators are invalidated. Overloads are
- // listed below.
- //
- // iterator insert(const value_type& value):
- //
- // Inserts a value into the `btree_multimap`, returning an iterator to the
- // inserted element.
- //
- // iterator insert(value_type&& value):
- //
- // Inserts a moveable value into the `btree_multimap`, returning an iterator
- // to the inserted element.
- //
- // iterator insert(const_iterator hint, const value_type& value):
- // iterator insert(const_iterator hint, value_type&& value):
- //
- // Inserts a value, using the position of `hint` as a non-binding suggestion
- // for where to begin the insertion search. Returns an iterator to the
- // inserted element.
- //
- // void insert(InputIterator first, InputIterator last):
- //
- // Inserts a range of values [`first`, `last`).
- //
- // void insert(std::initializer_list<init_type> ilist):
- //
- // Inserts the elements within the initializer list `ilist`.
- using Base::insert;
-
- // btree_multimap::emplace()
- //
- // Inserts an element of the specified value by constructing it in-place
- // within the `btree_multimap`. Any references, pointers, or iterators are
- // invalidated.
- using Base::emplace;
-
- // btree_multimap::emplace_hint()
- //
- // Inserts an element of the specified value by constructing it in-place
- // within the `btree_multimap`, using the position of `hint` as a non-binding
- // suggestion for where to begin the insertion search.
- //
- // Any references, pointers, or iterators are invalidated.
- using Base::emplace_hint;
-
- // btree_multimap::extract()
- //
- // Extracts the indicated element, erasing it in the process, and returns it
- // as a C++17-compatible node handle. Overloads are listed below.
- //
- // node_type extract(const_iterator position):
- //
- // Extracts the element at the indicated position and returns a node handle
- // owning that extracted data.
- //
- // template <typename K> node_type extract(const K& k):
- //
- // Extracts the element with the key matching the passed key value and
- // returns a node handle owning that extracted data. If the `btree_multimap`
- // does not contain an element with a matching key, this function returns an
- // empty node handle.
- //
- // NOTE: when compiled in an earlier version of C++ than C++17,
- // `node_type::key()` returns a const reference to the key instead of a
- // mutable reference. We cannot safely return a mutable reference without
- // std::launder (which is not available before C++17).
- //
- // NOTE: In this context, `node_type` refers to the C++17 concept of a
- // move-only type that owns and provides access to the elements in associative
- // containers (https://en.cppreference.com/w/cpp/container/node_handle).
- // It does NOT refer to the data layout of the underlying btree.
- using Base::extract;
-
- // btree_multimap::merge()
- //
- // Extracts all elements from a given `source` btree_multimap into this
- // `btree_multimap`.
- using Base::merge;
-
- // btree_multimap::swap(btree_multimap& other)
- //
- // Exchanges the contents of this `btree_multimap` with those of the `other`
- // btree_multimap, avoiding invocation of any move, copy, or swap operations
- // on individual elements.
- //
- // All iterators and references on the `btree_multimap` remain valid,
- // excepting for the past-the-end iterator, which is invalidated.
- using Base::swap;
-
- // btree_multimap::contains()
- //
- // template <typename K> bool contains(const K& key) const:
- //
- // Determines whether an element comparing equal to the given `key` exists
- // within the `btree_multimap`, returning `true` if so or `false` otherwise.
- //
- // Supports heterogeneous lookup, provided that the map has a compatible
- // heterogeneous comparator.
- using Base::contains;
-
- // btree_multimap::count()
- //
- // template <typename K> size_type count(const K& key) const:
- //
- // Returns the number of elements comparing equal to the given `key` within
- // the `btree_multimap`.
- //
- // Supports heterogeneous lookup, provided that the map has a compatible
- // heterogeneous comparator.
- using Base::count;
-
- // btree_multimap::equal_range()
- //
- // Returns a half-open range [first, last), defined by a `std::pair` of two
- // iterators, containing all elements with the passed key in the
- // `btree_multimap`.
- using Base::equal_range;
-
- // btree_multimap::find()
- //
- // template <typename K> iterator find(const K& key):
- // template <typename K> const_iterator find(const K& key) const:
- //
- // Finds an element with the passed `key` within the `btree_multimap`.
- //
- // Supports heterogeneous lookup, provided that the map has a compatible
- // heterogeneous comparator.
- using Base::find;
-
- // btree_multimap::lower_bound()
- //
- // template <typename K> iterator lower_bound(const K& key):
- // template <typename K> const_iterator lower_bound(const K& key) const:
- //
- // Finds the first element with a key that is not less than `key` within the
- // `btree_multimap`.
- //
- // Supports heterogeneous lookup, provided that the map has a compatible
- // heterogeneous comparator.
- using Base::lower_bound;
-
- // btree_multimap::upper_bound()
- //
- // template <typename K> iterator upper_bound(const K& key):
- // template <typename K> const_iterator upper_bound(const K& key) const:
- //
- // Finds the first element with a key that is greater than `key` within the
- // `btree_multimap`.
- //
- // Supports heterogeneous lookup, provided that the map has a compatible
- // heterogeneous comparator.
- using Base::upper_bound;
-
- // btree_multimap::get_allocator()
- //
- // Returns the allocator function associated with this `btree_multimap`.
- using Base::get_allocator;
-
- // btree_multimap::key_comp();
- //
- // Returns the key comparator associated with this `btree_multimap`.
- using Base::key_comp;
-
- // btree_multimap::value_comp();
- //
- // Returns the value comparator associated with this `btree_multimap`.
- using Base::value_comp;
-};
-
-// absl::swap(absl::btree_multimap<>, absl::btree_multimap<>)
-//
-// Swaps the contents of two `absl::btree_multimap` containers.
-template <typename K, typename V, typename C, typename A>
-void swap(btree_multimap<K, V, C, A> &x, btree_multimap<K, V, C, A> &y) {
- return x.swap(y);
-}
-
-// absl::erase_if(absl::btree_multimap<>, Pred)
-//
-// Erases all elements that satisfy the predicate pred from the container.
-// Returns the number of erased elements.
-template <typename K, typename V, typename C, typename A, typename Pred>
-typename btree_multimap<K, V, C, A>::size_type erase_if(
- btree_multimap<K, V, C, A> &map, Pred pred) {
- return container_internal::btree_access::erase_if(map, std::move(pred));
-}
-
-namespace container_internal {
-
-// A parameters structure for holding the type parameters for a btree_map.
-// Compare and Alloc should be nothrow copy-constructible.
-template <typename Key, typename Data, typename Compare, typename Alloc,
- int TargetNodeSize, bool IsMulti>
-struct map_params : common_params<Key, Compare, Alloc, TargetNodeSize, IsMulti,
- /*IsMap=*/true, map_slot_policy<Key, Data>> {
- using super_type = typename map_params::common_params;
- using mapped_type = Data;
- // This type allows us to move keys when it is safe to do so. It is safe
- // for maps in which value_type and mutable_value_type are layout compatible.
- using slot_policy = typename super_type::slot_policy;
- using slot_type = typename super_type::slot_type;
- using value_type = typename super_type::value_type;
- using init_type = typename super_type::init_type;
-
- template <typename V>
- static auto key(const V &value) -> decltype(value.first) {
- return value.first;
- }
- static const Key &key(const slot_type *s) { return slot_policy::key(s); }
- static const Key &key(slot_type *s) { return slot_policy::key(s); }
- // For use in node handle.
- static auto mutable_key(slot_type *s)
- -> decltype(slot_policy::mutable_key(s)) {
- return slot_policy::mutable_key(s);
- }
- static mapped_type &value(value_type *value) { return value->second; }
-};
-
-} // namespace container_internal
-
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_BTREE_MAP_H_
diff --git a/third_party/abseil-cpp/absl/container/btree_set.h b/third_party/abseil-cpp/absl/container/btree_set.h
deleted file mode 100644
index d93bdbf..0000000
--- a/third_party/abseil-cpp/absl/container/btree_set.h
+++ /dev/null
@@ -1,791 +0,0 @@
-// Copyright 2018 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.
-//
-// -----------------------------------------------------------------------------
-// File: btree_set.h
-// -----------------------------------------------------------------------------
-//
-// This header file defines B-tree sets: sorted associative containers of
-// values.
-//
-// * `absl::btree_set<>`
-// * `absl::btree_multiset<>`
-//
-// These B-tree types are similar to the corresponding types in the STL
-// (`std::set` and `std::multiset`) and generally conform to the STL interfaces
-// of those types. However, because they are implemented using B-trees, they
-// are more efficient in most situations.
-//
-// Unlike `std::set` and `std::multiset`, which are commonly implemented using
-// red-black tree nodes, B-tree sets use more generic B-tree nodes able to hold
-// multiple values per node. Holding multiple values per node often makes
-// B-tree sets perform better than their `std::set` counterparts, because
-// multiple entries can be checked within the same cache hit.
-//
-// However, these types should not be considered drop-in replacements for
-// `std::set` and `std::multiset` as there are some API differences, which are
-// noted in this header file. The most consequential differences with respect to
-// migrating to b-tree from the STL types are listed in the next paragraph.
-// Other API differences are minor.
-//
-// Importantly, insertions and deletions may invalidate outstanding iterators,
-// pointers, and references to elements. Such invalidations are typically only
-// an issue if insertion and deletion operations are interleaved with the use of
-// more than one iterator, pointer, or reference simultaneously. For this
-// reason, `insert()` and `erase()` return a valid iterator at the current
-// position (and `extract()` cannot be used in this way).
-//
-// Another API difference is that btree iterators can be subtracted, and this
-// is faster than using std::distance.
-
-#ifndef ABSL_CONTAINER_BTREE_SET_H_
-#define ABSL_CONTAINER_BTREE_SET_H_
-
-#include "absl/container/internal/btree.h" // IWYU pragma: export
-#include "absl/container/internal/btree_container.h" // IWYU pragma: export
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-
-namespace container_internal {
-
-template <typename Key>
-struct set_slot_policy;
-
-template <typename Key, typename Compare, typename Alloc, int TargetNodeSize,
- bool IsMulti>
-struct set_params;
-
-} // namespace container_internal
-
-// absl::btree_set<>
-//
-// An `absl::btree_set<K>` is an ordered associative container of unique key
-// values designed to be a more efficient replacement for `std::set` (in most
-// cases).
-//
-// Keys are sorted using an (optional) comparison function, which defaults to
-// `std::less<K>`.
-//
-// An `absl::btree_set<K>` uses a default allocator of `std::allocator<K>` to
-// allocate (and deallocate) nodes, and construct and destruct values within
-// those nodes. You may instead specify a custom allocator `A` (which in turn
-// requires specifying a custom comparator `C`) as in
-// `absl::btree_set<K, C, A>`.
-//
-template <typename Key, typename Compare = std::less<Key>,
- typename Alloc = std::allocator<Key>>
-class btree_set
- : public container_internal::btree_set_container<
- container_internal::btree<container_internal::set_params<
- Key, Compare, Alloc, /*TargetNodeSize=*/256,
- /*IsMulti=*/false>>> {
- using Base = typename btree_set::btree_set_container;
-
- public:
- // Constructors and Assignment Operators
- //
- // A `btree_set` supports the same overload set as `std::set`
- // for construction and assignment:
- //
- // * Default constructor
- //
- // absl::btree_set<std::string> set1;
- //
- // * Initializer List constructor
- //
- // absl::btree_set<std::string> set2 =
- // {{"huey"}, {"dewey"}, {"louie"},};
- //
- // * Copy constructor
- //
- // absl::btree_set<std::string> set3(set2);
- //
- // * Copy assignment operator
- //
- // absl::btree_set<std::string> set4;
- // set4 = set3;
- //
- // * Move constructor
- //
- // // Move is guaranteed efficient
- // absl::btree_set<std::string> set5(std::move(set4));
- //
- // * Move assignment operator
- //
- // // May be efficient if allocators are compatible
- // absl::btree_set<std::string> set6;
- // set6 = std::move(set5);
- //
- // * Range constructor
- //
- // std::vector<std::string> v = {"a", "b"};
- // absl::btree_set<std::string> set7(v.begin(), v.end());
- btree_set() {}
- using Base::Base;
-
- // btree_set::begin()
- //
- // Returns an iterator to the beginning of the `btree_set`.
- using Base::begin;
-
- // btree_set::cbegin()
- //
- // Returns a const iterator to the beginning of the `btree_set`.
- using Base::cbegin;
-
- // btree_set::end()
- //
- // Returns an iterator to the end of the `btree_set`.
- using Base::end;
-
- // btree_set::cend()
- //
- // Returns a const iterator to the end of the `btree_set`.
- using Base::cend;
-
- // btree_set::empty()
- //
- // Returns whether or not the `btree_set` is empty.
- using Base::empty;
-
- // btree_set::max_size()
- //
- // Returns the largest theoretical possible number of elements within a
- // `btree_set` under current memory constraints. This value can be thought
- // of as the largest value of `std::distance(begin(), end())` for a
- // `btree_set<Key>`.
- using Base::max_size;
-
- // btree_set::size()
- //
- // Returns the number of elements currently within the `btree_set`.
- using Base::size;
-
- // btree_set::clear()
- //
- // Removes all elements from the `btree_set`. Invalidates any references,
- // pointers, or iterators referring to contained elements.
- using Base::clear;
-
- // btree_set::erase()
- //
- // Erases elements within the `btree_set`. Overloads are listed below.
- //
- // iterator erase(iterator position):
- // iterator erase(const_iterator position):
- //
- // Erases the element at `position` of the `btree_set`, returning
- // the iterator pointing to the element after the one that was erased
- // (or end() if none exists).
- //
- // iterator erase(const_iterator first, const_iterator last):
- //
- // Erases the elements in the open interval [`first`, `last`), returning
- // the iterator pointing to the element after the interval that was erased
- // (or end() if none exists).
- //
- // template <typename K> size_type erase(const K& key):
- //
- // Erases the element with the matching key, if it exists, returning the
- // number of elements erased (0 or 1).
- using Base::erase;
-
- // btree_set::insert()
- //
- // Inserts an element of the specified value into the `btree_set`,
- // returning an iterator pointing to the newly inserted element, provided that
- // an element with the given key does not already exist. If an insertion
- // occurs, any references, pointers, or iterators are invalidated.
- // Overloads are listed below.
- //
- // std::pair<iterator,bool> insert(const value_type& value):
- //
- // Inserts a value into the `btree_set`. Returns a pair consisting of an
- // iterator to the inserted element (or to the element that prevented the
- // insertion) and a bool denoting whether the insertion took place.
- //
- // std::pair<iterator,bool> insert(value_type&& value):
- //
- // Inserts a moveable value into the `btree_set`. Returns a pair
- // consisting of an iterator to the inserted element (or to the element that
- // prevented the insertion) and a bool denoting whether the insertion took
- // place.
- //
- // iterator insert(const_iterator hint, const value_type& value):
- // iterator insert(const_iterator hint, value_type&& value):
- //
- // Inserts a value, using the position of `hint` as a non-binding suggestion
- // for where to begin the insertion search. Returns an iterator to the
- // inserted element, or to the existing element that prevented the
- // insertion.
- //
- // void insert(InputIterator first, InputIterator last):
- //
- // Inserts a range of values [`first`, `last`).
- //
- // void insert(std::initializer_list<init_type> ilist):
- //
- // Inserts the elements within the initializer list `ilist`.
- using Base::insert;
-
- // btree_set::emplace()
- //
- // Inserts an element of the specified value by constructing it in-place
- // within the `btree_set`, provided that no element with the given key
- // already exists.
- //
- // The element may be constructed even if there already is an element with the
- // key in the container, in which case the newly constructed element will be
- // destroyed immediately.
- //
- // If an insertion occurs, any references, pointers, or iterators are
- // invalidated.
- using Base::emplace;
-
- // btree_set::emplace_hint()
- //
- // Inserts an element of the specified value by constructing it in-place
- // within the `btree_set`, using the position of `hint` as a non-binding
- // suggestion for where to begin the insertion search, and only inserts
- // provided that no element with the given key already exists.
- //
- // The element may be constructed even if there already is an element with the
- // key in the container, in which case the newly constructed element will be
- // destroyed immediately.
- //
- // If an insertion occurs, any references, pointers, or iterators are
- // invalidated.
- using Base::emplace_hint;
-
- // btree_set::extract()
- //
- // Extracts the indicated element, erasing it in the process, and returns it
- // as a C++17-compatible node handle. Any references, pointers, or iterators
- // are invalidated. Overloads are listed below.
- //
- // node_type extract(const_iterator position):
- //
- // Extracts the element at the indicated position and returns a node handle
- // owning that extracted data.
- //
- // template <typename K> node_type extract(const K& k):
- //
- // Extracts the element with the key matching the passed key value and
- // returns a node handle owning that extracted data. If the `btree_set`
- // does not contain an element with a matching key, this function returns an
- // empty node handle.
- //
- // NOTE: In this context, `node_type` refers to the C++17 concept of a
- // move-only type that owns and provides access to the elements in associative
- // containers (https://en.cppreference.com/w/cpp/container/node_handle).
- // It does NOT refer to the data layout of the underlying btree.
- using Base::extract;
-
- // btree_set::merge()
- //
- // Extracts elements from a given `source` btree_set into this
- // `btree_set`. If the destination `btree_set` already contains an
- // element with an equivalent key, that element is not extracted.
- using Base::merge;
-
- // btree_set::swap(btree_set& other)
- //
- // Exchanges the contents of this `btree_set` with those of the `other`
- // btree_set, avoiding invocation of any move, copy, or swap operations on
- // individual elements.
- //
- // All iterators and references on the `btree_set` remain valid, excepting
- // for the past-the-end iterator, which is invalidated.
- using Base::swap;
-
- // btree_set::contains()
- //
- // template <typename K> bool contains(const K& key) const:
- //
- // Determines whether an element comparing equal to the given `key` exists
- // within the `btree_set`, returning `true` if so or `false` otherwise.
- //
- // Supports heterogeneous lookup, provided that the set has a compatible
- // heterogeneous comparator.
- using Base::contains;
-
- // btree_set::count()
- //
- // template <typename K> size_type count(const K& key) const:
- //
- // Returns the number of elements comparing equal to the given `key` within
- // the `btree_set`. Note that this function will return either `1` or `0`
- // since duplicate elements are not allowed within a `btree_set`.
- //
- // Supports heterogeneous lookup, provided that the set has a compatible
- // heterogeneous comparator.
- using Base::count;
-
- // btree_set::equal_range()
- //
- // Returns a closed range [first, last], defined by a `std::pair` of two
- // iterators, containing all elements with the passed key in the
- // `btree_set`.
- using Base::equal_range;
-
- // btree_set::find()
- //
- // template <typename K> iterator find(const K& key):
- // template <typename K> const_iterator find(const K& key) const:
- //
- // Finds an element with the passed `key` within the `btree_set`.
- //
- // Supports heterogeneous lookup, provided that the set has a compatible
- // heterogeneous comparator.
- using Base::find;
-
- // btree_set::lower_bound()
- //
- // template <typename K> iterator lower_bound(const K& key):
- // template <typename K> const_iterator lower_bound(const K& key) const:
- //
- // Finds the first element that is not less than `key` within the `btree_set`.
- //
- // Supports heterogeneous lookup, provided that the set has a compatible
- // heterogeneous comparator.
- using Base::lower_bound;
-
- // btree_set::upper_bound()
- //
- // template <typename K> iterator upper_bound(const K& key):
- // template <typename K> const_iterator upper_bound(const K& key) const:
- //
- // Finds the first element that is greater than `key` within the `btree_set`.
- //
- // Supports heterogeneous lookup, provided that the set has a compatible
- // heterogeneous comparator.
- using Base::upper_bound;
-
- // btree_set::get_allocator()
- //
- // Returns the allocator function associated with this `btree_set`.
- using Base::get_allocator;
-
- // btree_set::key_comp();
- //
- // Returns the key comparator associated with this `btree_set`.
- using Base::key_comp;
-
- // btree_set::value_comp();
- //
- // Returns the value comparator associated with this `btree_set`. The keys to
- // sort the elements are the values themselves, therefore `value_comp` and its
- // sibling member function `key_comp` are equivalent.
- using Base::value_comp;
-};
-
-// absl::swap(absl::btree_set<>, absl::btree_set<>)
-//
-// Swaps the contents of two `absl::btree_set` containers.
-template <typename K, typename C, typename A>
-void swap(btree_set<K, C, A> &x, btree_set<K, C, A> &y) {
- return x.swap(y);
-}
-
-// absl::erase_if(absl::btree_set<>, Pred)
-//
-// Erases all elements that satisfy the predicate pred from the container.
-// Returns the number of erased elements.
-template <typename K, typename C, typename A, typename Pred>
-typename btree_set<K, C, A>::size_type erase_if(btree_set<K, C, A> &set,
- Pred pred) {
- return container_internal::btree_access::erase_if(set, std::move(pred));
-}
-
-// absl::btree_multiset<>
-//
-// An `absl::btree_multiset<K>` is an ordered associative container of
-// keys and associated values designed to be a more efficient replacement
-// for `std::multiset` (in most cases). Unlike `absl::btree_set`, a B-tree
-// multiset allows equivalent elements.
-//
-// Keys are sorted using an (optional) comparison function, which defaults to
-// `std::less<K>`.
-//
-// An `absl::btree_multiset<K>` uses a default allocator of `std::allocator<K>`
-// to allocate (and deallocate) nodes, and construct and destruct values within
-// those nodes. You may instead specify a custom allocator `A` (which in turn
-// requires specifying a custom comparator `C`) as in
-// `absl::btree_multiset<K, C, A>`.
-//
-template <typename Key, typename Compare = std::less<Key>,
- typename Alloc = std::allocator<Key>>
-class btree_multiset
- : public container_internal::btree_multiset_container<
- container_internal::btree<container_internal::set_params<
- Key, Compare, Alloc, /*TargetNodeSize=*/256,
- /*IsMulti=*/true>>> {
- using Base = typename btree_multiset::btree_multiset_container;
-
- public:
- // Constructors and Assignment Operators
- //
- // A `btree_multiset` supports the same overload set as `std::set`
- // for construction and assignment:
- //
- // * Default constructor
- //
- // absl::btree_multiset<std::string> set1;
- //
- // * Initializer List constructor
- //
- // absl::btree_multiset<std::string> set2 =
- // {{"huey"}, {"dewey"}, {"louie"},};
- //
- // * Copy constructor
- //
- // absl::btree_multiset<std::string> set3(set2);
- //
- // * Copy assignment operator
- //
- // absl::btree_multiset<std::string> set4;
- // set4 = set3;
- //
- // * Move constructor
- //
- // // Move is guaranteed efficient
- // absl::btree_multiset<std::string> set5(std::move(set4));
- //
- // * Move assignment operator
- //
- // // May be efficient if allocators are compatible
- // absl::btree_multiset<std::string> set6;
- // set6 = std::move(set5);
- //
- // * Range constructor
- //
- // std::vector<std::string> v = {"a", "b"};
- // absl::btree_multiset<std::string> set7(v.begin(), v.end());
- btree_multiset() {}
- using Base::Base;
-
- // btree_multiset::begin()
- //
- // Returns an iterator to the beginning of the `btree_multiset`.
- using Base::begin;
-
- // btree_multiset::cbegin()
- //
- // Returns a const iterator to the beginning of the `btree_multiset`.
- using Base::cbegin;
-
- // btree_multiset::end()
- //
- // Returns an iterator to the end of the `btree_multiset`.
- using Base::end;
-
- // btree_multiset::cend()
- //
- // Returns a const iterator to the end of the `btree_multiset`.
- using Base::cend;
-
- // btree_multiset::empty()
- //
- // Returns whether or not the `btree_multiset` is empty.
- using Base::empty;
-
- // btree_multiset::max_size()
- //
- // Returns the largest theoretical possible number of elements within a
- // `btree_multiset` under current memory constraints. This value can be
- // thought of as the largest value of `std::distance(begin(), end())` for a
- // `btree_multiset<Key>`.
- using Base::max_size;
-
- // btree_multiset::size()
- //
- // Returns the number of elements currently within the `btree_multiset`.
- using Base::size;
-
- // btree_multiset::clear()
- //
- // Removes all elements from the `btree_multiset`. Invalidates any references,
- // pointers, or iterators referring to contained elements.
- using Base::clear;
-
- // btree_multiset::erase()
- //
- // Erases elements within the `btree_multiset`. Overloads are listed below.
- //
- // iterator erase(iterator position):
- // iterator erase(const_iterator position):
- //
- // Erases the element at `position` of the `btree_multiset`, returning
- // the iterator pointing to the element after the one that was erased
- // (or end() if none exists).
- //
- // iterator erase(const_iterator first, const_iterator last):
- //
- // Erases the elements in the open interval [`first`, `last`), returning
- // the iterator pointing to the element after the interval that was erased
- // (or end() if none exists).
- //
- // template <typename K> size_type erase(const K& key):
- //
- // Erases the elements matching the key, if any exist, returning the
- // number of elements erased.
- using Base::erase;
-
- // btree_multiset::insert()
- //
- // Inserts an element of the specified value into the `btree_multiset`,
- // returning an iterator pointing to the newly inserted element.
- // Any references, pointers, or iterators are invalidated. Overloads are
- // listed below.
- //
- // iterator insert(const value_type& value):
- //
- // Inserts a value into the `btree_multiset`, returning an iterator to the
- // inserted element.
- //
- // iterator insert(value_type&& value):
- //
- // Inserts a moveable value into the `btree_multiset`, returning an iterator
- // to the inserted element.
- //
- // iterator insert(const_iterator hint, const value_type& value):
- // iterator insert(const_iterator hint, value_type&& value):
- //
- // Inserts a value, using the position of `hint` as a non-binding suggestion
- // for where to begin the insertion search. Returns an iterator to the
- // inserted element.
- //
- // void insert(InputIterator first, InputIterator last):
- //
- // Inserts a range of values [`first`, `last`).
- //
- // void insert(std::initializer_list<init_type> ilist):
- //
- // Inserts the elements within the initializer list `ilist`.
- using Base::insert;
-
- // btree_multiset::emplace()
- //
- // Inserts an element of the specified value by constructing it in-place
- // within the `btree_multiset`. Any references, pointers, or iterators are
- // invalidated.
- using Base::emplace;
-
- // btree_multiset::emplace_hint()
- //
- // Inserts an element of the specified value by constructing it in-place
- // within the `btree_multiset`, using the position of `hint` as a non-binding
- // suggestion for where to begin the insertion search.
- //
- // Any references, pointers, or iterators are invalidated.
- using Base::emplace_hint;
-
- // btree_multiset::extract()
- //
- // Extracts the indicated element, erasing it in the process, and returns it
- // as a C++17-compatible node handle. Overloads are listed below.
- //
- // node_type extract(const_iterator position):
- //
- // Extracts the element at the indicated position and returns a node handle
- // owning that extracted data.
- //
- // template <typename K> node_type extract(const K& k):
- //
- // Extracts the element with the key matching the passed key value and
- // returns a node handle owning that extracted data. If the `btree_multiset`
- // does not contain an element with a matching key, this function returns an
- // empty node handle.
- //
- // NOTE: In this context, `node_type` refers to the C++17 concept of a
- // move-only type that owns and provides access to the elements in associative
- // containers (https://en.cppreference.com/w/cpp/container/node_handle).
- // It does NOT refer to the data layout of the underlying btree.
- using Base::extract;
-
- // btree_multiset::merge()
- //
- // Extracts all elements from a given `source` btree_multiset into this
- // `btree_multiset`.
- using Base::merge;
-
- // btree_multiset::swap(btree_multiset& other)
- //
- // Exchanges the contents of this `btree_multiset` with those of the `other`
- // btree_multiset, avoiding invocation of any move, copy, or swap operations
- // on individual elements.
- //
- // All iterators and references on the `btree_multiset` remain valid,
- // excepting for the past-the-end iterator, which is invalidated.
- using Base::swap;
-
- // btree_multiset::contains()
- //
- // template <typename K> bool contains(const K& key) const:
- //
- // Determines whether an element comparing equal to the given `key` exists
- // within the `btree_multiset`, returning `true` if so or `false` otherwise.
- //
- // Supports heterogeneous lookup, provided that the set has a compatible
- // heterogeneous comparator.
- using Base::contains;
-
- // btree_multiset::count()
- //
- // template <typename K> size_type count(const K& key) const:
- //
- // Returns the number of elements comparing equal to the given `key` within
- // the `btree_multiset`.
- //
- // Supports heterogeneous lookup, provided that the set has a compatible
- // heterogeneous comparator.
- using Base::count;
-
- // btree_multiset::equal_range()
- //
- // Returns a closed range [first, last], defined by a `std::pair` of two
- // iterators, containing all elements with the passed key in the
- // `btree_multiset`.
- using Base::equal_range;
-
- // btree_multiset::find()
- //
- // template <typename K> iterator find(const K& key):
- // template <typename K> const_iterator find(const K& key) const:
- //
- // Finds an element with the passed `key` within the `btree_multiset`.
- //
- // Supports heterogeneous lookup, provided that the set has a compatible
- // heterogeneous comparator.
- using Base::find;
-
- // btree_multiset::lower_bound()
- //
- // template <typename K> iterator lower_bound(const K& key):
- // template <typename K> const_iterator lower_bound(const K& key) const:
- //
- // Finds the first element that is not less than `key` within the
- // `btree_multiset`.
- //
- // Supports heterogeneous lookup, provided that the set has a compatible
- // heterogeneous comparator.
- using Base::lower_bound;
-
- // btree_multiset::upper_bound()
- //
- // template <typename K> iterator upper_bound(const K& key):
- // template <typename K> const_iterator upper_bound(const K& key) const:
- //
- // Finds the first element that is greater than `key` within the
- // `btree_multiset`.
- //
- // Supports heterogeneous lookup, provided that the set has a compatible
- // heterogeneous comparator.
- using Base::upper_bound;
-
- // btree_multiset::get_allocator()
- //
- // Returns the allocator function associated with this `btree_multiset`.
- using Base::get_allocator;
-
- // btree_multiset::key_comp();
- //
- // Returns the key comparator associated with this `btree_multiset`.
- using Base::key_comp;
-
- // btree_multiset::value_comp();
- //
- // Returns the value comparator associated with this `btree_multiset`. The
- // keys to sort the elements are the values themselves, therefore `value_comp`
- // and its sibling member function `key_comp` are equivalent.
- using Base::value_comp;
-};
-
-// absl::swap(absl::btree_multiset<>, absl::btree_multiset<>)
-//
-// Swaps the contents of two `absl::btree_multiset` containers.
-template <typename K, typename C, typename A>
-void swap(btree_multiset<K, C, A> &x, btree_multiset<K, C, A> &y) {
- return x.swap(y);
-}
-
-// absl::erase_if(absl::btree_multiset<>, Pred)
-//
-// Erases all elements that satisfy the predicate pred from the container.
-// Returns the number of erased elements.
-template <typename K, typename C, typename A, typename Pred>
-typename btree_multiset<K, C, A>::size_type erase_if(
- btree_multiset<K, C, A> & set, Pred pred) {
- return container_internal::btree_access::erase_if(set, std::move(pred));
-}
-
-namespace container_internal {
-
-// This type implements the necessary functions from the
-// absl::container_internal::slot_type interface for btree_(multi)set.
-template <typename Key>
-struct set_slot_policy {
- using slot_type = Key;
- using value_type = Key;
- using mutable_value_type = Key;
-
- static value_type &element(slot_type *slot) { return *slot; }
- static const value_type &element(const slot_type *slot) { return *slot; }
-
- template <typename Alloc, class... Args>
- static void construct(Alloc *alloc, slot_type *slot, Args &&...args) {
- absl::allocator_traits<Alloc>::construct(*alloc, slot,
- std::forward<Args>(args)...);
- }
-
- template <typename Alloc>
- static void construct(Alloc *alloc, slot_type *slot, slot_type *other) {
- absl::allocator_traits<Alloc>::construct(*alloc, slot, std::move(*other));
- }
-
- template <typename Alloc>
- static void construct(Alloc *alloc, slot_type *slot, const slot_type *other) {
- absl::allocator_traits<Alloc>::construct(*alloc, slot, *other);
- }
-
- template <typename Alloc>
- static void destroy(Alloc *alloc, slot_type *slot) {
- absl::allocator_traits<Alloc>::destroy(*alloc, slot);
- }
-};
-
-// A parameters structure for holding the type parameters for a btree_set.
-// Compare and Alloc should be nothrow copy-constructible.
-template <typename Key, typename Compare, typename Alloc, int TargetNodeSize,
- bool IsMulti>
-struct set_params : common_params<Key, Compare, Alloc, TargetNodeSize, IsMulti,
- /*IsMap=*/false, set_slot_policy<Key>> {
- using value_type = Key;
- using slot_type = typename set_params::common_params::slot_type;
-
- template <typename V>
- static const V &key(const V &value) {
- return value;
- }
- static const Key &key(const slot_type *slot) { return *slot; }
- static const Key &key(slot_type *slot) { return *slot; }
-};
-
-} // namespace container_internal
-
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_BTREE_SET_H_
diff --git a/third_party/abseil-cpp/absl/container/btree_test.cc b/third_party/abseil-cpp/absl/container/btree_test.cc
deleted file mode 100644
index e6d4e36..0000000
--- a/third_party/abseil-cpp/absl/container/btree_test.cc
+++ /dev/null
@@ -1,3354 +0,0 @@
-// Copyright 2018 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/container/btree_test.h"
-
-#include <algorithm>
-#include <array>
-#include <cstdint>
-#include <functional>
-#include <iterator>
-#include <limits>
-#include <map>
-#include <memory>
-#include <numeric>
-#include <stdexcept>
-#include <string>
-#include <type_traits>
-#include <utility>
-#include <vector>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/algorithm/container.h"
-#include "absl/base/internal/raw_logging.h"
-#include "absl/base/macros.h"
-#include "absl/container/btree_map.h"
-#include "absl/container/btree_set.h"
-#include "absl/container/internal/counting_allocator.h"
-#include "absl/container/internal/test_instance_tracker.h"
-#include "absl/flags/flag.h"
-#include "absl/hash/hash_testing.h"
-#include "absl/memory/memory.h"
-#include "absl/random/random.h"
-#include "absl/strings/str_cat.h"
-#include "absl/strings/str_split.h"
-#include "absl/strings/string_view.h"
-#include "absl/types/compare.h"
-
-ABSL_FLAG(int, test_values, 10000, "The number of values to use for tests");
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-namespace {
-
-using ::absl::test_internal::CopyableMovableInstance;
-using ::absl::test_internal::InstanceTracker;
-using ::absl::test_internal::MovableOnlyInstance;
-using ::testing::ElementsAre;
-using ::testing::ElementsAreArray;
-using ::testing::IsEmpty;
-using ::testing::IsNull;
-using ::testing::Pair;
-using ::testing::SizeIs;
-
-template <typename T, typename U>
-void CheckPairEquals(const T &x, const U &y) {
- ABSL_INTERNAL_CHECK(x == y, "Values are unequal.");
-}
-
-template <typename T, typename U, typename V, typename W>
-void CheckPairEquals(const std::pair<T, U> &x, const std::pair<V, W> &y) {
- CheckPairEquals(x.first, y.first);
- CheckPairEquals(x.second, y.second);
-}
-} // namespace
-
-// The base class for a sorted associative container checker. TreeType is the
-// container type to check and CheckerType is the container type to check
-// against. TreeType is expected to be btree_{set,map,multiset,multimap} and
-// CheckerType is expected to be {set,map,multiset,multimap}.
-template <typename TreeType, typename CheckerType>
-class base_checker {
- public:
- using key_type = typename TreeType::key_type;
- using value_type = typename TreeType::value_type;
- using key_compare = typename TreeType::key_compare;
- using pointer = typename TreeType::pointer;
- using const_pointer = typename TreeType::const_pointer;
- using reference = typename TreeType::reference;
- using const_reference = typename TreeType::const_reference;
- using size_type = typename TreeType::size_type;
- using difference_type = typename TreeType::difference_type;
- using iterator = typename TreeType::iterator;
- using const_iterator = typename TreeType::const_iterator;
- using reverse_iterator = typename TreeType::reverse_iterator;
- using const_reverse_iterator = typename TreeType::const_reverse_iterator;
-
- public:
- base_checker() : const_tree_(tree_) {}
- base_checker(const base_checker &other)
- : tree_(other.tree_), const_tree_(tree_), checker_(other.checker_) {}
- template <typename InputIterator>
- base_checker(InputIterator b, InputIterator e)
- : tree_(b, e), const_tree_(tree_), checker_(b, e) {}
-
- iterator begin() { return tree_.begin(); }
- const_iterator begin() const { return tree_.begin(); }
- iterator end() { return tree_.end(); }
- const_iterator end() const { return tree_.end(); }
- reverse_iterator rbegin() { return tree_.rbegin(); }
- const_reverse_iterator rbegin() const { return tree_.rbegin(); }
- reverse_iterator rend() { return tree_.rend(); }
- const_reverse_iterator rend() const { return tree_.rend(); }
-
- template <typename IterType, typename CheckerIterType>
- IterType iter_check(IterType tree_iter, CheckerIterType checker_iter) const {
- if (tree_iter == tree_.end()) {
- ABSL_INTERNAL_CHECK(checker_iter == checker_.end(),
- "Checker iterator not at end.");
- } else {
- CheckPairEquals(*tree_iter, *checker_iter);
- }
- return tree_iter;
- }
- template <typename IterType, typename CheckerIterType>
- IterType riter_check(IterType tree_iter, CheckerIterType checker_iter) const {
- if (tree_iter == tree_.rend()) {
- ABSL_INTERNAL_CHECK(checker_iter == checker_.rend(),
- "Checker iterator not at rend.");
- } else {
- CheckPairEquals(*tree_iter, *checker_iter);
- }
- return tree_iter;
- }
- void value_check(const value_type &v) {
- typename KeyOfValue<typename TreeType::key_type,
- typename TreeType::value_type>::type key_of_value;
- const key_type &key = key_of_value(v);
- CheckPairEquals(*find(key), v);
- lower_bound(key);
- upper_bound(key);
- equal_range(key);
- contains(key);
- count(key);
- }
- void erase_check(const key_type &key) {
- EXPECT_FALSE(tree_.contains(key));
- EXPECT_EQ(tree_.find(key), const_tree_.end());
- EXPECT_FALSE(const_tree_.contains(key));
- EXPECT_EQ(const_tree_.find(key), tree_.end());
- EXPECT_EQ(tree_.equal_range(key).first,
- const_tree_.equal_range(key).second);
- }
-
- iterator lower_bound(const key_type &key) {
- return iter_check(tree_.lower_bound(key), checker_.lower_bound(key));
- }
- const_iterator lower_bound(const key_type &key) const {
- return iter_check(tree_.lower_bound(key), checker_.lower_bound(key));
- }
- iterator upper_bound(const key_type &key) {
- return iter_check(tree_.upper_bound(key), checker_.upper_bound(key));
- }
- const_iterator upper_bound(const key_type &key) const {
- return iter_check(tree_.upper_bound(key), checker_.upper_bound(key));
- }
- std::pair<iterator, iterator> equal_range(const key_type &key) {
- std::pair<typename CheckerType::iterator, typename CheckerType::iterator>
- checker_res = checker_.equal_range(key);
- std::pair<iterator, iterator> tree_res = tree_.equal_range(key);
- iter_check(tree_res.first, checker_res.first);
- iter_check(tree_res.second, checker_res.second);
- return tree_res;
- }
- std::pair<const_iterator, const_iterator> equal_range(
- const key_type &key) const {
- std::pair<typename CheckerType::const_iterator,
- typename CheckerType::const_iterator>
- checker_res = checker_.equal_range(key);
- std::pair<const_iterator, const_iterator> tree_res = tree_.equal_range(key);
- iter_check(tree_res.first, checker_res.first);
- iter_check(tree_res.second, checker_res.second);
- return tree_res;
- }
- iterator find(const key_type &key) {
- return iter_check(tree_.find(key), checker_.find(key));
- }
- const_iterator find(const key_type &key) const {
- return iter_check(tree_.find(key), checker_.find(key));
- }
- bool contains(const key_type &key) const { return find(key) != end(); }
- size_type count(const key_type &key) const {
- size_type res = checker_.count(key);
- EXPECT_EQ(res, tree_.count(key));
- return res;
- }
-
- base_checker &operator=(const base_checker &other) {
- tree_ = other.tree_;
- checker_ = other.checker_;
- return *this;
- }
-
- int erase(const key_type &key) {
- int size = tree_.size();
- int res = checker_.erase(key);
- EXPECT_EQ(res, tree_.count(key));
- EXPECT_EQ(res, tree_.erase(key));
- EXPECT_EQ(tree_.count(key), 0);
- EXPECT_EQ(tree_.size(), size - res);
- erase_check(key);
- return res;
- }
- iterator erase(iterator iter) {
- key_type key = iter.key();
- int size = tree_.size();
- int count = tree_.count(key);
- auto checker_iter = checker_.lower_bound(key);
- for (iterator tmp(tree_.lower_bound(key)); tmp != iter; ++tmp) {
- ++checker_iter;
- }
- auto checker_next = checker_iter;
- ++checker_next;
- checker_.erase(checker_iter);
- iter = tree_.erase(iter);
- EXPECT_EQ(tree_.size(), checker_.size());
- EXPECT_EQ(tree_.size(), size - 1);
- EXPECT_EQ(tree_.count(key), count - 1);
- if (count == 1) {
- erase_check(key);
- }
- return iter_check(iter, checker_next);
- }
-
- void erase(iterator begin, iterator end) {
- int size = tree_.size();
- int count = std::distance(begin, end);
- auto checker_begin = checker_.lower_bound(begin.key());
- for (iterator tmp(tree_.lower_bound(begin.key())); tmp != begin; ++tmp) {
- ++checker_begin;
- }
- auto checker_end =
- end == tree_.end() ? checker_.end() : checker_.lower_bound(end.key());
- if (end != tree_.end()) {
- for (iterator tmp(tree_.lower_bound(end.key())); tmp != end; ++tmp) {
- ++checker_end;
- }
- }
- const auto checker_ret = checker_.erase(checker_begin, checker_end);
- const auto tree_ret = tree_.erase(begin, end);
- EXPECT_EQ(std::distance(checker_.begin(), checker_ret),
- std::distance(tree_.begin(), tree_ret));
- EXPECT_EQ(tree_.size(), checker_.size());
- EXPECT_EQ(tree_.size(), size - count);
- }
-
- void clear() {
- tree_.clear();
- checker_.clear();
- }
- void swap(base_checker &other) {
- tree_.swap(other.tree_);
- checker_.swap(other.checker_);
- }
-
- void verify() const {
- tree_.verify();
- EXPECT_EQ(tree_.size(), checker_.size());
-
- // Move through the forward iterators using increment.
- auto checker_iter = checker_.begin();
- const_iterator tree_iter(tree_.begin());
- for (; tree_iter != tree_.end(); ++tree_iter, ++checker_iter) {
- CheckPairEquals(*tree_iter, *checker_iter);
- }
-
- // Move through the forward iterators using decrement.
- for (int n = tree_.size() - 1; n >= 0; --n) {
- iter_check(tree_iter, checker_iter);
- --tree_iter;
- --checker_iter;
- }
- EXPECT_EQ(tree_iter, tree_.begin());
- EXPECT_EQ(checker_iter, checker_.begin());
-
- // Move through the reverse iterators using increment.
- auto checker_riter = checker_.rbegin();
- const_reverse_iterator tree_riter(tree_.rbegin());
- for (; tree_riter != tree_.rend(); ++tree_riter, ++checker_riter) {
- CheckPairEquals(*tree_riter, *checker_riter);
- }
-
- // Move through the reverse iterators using decrement.
- for (int n = tree_.size() - 1; n >= 0; --n) {
- riter_check(tree_riter, checker_riter);
- --tree_riter;
- --checker_riter;
- }
- EXPECT_EQ(tree_riter, tree_.rbegin());
- EXPECT_EQ(checker_riter, checker_.rbegin());
- }
-
- const TreeType &tree() const { return tree_; }
-
- size_type size() const {
- EXPECT_EQ(tree_.size(), checker_.size());
- return tree_.size();
- }
- size_type max_size() const { return tree_.max_size(); }
- bool empty() const {
- EXPECT_EQ(tree_.empty(), checker_.empty());
- return tree_.empty();
- }
-
- protected:
- TreeType tree_;
- const TreeType &const_tree_;
- CheckerType checker_;
-};
-
-namespace {
-// A checker for unique sorted associative containers. TreeType is expected to
-// be btree_{set,map} and CheckerType is expected to be {set,map}.
-template <typename TreeType, typename CheckerType>
-class unique_checker : public base_checker<TreeType, CheckerType> {
- using super_type = base_checker<TreeType, CheckerType>;
-
- public:
- using iterator = typename super_type::iterator;
- using value_type = typename super_type::value_type;
-
- public:
- unique_checker() : super_type() {}
- unique_checker(const unique_checker &other) : super_type(other) {}
- template <class InputIterator>
- unique_checker(InputIterator b, InputIterator e) : super_type(b, e) {}
- unique_checker &operator=(const unique_checker &) = default;
-
- // Insertion routines.
- std::pair<iterator, bool> insert(const value_type &v) {
- int size = this->tree_.size();
- std::pair<typename CheckerType::iterator, bool> checker_res =
- this->checker_.insert(v);
- std::pair<iterator, bool> tree_res = this->tree_.insert(v);
- CheckPairEquals(*tree_res.first, *checker_res.first);
- EXPECT_EQ(tree_res.second, checker_res.second);
- EXPECT_EQ(this->tree_.size(), this->checker_.size());
- EXPECT_EQ(this->tree_.size(), size + tree_res.second);
- return tree_res;
- }
- iterator insert(iterator position, const value_type &v) {
- int size = this->tree_.size();
- std::pair<typename CheckerType::iterator, bool> checker_res =
- this->checker_.insert(v);
- iterator tree_res = this->tree_.insert(position, v);
- CheckPairEquals(*tree_res, *checker_res.first);
- EXPECT_EQ(this->tree_.size(), this->checker_.size());
- EXPECT_EQ(this->tree_.size(), size + checker_res.second);
- return tree_res;
- }
- template <typename InputIterator>
- void insert(InputIterator b, InputIterator e) {
- for (; b != e; ++b) {
- insert(*b);
- }
- }
-};
-
-// A checker for multiple sorted associative containers. TreeType is expected
-// to be btree_{multiset,multimap} and CheckerType is expected to be
-// {multiset,multimap}.
-template <typename TreeType, typename CheckerType>
-class multi_checker : public base_checker<TreeType, CheckerType> {
- using super_type = base_checker<TreeType, CheckerType>;
-
- public:
- using iterator = typename super_type::iterator;
- using value_type = typename super_type::value_type;
-
- public:
- multi_checker() : super_type() {}
- multi_checker(const multi_checker &other) : super_type(other) {}
- template <class InputIterator>
- multi_checker(InputIterator b, InputIterator e) : super_type(b, e) {}
- multi_checker &operator=(const multi_checker &) = default;
-
- // Insertion routines.
- iterator insert(const value_type &v) {
- int size = this->tree_.size();
- auto checker_res = this->checker_.insert(v);
- iterator tree_res = this->tree_.insert(v);
- CheckPairEquals(*tree_res, *checker_res);
- EXPECT_EQ(this->tree_.size(), this->checker_.size());
- EXPECT_EQ(this->tree_.size(), size + 1);
- return tree_res;
- }
- iterator insert(iterator position, const value_type &v) {
- int size = this->tree_.size();
- auto checker_res = this->checker_.insert(v);
- iterator tree_res = this->tree_.insert(position, v);
- CheckPairEquals(*tree_res, *checker_res);
- EXPECT_EQ(this->tree_.size(), this->checker_.size());
- EXPECT_EQ(this->tree_.size(), size + 1);
- return tree_res;
- }
- template <typename InputIterator>
- void insert(InputIterator b, InputIterator e) {
- for (; b != e; ++b) {
- insert(*b);
- }
- }
-};
-
-template <typename T, typename V>
-void DoTest(const char *name, T *b, const std::vector<V> &values) {
- typename KeyOfValue<typename T::key_type, V>::type key_of_value;
-
- T &mutable_b = *b;
- const T &const_b = *b;
-
- // Test insert.
- for (int i = 0; i < values.size(); ++i) {
- mutable_b.insert(values[i]);
- mutable_b.value_check(values[i]);
- }
- ASSERT_EQ(mutable_b.size(), values.size());
-
- const_b.verify();
-
- // Test copy constructor.
- T b_copy(const_b);
- EXPECT_EQ(b_copy.size(), const_b.size());
- for (int i = 0; i < values.size(); ++i) {
- CheckPairEquals(*b_copy.find(key_of_value(values[i])), values[i]);
- }
-
- // Test range constructor.
- T b_range(const_b.begin(), const_b.end());
- EXPECT_EQ(b_range.size(), const_b.size());
- for (int i = 0; i < values.size(); ++i) {
- CheckPairEquals(*b_range.find(key_of_value(values[i])), values[i]);
- }
-
- // Test range insertion for values that already exist.
- b_range.insert(b_copy.begin(), b_copy.end());
- b_range.verify();
-
- // Test range insertion for new values.
- b_range.clear();
- b_range.insert(b_copy.begin(), b_copy.end());
- EXPECT_EQ(b_range.size(), b_copy.size());
- for (int i = 0; i < values.size(); ++i) {
- CheckPairEquals(*b_range.find(key_of_value(values[i])), values[i]);
- }
-
- // Test assignment to self. Nothing should change.
- b_range.operator=(b_range);
- EXPECT_EQ(b_range.size(), b_copy.size());
-
- // Test assignment of new values.
- b_range.clear();
- b_range = b_copy;
- EXPECT_EQ(b_range.size(), b_copy.size());
-
- // Test swap.
- b_range.clear();
- b_range.swap(b_copy);
- EXPECT_EQ(b_copy.size(), 0);
- EXPECT_EQ(b_range.size(), const_b.size());
- for (int i = 0; i < values.size(); ++i) {
- CheckPairEquals(*b_range.find(key_of_value(values[i])), values[i]);
- }
- b_range.swap(b_copy);
-
- // Test non-member function swap.
- swap(b_range, b_copy);
- EXPECT_EQ(b_copy.size(), 0);
- EXPECT_EQ(b_range.size(), const_b.size());
- for (int i = 0; i < values.size(); ++i) {
- CheckPairEquals(*b_range.find(key_of_value(values[i])), values[i]);
- }
- swap(b_range, b_copy);
-
- // Test erase via values.
- for (int i = 0; i < values.size(); ++i) {
- mutable_b.erase(key_of_value(values[i]));
- // Erasing a non-existent key should have no effect.
- ASSERT_EQ(mutable_b.erase(key_of_value(values[i])), 0);
- }
-
- const_b.verify();
- EXPECT_EQ(const_b.size(), 0);
-
- // Test erase via iterators.
- mutable_b = b_copy;
- for (int i = 0; i < values.size(); ++i) {
- mutable_b.erase(mutable_b.find(key_of_value(values[i])));
- }
-
- const_b.verify();
- EXPECT_EQ(const_b.size(), 0);
-
- // Test insert with hint.
- for (int i = 0; i < values.size(); i++) {
- mutable_b.insert(mutable_b.upper_bound(key_of_value(values[i])), values[i]);
- }
-
- const_b.verify();
-
- // Test range erase.
- mutable_b.erase(mutable_b.begin(), mutable_b.end());
- EXPECT_EQ(mutable_b.size(), 0);
- const_b.verify();
-
- // First half.
- mutable_b = b_copy;
- typename T::iterator mutable_iter_end = mutable_b.begin();
- for (int i = 0; i < values.size() / 2; ++i) ++mutable_iter_end;
- mutable_b.erase(mutable_b.begin(), mutable_iter_end);
- EXPECT_EQ(mutable_b.size(), values.size() - values.size() / 2);
- const_b.verify();
-
- // Second half.
- mutable_b = b_copy;
- typename T::iterator mutable_iter_begin = mutable_b.begin();
- for (int i = 0; i < values.size() / 2; ++i) ++mutable_iter_begin;
- mutable_b.erase(mutable_iter_begin, mutable_b.end());
- EXPECT_EQ(mutable_b.size(), values.size() / 2);
- const_b.verify();
-
- // Second quarter.
- mutable_b = b_copy;
- mutable_iter_begin = mutable_b.begin();
- for (int i = 0; i < values.size() / 4; ++i) ++mutable_iter_begin;
- mutable_iter_end = mutable_iter_begin;
- for (int i = 0; i < values.size() / 4; ++i) ++mutable_iter_end;
- mutable_b.erase(mutable_iter_begin, mutable_iter_end);
- EXPECT_EQ(mutable_b.size(), values.size() - values.size() / 4);
- const_b.verify();
-
- mutable_b.clear();
-}
-
-template <typename T>
-void ConstTest() {
- using value_type = typename T::value_type;
- typename KeyOfValue<typename T::key_type, value_type>::type key_of_value;
-
- T mutable_b;
- const T &const_b = mutable_b;
-
- // Insert a single value into the container and test looking it up.
- value_type value = Generator<value_type>(2)(2);
- mutable_b.insert(value);
- EXPECT_TRUE(mutable_b.contains(key_of_value(value)));
- EXPECT_NE(mutable_b.find(key_of_value(value)), const_b.end());
- EXPECT_TRUE(const_b.contains(key_of_value(value)));
- EXPECT_NE(const_b.find(key_of_value(value)), mutable_b.end());
- EXPECT_EQ(*const_b.lower_bound(key_of_value(value)), value);
- EXPECT_EQ(const_b.upper_bound(key_of_value(value)), const_b.end());
- EXPECT_EQ(*const_b.equal_range(key_of_value(value)).first, value);
-
- // We can only create a non-const iterator from a non-const container.
- typename T::iterator mutable_iter(mutable_b.begin());
- EXPECT_EQ(mutable_iter, const_b.begin());
- EXPECT_NE(mutable_iter, const_b.end());
- EXPECT_EQ(const_b.begin(), mutable_iter);
- EXPECT_NE(const_b.end(), mutable_iter);
- typename T::reverse_iterator mutable_riter(mutable_b.rbegin());
- EXPECT_EQ(mutable_riter, const_b.rbegin());
- EXPECT_NE(mutable_riter, const_b.rend());
- EXPECT_EQ(const_b.rbegin(), mutable_riter);
- EXPECT_NE(const_b.rend(), mutable_riter);
-
- // We can create a const iterator from a non-const iterator.
- typename T::const_iterator const_iter(mutable_iter);
- EXPECT_EQ(const_iter, mutable_b.begin());
- EXPECT_NE(const_iter, mutable_b.end());
- EXPECT_EQ(mutable_b.begin(), const_iter);
- EXPECT_NE(mutable_b.end(), const_iter);
- typename T::const_reverse_iterator const_riter(mutable_riter);
- EXPECT_EQ(const_riter, mutable_b.rbegin());
- EXPECT_NE(const_riter, mutable_b.rend());
- EXPECT_EQ(mutable_b.rbegin(), const_riter);
- EXPECT_NE(mutable_b.rend(), const_riter);
-
- // Make sure various methods can be invoked on a const container.
- const_b.verify();
- ASSERT_TRUE(!const_b.empty());
- EXPECT_EQ(const_b.size(), 1);
- EXPECT_GT(const_b.max_size(), 0);
- EXPECT_TRUE(const_b.contains(key_of_value(value)));
- EXPECT_EQ(const_b.count(key_of_value(value)), 1);
-}
-
-template <typename T, typename C>
-void BtreeTest() {
- ConstTest<T>();
-
- using V = typename remove_pair_const<typename T::value_type>::type;
- const std::vector<V> random_values = GenerateValuesWithSeed<V>(
- absl::GetFlag(FLAGS_test_values), 4 * absl::GetFlag(FLAGS_test_values),
- GTEST_FLAG_GET(random_seed));
-
- unique_checker<T, C> container;
-
- // Test key insertion/deletion in sorted order.
- std::vector<V> sorted_values(random_values);
- std::sort(sorted_values.begin(), sorted_values.end());
- DoTest("sorted: ", &container, sorted_values);
-
- // Test key insertion/deletion in reverse sorted order.
- std::reverse(sorted_values.begin(), sorted_values.end());
- DoTest("rsorted: ", &container, sorted_values);
-
- // Test key insertion/deletion in random order.
- DoTest("random: ", &container, random_values);
-}
-
-template <typename T, typename C>
-void BtreeMultiTest() {
- ConstTest<T>();
-
- using V = typename remove_pair_const<typename T::value_type>::type;
- const std::vector<V> random_values = GenerateValuesWithSeed<V>(
- absl::GetFlag(FLAGS_test_values), 4 * absl::GetFlag(FLAGS_test_values),
- GTEST_FLAG_GET(random_seed));
-
- multi_checker<T, C> container;
-
- // Test keys in sorted order.
- std::vector<V> sorted_values(random_values);
- std::sort(sorted_values.begin(), sorted_values.end());
- DoTest("sorted: ", &container, sorted_values);
-
- // Test keys in reverse sorted order.
- std::reverse(sorted_values.begin(), sorted_values.end());
- DoTest("rsorted: ", &container, sorted_values);
-
- // Test keys in random order.
- DoTest("random: ", &container, random_values);
-
- // Test keys in random order w/ duplicates.
- std::vector<V> duplicate_values(random_values);
- duplicate_values.insert(duplicate_values.end(), random_values.begin(),
- random_values.end());
- DoTest("duplicates:", &container, duplicate_values);
-
- // Test all identical keys.
- std::vector<V> identical_values(100);
- std::fill(identical_values.begin(), identical_values.end(),
- Generator<V>(2)(2));
- DoTest("identical: ", &container, identical_values);
-}
-
-template <typename T>
-struct PropagatingCountingAlloc : public CountingAllocator<T> {
- using propagate_on_container_copy_assignment = std::true_type;
- using propagate_on_container_move_assignment = std::true_type;
- using propagate_on_container_swap = std::true_type;
-
- using Base = CountingAllocator<T>;
- using Base::Base;
-
- template <typename U>
- explicit PropagatingCountingAlloc(const PropagatingCountingAlloc<U> &other)
- : Base(other.bytes_used_) {}
-
- template <typename U>
- struct rebind {
- using other = PropagatingCountingAlloc<U>;
- };
-};
-
-template <typename T>
-void BtreeAllocatorTest() {
- using value_type = typename T::value_type;
-
- int64_t bytes1 = 0, bytes2 = 0;
- PropagatingCountingAlloc<T> allocator1(&bytes1);
- PropagatingCountingAlloc<T> allocator2(&bytes2);
- Generator<value_type> generator(1000);
-
- // Test that we allocate properly aligned memory. If we don't, then Layout
- // will assert fail.
- auto unused1 = allocator1.allocate(1);
- auto unused2 = allocator2.allocate(1);
-
- // Test copy assignment
- {
- T b1(typename T::key_compare(), allocator1);
- T b2(typename T::key_compare(), allocator2);
-
- int64_t original_bytes1 = bytes1;
- b1.insert(generator(0));
- EXPECT_GT(bytes1, original_bytes1);
-
- // This should propagate the allocator.
- b1 = b2;
- EXPECT_EQ(b1.size(), 0);
- EXPECT_EQ(b2.size(), 0);
- EXPECT_EQ(bytes1, original_bytes1);
-
- for (int i = 1; i < 1000; i++) {
- b1.insert(generator(i));
- }
-
- // We should have allocated out of allocator2.
- EXPECT_GT(bytes2, bytes1);
- }
-
- // Test move assignment
- {
- T b1(typename T::key_compare(), allocator1);
- T b2(typename T::key_compare(), allocator2);
-
- int64_t original_bytes1 = bytes1;
- b1.insert(generator(0));
- EXPECT_GT(bytes1, original_bytes1);
-
- // This should propagate the allocator.
- b1 = std::move(b2);
- EXPECT_EQ(b1.size(), 0);
- EXPECT_EQ(bytes1, original_bytes1);
-
- for (int i = 1; i < 1000; i++) {
- b1.insert(generator(i));
- }
-
- // We should have allocated out of allocator2.
- EXPECT_GT(bytes2, bytes1);
- }
-
- // Test swap
- {
- T b1(typename T::key_compare(), allocator1);
- T b2(typename T::key_compare(), allocator2);
-
- int64_t original_bytes1 = bytes1;
- b1.insert(generator(0));
- EXPECT_GT(bytes1, original_bytes1);
-
- // This should swap the allocators.
- swap(b1, b2);
- EXPECT_EQ(b1.size(), 0);
- EXPECT_EQ(b2.size(), 1);
- EXPECT_GT(bytes1, original_bytes1);
-
- for (int i = 1; i < 1000; i++) {
- b1.insert(generator(i));
- }
-
- // We should have allocated out of allocator2.
- EXPECT_GT(bytes2, bytes1);
- }
-
- allocator1.deallocate(unused1, 1);
- allocator2.deallocate(unused2, 1);
-}
-
-template <typename T>
-void BtreeMapTest() {
- using value_type = typename T::value_type;
- using mapped_type = typename T::mapped_type;
-
- mapped_type m = Generator<mapped_type>(0)(0);
- (void)m;
-
- T b;
-
- // Verify we can insert using operator[].
- for (int i = 0; i < 1000; i++) {
- value_type v = Generator<value_type>(1000)(i);
- b[v.first] = v.second;
- }
- EXPECT_EQ(b.size(), 1000);
-
- // Test whether we can use the "->" operator on iterators and
- // reverse_iterators. This stresses the btree_map_params::pair_pointer
- // mechanism.
- EXPECT_EQ(b.begin()->first, Generator<value_type>(1000)(0).first);
- EXPECT_EQ(b.begin()->second, Generator<value_type>(1000)(0).second);
- EXPECT_EQ(b.rbegin()->first, Generator<value_type>(1000)(999).first);
- EXPECT_EQ(b.rbegin()->second, Generator<value_type>(1000)(999).second);
-}
-
-template <typename T>
-void BtreeMultiMapTest() {
- using mapped_type = typename T::mapped_type;
- mapped_type m = Generator<mapped_type>(0)(0);
- (void)m;
-}
-
-template <typename K, int N = 256>
-void SetTest() {
- EXPECT_EQ(
- sizeof(absl::btree_set<K>),
- 2 * sizeof(void *) + sizeof(typename absl::btree_set<K>::size_type));
- using BtreeSet = absl::btree_set<K>;
- using CountingBtreeSet =
- absl::btree_set<K, std::less<K>, PropagatingCountingAlloc<K>>;
- BtreeTest<BtreeSet, std::set<K>>();
- BtreeAllocatorTest<CountingBtreeSet>();
-}
-
-template <typename K, int N = 256>
-void MapTest() {
- EXPECT_EQ(
- sizeof(absl::btree_map<K, K>),
- 2 * sizeof(void *) + sizeof(typename absl::btree_map<K, K>::size_type));
- using BtreeMap = absl::btree_map<K, K>;
- using CountingBtreeMap =
- absl::btree_map<K, K, std::less<K>,
- PropagatingCountingAlloc<std::pair<const K, K>>>;
- BtreeTest<BtreeMap, std::map<K, K>>();
- BtreeAllocatorTest<CountingBtreeMap>();
- BtreeMapTest<BtreeMap>();
-}
-
-TEST(Btree, set_int32) { SetTest<int32_t>(); }
-TEST(Btree, set_int64) { SetTest<int64_t>(); }
-TEST(Btree, set_string) { SetTest<std::string>(); }
-TEST(Btree, set_cord) { SetTest<absl::Cord>(); }
-TEST(Btree, set_pair) { SetTest<std::pair<int, int>>(); }
-TEST(Btree, map_int32) { MapTest<int32_t>(); }
-TEST(Btree, map_int64) { MapTest<int64_t>(); }
-TEST(Btree, map_string) { MapTest<std::string>(); }
-TEST(Btree, map_cord) { MapTest<absl::Cord>(); }
-TEST(Btree, map_pair) { MapTest<std::pair<int, int>>(); }
-
-template <typename K, int N = 256>
-void MultiSetTest() {
- EXPECT_EQ(
- sizeof(absl::btree_multiset<K>),
- 2 * sizeof(void *) + sizeof(typename absl::btree_multiset<K>::size_type));
- using BtreeMSet = absl::btree_multiset<K>;
- using CountingBtreeMSet =
- absl::btree_multiset<K, std::less<K>, PropagatingCountingAlloc<K>>;
- BtreeMultiTest<BtreeMSet, std::multiset<K>>();
- BtreeAllocatorTest<CountingBtreeMSet>();
-}
-
-template <typename K, int N = 256>
-void MultiMapTest() {
- EXPECT_EQ(sizeof(absl::btree_multimap<K, K>),
- 2 * sizeof(void *) +
- sizeof(typename absl::btree_multimap<K, K>::size_type));
- using BtreeMMap = absl::btree_multimap<K, K>;
- using CountingBtreeMMap =
- absl::btree_multimap<K, K, std::less<K>,
- PropagatingCountingAlloc<std::pair<const K, K>>>;
- BtreeMultiTest<BtreeMMap, std::multimap<K, K>>();
- BtreeMultiMapTest<BtreeMMap>();
- BtreeAllocatorTest<CountingBtreeMMap>();
-}
-
-TEST(Btree, multiset_int32) { MultiSetTest<int32_t>(); }
-TEST(Btree, multiset_int64) { MultiSetTest<int64_t>(); }
-TEST(Btree, multiset_string) { MultiSetTest<std::string>(); }
-TEST(Btree, multiset_cord) { MultiSetTest<absl::Cord>(); }
-TEST(Btree, multiset_pair) { MultiSetTest<std::pair<int, int>>(); }
-TEST(Btree, multimap_int32) { MultiMapTest<int32_t>(); }
-TEST(Btree, multimap_int64) { MultiMapTest<int64_t>(); }
-TEST(Btree, multimap_string) { MultiMapTest<std::string>(); }
-TEST(Btree, multimap_cord) { MultiMapTest<absl::Cord>(); }
-TEST(Btree, multimap_pair) { MultiMapTest<std::pair<int, int>>(); }
-
-struct CompareIntToString {
- bool operator()(const std::string &a, const std::string &b) const {
- return a < b;
- }
- bool operator()(const std::string &a, int b) const {
- return a < absl::StrCat(b);
- }
- bool operator()(int a, const std::string &b) const {
- return absl::StrCat(a) < b;
- }
- using is_transparent = void;
-};
-
-struct NonTransparentCompare {
- template <typename T, typename U>
- bool operator()(const T &t, const U &u) const {
- // Treating all comparators as transparent can cause inefficiencies (see
- // N3657 C++ proposal). Test that for comparators without 'is_transparent'
- // alias (like this one), we do not attempt heterogeneous lookup.
- EXPECT_TRUE((std::is_same<T, U>()));
- return t < u;
- }
-};
-
-template <typename T>
-bool CanEraseWithEmptyBrace(T t, decltype(t.erase({})) *) {
- return true;
-}
-
-template <typename T>
-bool CanEraseWithEmptyBrace(T, ...) {
- return false;
-}
-
-template <typename T>
-void TestHeterogeneous(T table) {
- auto lb = table.lower_bound("3");
- EXPECT_EQ(lb, table.lower_bound(3));
- EXPECT_NE(lb, table.lower_bound(4));
- EXPECT_EQ(lb, table.lower_bound({"3"}));
- EXPECT_NE(lb, table.lower_bound({}));
-
- auto ub = table.upper_bound("3");
- EXPECT_EQ(ub, table.upper_bound(3));
- EXPECT_NE(ub, table.upper_bound(5));
- EXPECT_EQ(ub, table.upper_bound({"3"}));
- EXPECT_NE(ub, table.upper_bound({}));
-
- auto er = table.equal_range("3");
- EXPECT_EQ(er, table.equal_range(3));
- EXPECT_NE(er, table.equal_range(4));
- EXPECT_EQ(er, table.equal_range({"3"}));
- EXPECT_NE(er, table.equal_range({}));
-
- auto it = table.find("3");
- EXPECT_EQ(it, table.find(3));
- EXPECT_NE(it, table.find(4));
- EXPECT_EQ(it, table.find({"3"}));
- EXPECT_NE(it, table.find({}));
-
- EXPECT_TRUE(table.contains(3));
- EXPECT_FALSE(table.contains(4));
- EXPECT_TRUE(table.count({"3"}));
- EXPECT_FALSE(table.contains({}));
-
- EXPECT_EQ(1, table.count(3));
- EXPECT_EQ(0, table.count(4));
- EXPECT_EQ(1, table.count({"3"}));
- EXPECT_EQ(0, table.count({}));
-
- auto copy = table;
- copy.erase(3);
- EXPECT_EQ(table.size() - 1, copy.size());
- copy.erase(4);
- EXPECT_EQ(table.size() - 1, copy.size());
- copy.erase({"5"});
- EXPECT_EQ(table.size() - 2, copy.size());
- EXPECT_FALSE(CanEraseWithEmptyBrace(table, nullptr));
-
- // Also run it with const T&.
- if (std::is_class<T>()) TestHeterogeneous<const T &>(table);
-}
-
-TEST(Btree, HeterogeneousLookup) {
- TestHeterogeneous(btree_set<std::string, CompareIntToString>{"1", "3", "5"});
- TestHeterogeneous(btree_map<std::string, int, CompareIntToString>{
- {"1", 1}, {"3", 3}, {"5", 5}});
- TestHeterogeneous(
- btree_multiset<std::string, CompareIntToString>{"1", "3", "5"});
- TestHeterogeneous(btree_multimap<std::string, int, CompareIntToString>{
- {"1", 1}, {"3", 3}, {"5", 5}});
-
- // Only maps have .at()
- btree_map<std::string, int, CompareIntToString> map{
- {"", -1}, {"1", 1}, {"3", 3}, {"5", 5}};
- EXPECT_EQ(1, map.at(1));
- EXPECT_EQ(3, map.at({"3"}));
- EXPECT_EQ(-1, map.at({}));
- const auto &cmap = map;
- EXPECT_EQ(1, cmap.at(1));
- EXPECT_EQ(3, cmap.at({"3"}));
- EXPECT_EQ(-1, cmap.at({}));
-}
-
-TEST(Btree, NoHeterogeneousLookupWithoutAlias) {
- using StringSet = absl::btree_set<std::string, NonTransparentCompare>;
- StringSet s;
- ASSERT_TRUE(s.insert("hello").second);
- ASSERT_TRUE(s.insert("world").second);
- EXPECT_TRUE(s.end() == s.find("blah"));
- EXPECT_TRUE(s.begin() == s.lower_bound("hello"));
- EXPECT_EQ(1, s.count("world"));
- EXPECT_TRUE(s.contains("hello"));
- EXPECT_TRUE(s.contains("world"));
- EXPECT_FALSE(s.contains("blah"));
-
- using StringMultiSet =
- absl::btree_multiset<std::string, NonTransparentCompare>;
- StringMultiSet ms;
- ms.insert("hello");
- ms.insert("world");
- ms.insert("world");
- EXPECT_TRUE(ms.end() == ms.find("blah"));
- EXPECT_TRUE(ms.begin() == ms.lower_bound("hello"));
- EXPECT_EQ(2, ms.count("world"));
- EXPECT_TRUE(ms.contains("hello"));
- EXPECT_TRUE(ms.contains("world"));
- EXPECT_FALSE(ms.contains("blah"));
-}
-
-TEST(Btree, DefaultTransparent) {
- {
- // `int` does not have a default transparent comparator.
- // The input value is converted to key_type.
- btree_set<int> s = {1};
- double d = 1.1;
- EXPECT_EQ(s.begin(), s.find(d));
- EXPECT_TRUE(s.contains(d));
- }
-
- {
- // `std::string` has heterogeneous support.
- btree_set<std::string> s = {"A"};
- EXPECT_EQ(s.begin(), s.find(absl::string_view("A")));
- EXPECT_TRUE(s.contains(absl::string_view("A")));
- }
-}
-
-class StringLike {
- public:
- StringLike() = default;
-
- StringLike(const char *s) : s_(s) { // NOLINT
- ++constructor_calls_;
- }
-
- bool operator<(const StringLike &a) const { return s_ < a.s_; }
-
- static void clear_constructor_call_count() { constructor_calls_ = 0; }
-
- static int constructor_calls() { return constructor_calls_; }
-
- private:
- static int constructor_calls_;
- std::string s_;
-};
-
-int StringLike::constructor_calls_ = 0;
-
-TEST(Btree, HeterogeneousLookupDoesntDegradePerformance) {
- using StringSet = absl::btree_set<StringLike>;
- StringSet s;
- for (int i = 0; i < 100; ++i) {
- ASSERT_TRUE(s.insert(absl::StrCat(i).c_str()).second);
- }
- StringLike::clear_constructor_call_count();
- s.find("50");
- ASSERT_EQ(1, StringLike::constructor_calls());
-
- StringLike::clear_constructor_call_count();
- s.contains("50");
- ASSERT_EQ(1, StringLike::constructor_calls());
-
- StringLike::clear_constructor_call_count();
- s.count("50");
- ASSERT_EQ(1, StringLike::constructor_calls());
-
- StringLike::clear_constructor_call_count();
- s.lower_bound("50");
- ASSERT_EQ(1, StringLike::constructor_calls());
-
- StringLike::clear_constructor_call_count();
- s.upper_bound("50");
- ASSERT_EQ(1, StringLike::constructor_calls());
-
- StringLike::clear_constructor_call_count();
- s.equal_range("50");
- ASSERT_EQ(1, StringLike::constructor_calls());
-
- StringLike::clear_constructor_call_count();
- s.erase("50");
- ASSERT_EQ(1, StringLike::constructor_calls());
-}
-
-// Verify that swapping btrees swaps the key comparison functors and that we can
-// use non-default constructible comparators.
-struct SubstringLess {
- SubstringLess() = delete;
- explicit SubstringLess(int length) : n(length) {}
- bool operator()(const std::string &a, const std::string &b) const {
- return absl::string_view(a).substr(0, n) <
- absl::string_view(b).substr(0, n);
- }
- int n;
-};
-
-TEST(Btree, SwapKeyCompare) {
- using SubstringSet = absl::btree_set<std::string, SubstringLess>;
- SubstringSet s1(SubstringLess(1), SubstringSet::allocator_type());
- SubstringSet s2(SubstringLess(2), SubstringSet::allocator_type());
-
- ASSERT_TRUE(s1.insert("a").second);
- ASSERT_FALSE(s1.insert("aa").second);
-
- ASSERT_TRUE(s2.insert("a").second);
- ASSERT_TRUE(s2.insert("aa").second);
- ASSERT_FALSE(s2.insert("aaa").second);
-
- swap(s1, s2);
-
- ASSERT_TRUE(s1.insert("b").second);
- ASSERT_TRUE(s1.insert("bb").second);
- ASSERT_FALSE(s1.insert("bbb").second);
-
- ASSERT_TRUE(s2.insert("b").second);
- ASSERT_FALSE(s2.insert("bb").second);
-}
-
-TEST(Btree, UpperBoundRegression) {
- // Regress a bug where upper_bound would default-construct a new key_compare
- // instead of copying the existing one.
- using SubstringSet = absl::btree_set<std::string, SubstringLess>;
- SubstringSet my_set(SubstringLess(3));
- my_set.insert("aab");
- my_set.insert("abb");
- // We call upper_bound("aaa"). If this correctly uses the length 3
- // comparator, aaa < aab < abb, so we should get aab as the result.
- // If it instead uses the default-constructed length 2 comparator,
- // aa == aa < ab, so we'll get abb as our result.
- SubstringSet::iterator it = my_set.upper_bound("aaa");
- ASSERT_TRUE(it != my_set.end());
- EXPECT_EQ("aab", *it);
-}
-
-TEST(Btree, Comparison) {
- const int kSetSize = 1201;
- absl::btree_set<int64_t> my_set;
- for (int i = 0; i < kSetSize; ++i) {
- my_set.insert(i);
- }
- absl::btree_set<int64_t> my_set_copy(my_set);
- EXPECT_TRUE(my_set_copy == my_set);
- EXPECT_TRUE(my_set == my_set_copy);
- EXPECT_FALSE(my_set_copy != my_set);
- EXPECT_FALSE(my_set != my_set_copy);
-
- my_set.insert(kSetSize);
- EXPECT_FALSE(my_set_copy == my_set);
- EXPECT_FALSE(my_set == my_set_copy);
- EXPECT_TRUE(my_set_copy != my_set);
- EXPECT_TRUE(my_set != my_set_copy);
-
- my_set.erase(kSetSize - 1);
- EXPECT_FALSE(my_set_copy == my_set);
- EXPECT_FALSE(my_set == my_set_copy);
- EXPECT_TRUE(my_set_copy != my_set);
- EXPECT_TRUE(my_set != my_set_copy);
-
- absl::btree_map<std::string, int64_t> my_map;
- for (int i = 0; i < kSetSize; ++i) {
- my_map[std::string(i, 'a')] = i;
- }
- absl::btree_map<std::string, int64_t> my_map_copy(my_map);
- EXPECT_TRUE(my_map_copy == my_map);
- EXPECT_TRUE(my_map == my_map_copy);
- EXPECT_FALSE(my_map_copy != my_map);
- EXPECT_FALSE(my_map != my_map_copy);
-
- ++my_map_copy[std::string(7, 'a')];
- EXPECT_FALSE(my_map_copy == my_map);
- EXPECT_FALSE(my_map == my_map_copy);
- EXPECT_TRUE(my_map_copy != my_map);
- EXPECT_TRUE(my_map != my_map_copy);
-
- my_map_copy = my_map;
- my_map["hello"] = kSetSize;
- EXPECT_FALSE(my_map_copy == my_map);
- EXPECT_FALSE(my_map == my_map_copy);
- EXPECT_TRUE(my_map_copy != my_map);
- EXPECT_TRUE(my_map != my_map_copy);
-
- my_map.erase(std::string(kSetSize - 1, 'a'));
- EXPECT_FALSE(my_map_copy == my_map);
- EXPECT_FALSE(my_map == my_map_copy);
- EXPECT_TRUE(my_map_copy != my_map);
- EXPECT_TRUE(my_map != my_map_copy);
-}
-
-TEST(Btree, RangeCtorSanity) {
- std::vector<int> ivec;
- ivec.push_back(1);
- std::map<int, int> imap;
- imap.insert(std::make_pair(1, 2));
- absl::btree_multiset<int> tmset(ivec.begin(), ivec.end());
- absl::btree_multimap<int, int> tmmap(imap.begin(), imap.end());
- absl::btree_set<int> tset(ivec.begin(), ivec.end());
- absl::btree_map<int, int> tmap(imap.begin(), imap.end());
- EXPECT_EQ(1, tmset.size());
- EXPECT_EQ(1, tmmap.size());
- EXPECT_EQ(1, tset.size());
- EXPECT_EQ(1, tmap.size());
-}
-
-} // namespace
-
-class BtreeNodePeer {
- public:
- // Yields the size of a leaf node with a specific number of values.
- template <typename ValueType>
- constexpr static size_t GetTargetNodeSize(size_t target_values_per_node) {
- return btree_node<
- set_params<ValueType, std::less<ValueType>, std::allocator<ValueType>,
- /*TargetNodeSize=*/256, // This parameter isn't used here.
- /*Multi=*/false>>::SizeWithNSlots(target_values_per_node);
- }
-
- // Yields the number of slots in a (non-root) leaf node for this btree.
- template <typename Btree>
- constexpr static size_t GetNumSlotsPerNode() {
- return btree_node<typename Btree::params_type>::kNodeSlots;
- }
-
- template <typename Btree>
- constexpr static size_t GetMaxFieldType() {
- return std::numeric_limits<
- typename btree_node<typename Btree::params_type>::field_type>::max();
- }
-
- template <typename Btree>
- constexpr static bool UsesLinearNodeSearch() {
- return btree_node<typename Btree::params_type>::use_linear_search::value;
- }
-
- template <typename Btree>
- constexpr static bool UsesGenerations() {
- return Btree::params_type::kEnableGenerations;
- }
-};
-
-namespace {
-
-class BtreeMapTest : public ::testing::Test {
- public:
- struct Key {};
- struct Cmp {
- template <typename T>
- bool operator()(T, T) const {
- return false;
- }
- };
-
- struct KeyLin {
- using absl_btree_prefer_linear_node_search = std::true_type;
- };
- struct CmpLin : Cmp {
- using absl_btree_prefer_linear_node_search = std::true_type;
- };
-
- struct KeyBin {
- using absl_btree_prefer_linear_node_search = std::false_type;
- };
- struct CmpBin : Cmp {
- using absl_btree_prefer_linear_node_search = std::false_type;
- };
-
- template <typename K, typename C>
- static bool IsLinear() {
- return BtreeNodePeer::UsesLinearNodeSearch<absl::btree_map<K, int, C>>();
- }
-};
-
-TEST_F(BtreeMapTest, TestLinearSearchPreferredForKeyLinearViaAlias) {
- // Test requesting linear search by directly exporting an alias.
- EXPECT_FALSE((IsLinear<Key, Cmp>()));
- EXPECT_TRUE((IsLinear<KeyLin, Cmp>()));
- EXPECT_TRUE((IsLinear<Key, CmpLin>()));
- EXPECT_TRUE((IsLinear<KeyLin, CmpLin>()));
-}
-
-TEST_F(BtreeMapTest, LinearChoiceTree) {
- // Cmp has precedence, and is forcing binary
- EXPECT_FALSE((IsLinear<Key, CmpBin>()));
- EXPECT_FALSE((IsLinear<KeyLin, CmpBin>()));
- EXPECT_FALSE((IsLinear<KeyBin, CmpBin>()));
- EXPECT_FALSE((IsLinear<int, CmpBin>()));
- EXPECT_FALSE((IsLinear<std::string, CmpBin>()));
- // Cmp has precedence, and is forcing linear
- EXPECT_TRUE((IsLinear<Key, CmpLin>()));
- EXPECT_TRUE((IsLinear<KeyLin, CmpLin>()));
- EXPECT_TRUE((IsLinear<KeyBin, CmpLin>()));
- EXPECT_TRUE((IsLinear<int, CmpLin>()));
- EXPECT_TRUE((IsLinear<std::string, CmpLin>()));
- // Cmp has no preference, Key determines linear vs binary.
- EXPECT_FALSE((IsLinear<Key, Cmp>()));
- EXPECT_TRUE((IsLinear<KeyLin, Cmp>()));
- EXPECT_FALSE((IsLinear<KeyBin, Cmp>()));
- // arithmetic key w/ std::less or std::greater: linear
- EXPECT_TRUE((IsLinear<int, std::less<int>>()));
- EXPECT_TRUE((IsLinear<double, std::greater<double>>()));
- // arithmetic key w/ custom compare: binary
- EXPECT_FALSE((IsLinear<int, Cmp>()));
- // non-arithmetic key: binary
- EXPECT_FALSE((IsLinear<std::string, std::less<std::string>>()));
-}
-
-TEST(Btree, BtreeMapCanHoldMoveOnlyTypes) {
- absl::btree_map<std::string, std::unique_ptr<std::string>> m;
-
- std::unique_ptr<std::string> &v = m["A"];
- EXPECT_TRUE(v == nullptr);
- v = absl::make_unique<std::string>("X");
-
- auto iter = m.find("A");
- EXPECT_EQ("X", *iter->second);
-}
-
-TEST(Btree, InitializerListConstructor) {
- absl::btree_set<std::string> set({"a", "b"});
- EXPECT_EQ(set.count("a"), 1);
- EXPECT_EQ(set.count("b"), 1);
-
- absl::btree_multiset<int> mset({1, 1, 4});
- EXPECT_EQ(mset.count(1), 2);
- EXPECT_EQ(mset.count(4), 1);
-
- absl::btree_map<int, int> map({{1, 5}, {2, 10}});
- EXPECT_EQ(map[1], 5);
- EXPECT_EQ(map[2], 10);
-
- absl::btree_multimap<int, int> mmap({{1, 5}, {1, 10}});
- auto range = mmap.equal_range(1);
- auto it = range.first;
- ASSERT_NE(it, range.second);
- EXPECT_EQ(it->second, 5);
- ASSERT_NE(++it, range.second);
- EXPECT_EQ(it->second, 10);
- EXPECT_EQ(++it, range.second);
-}
-
-TEST(Btree, InitializerListInsert) {
- absl::btree_set<std::string> set;
- set.insert({"a", "b"});
- EXPECT_EQ(set.count("a"), 1);
- EXPECT_EQ(set.count("b"), 1);
-
- absl::btree_multiset<int> mset;
- mset.insert({1, 1, 4});
- EXPECT_EQ(mset.count(1), 2);
- EXPECT_EQ(mset.count(4), 1);
-
- absl::btree_map<int, int> map;
- map.insert({{1, 5}, {2, 10}});
- // Test that inserting one element using an initializer list also works.
- map.insert({3, 15});
- EXPECT_EQ(map[1], 5);
- EXPECT_EQ(map[2], 10);
- EXPECT_EQ(map[3], 15);
-
- absl::btree_multimap<int, int> mmap;
- mmap.insert({{1, 5}, {1, 10}});
- auto range = mmap.equal_range(1);
- auto it = range.first;
- ASSERT_NE(it, range.second);
- EXPECT_EQ(it->second, 5);
- ASSERT_NE(++it, range.second);
- EXPECT_EQ(it->second, 10);
- EXPECT_EQ(++it, range.second);
-}
-
-template <typename Compare, typename Key>
-void AssertKeyCompareStringAdapted() {
- using Adapted = typename key_compare_adapter<Compare, Key>::type;
- static_assert(
- std::is_same<Adapted, StringBtreeDefaultLess>::value ||
- std::is_same<Adapted, StringBtreeDefaultGreater>::value,
- "key_compare_adapter should have string-adapted this comparator.");
-}
-template <typename Compare, typename Key>
-void AssertKeyCompareNotStringAdapted() {
- using Adapted = typename key_compare_adapter<Compare, Key>::type;
- static_assert(
- !std::is_same<Adapted, StringBtreeDefaultLess>::value &&
- !std::is_same<Adapted, StringBtreeDefaultGreater>::value,
- "key_compare_adapter shouldn't have string-adapted this comparator.");
-}
-
-TEST(Btree, KeyCompareAdapter) {
- AssertKeyCompareStringAdapted<std::less<std::string>, std::string>();
- AssertKeyCompareStringAdapted<std::greater<std::string>, std::string>();
- AssertKeyCompareStringAdapted<std::less<absl::string_view>,
- absl::string_view>();
- AssertKeyCompareStringAdapted<std::greater<absl::string_view>,
- absl::string_view>();
- AssertKeyCompareStringAdapted<std::less<absl::Cord>, absl::Cord>();
- AssertKeyCompareStringAdapted<std::greater<absl::Cord>, absl::Cord>();
- AssertKeyCompareNotStringAdapted<std::less<int>, int>();
- AssertKeyCompareNotStringAdapted<std::greater<int>, int>();
-}
-
-TEST(Btree, RValueInsert) {
- InstanceTracker tracker;
-
- absl::btree_set<MovableOnlyInstance> set;
- set.insert(MovableOnlyInstance(1));
- set.insert(MovableOnlyInstance(3));
- MovableOnlyInstance two(2);
- set.insert(set.find(MovableOnlyInstance(3)), std::move(two));
- auto it = set.find(MovableOnlyInstance(2));
- ASSERT_NE(it, set.end());
- ASSERT_NE(++it, set.end());
- EXPECT_EQ(it->value(), 3);
-
- absl::btree_multiset<MovableOnlyInstance> mset;
- MovableOnlyInstance zero(0);
- MovableOnlyInstance zero2(0);
- mset.insert(std::move(zero));
- mset.insert(mset.find(MovableOnlyInstance(0)), std::move(zero2));
- EXPECT_EQ(mset.count(MovableOnlyInstance(0)), 2);
-
- absl::btree_map<int, MovableOnlyInstance> map;
- std::pair<const int, MovableOnlyInstance> p1 = {1, MovableOnlyInstance(5)};
- std::pair<const int, MovableOnlyInstance> p2 = {2, MovableOnlyInstance(10)};
- std::pair<const int, MovableOnlyInstance> p3 = {3, MovableOnlyInstance(15)};
- map.insert(std::move(p1));
- map.insert(std::move(p3));
- map.insert(map.find(3), std::move(p2));
- ASSERT_NE(map.find(2), map.end());
- EXPECT_EQ(map.find(2)->second.value(), 10);
-
- absl::btree_multimap<int, MovableOnlyInstance> mmap;
- std::pair<const int, MovableOnlyInstance> p4 = {1, MovableOnlyInstance(5)};
- std::pair<const int, MovableOnlyInstance> p5 = {1, MovableOnlyInstance(10)};
- mmap.insert(std::move(p4));
- mmap.insert(mmap.find(1), std::move(p5));
- auto range = mmap.equal_range(1);
- auto it1 = range.first;
- ASSERT_NE(it1, range.second);
- EXPECT_EQ(it1->second.value(), 10);
- ASSERT_NE(++it1, range.second);
- EXPECT_EQ(it1->second.value(), 5);
- EXPECT_EQ(++it1, range.second);
-
- EXPECT_EQ(tracker.copies(), 0);
- EXPECT_EQ(tracker.swaps(), 0);
-}
-
-template <typename Cmp>
-struct CheckedCompareOptedOutCmp : Cmp, BtreeTestOnlyCheckedCompareOptOutBase {
- using Cmp::Cmp;
- CheckedCompareOptedOutCmp() {}
- CheckedCompareOptedOutCmp(Cmp cmp) : Cmp(std::move(cmp)) {} // NOLINT
-};
-
-// A btree set with a specific number of values per node. Opt out of
-// checked_compare so that we can expect exact numbers of comparisons.
-template <typename Key, int TargetValuesPerNode, typename Cmp = std::less<Key>>
-class SizedBtreeSet
- : public btree_set_container<btree<
- set_params<Key, CheckedCompareOptedOutCmp<Cmp>, std::allocator<Key>,
- BtreeNodePeer::GetTargetNodeSize<Key>(TargetValuesPerNode),
- /*Multi=*/false>>> {
- using Base = typename SizedBtreeSet::btree_set_container;
-
- public:
- SizedBtreeSet() {}
- using Base::Base;
-};
-
-template <typename Set>
-void ExpectOperationCounts(const int expected_moves,
- const int expected_comparisons,
- const std::vector<int> &values,
- InstanceTracker *tracker, Set *set) {
- for (const int v : values) set->insert(MovableOnlyInstance(v));
- set->clear();
- EXPECT_EQ(tracker->moves(), expected_moves);
- EXPECT_EQ(tracker->comparisons(), expected_comparisons);
- EXPECT_EQ(tracker->copies(), 0);
- EXPECT_EQ(tracker->swaps(), 0);
- tracker->ResetCopiesMovesSwaps();
-}
-
-// Note: when the values in this test change, it is expected to have an impact
-// on performance.
-TEST(Btree, MovesComparisonsCopiesSwapsTracking) {
- InstanceTracker tracker;
- // Note: this is minimum number of values per node.
- SizedBtreeSet<MovableOnlyInstance, /*TargetValuesPerNode=*/4> set4;
- // Note: this is the default number of values per node for a set of int32s
- // (with 64-bit pointers).
- SizedBtreeSet<MovableOnlyInstance, /*TargetValuesPerNode=*/61> set61;
- SizedBtreeSet<MovableOnlyInstance, /*TargetValuesPerNode=*/100> set100;
-
- // Don't depend on flags for random values because then the expectations will
- // fail if the flags change.
- std::vector<int> values =
- GenerateValuesWithSeed<int>(10000, 1 << 22, /*seed=*/23);
-
- EXPECT_EQ(BtreeNodePeer::GetNumSlotsPerNode<decltype(set4)>(), 4);
- EXPECT_EQ(BtreeNodePeer::GetNumSlotsPerNode<decltype(set61)>(), 61);
- EXPECT_EQ(BtreeNodePeer::GetNumSlotsPerNode<decltype(set100)>(), 100);
- if (sizeof(void *) == 8) {
- EXPECT_EQ(
- BtreeNodePeer::GetNumSlotsPerNode<absl::btree_set<int32_t>>(),
- // When we have generations, there is one fewer slot.
- BtreeNodePeer::UsesGenerations<absl::btree_set<int32_t>>() ? 60 : 61);
- }
-
- // Test key insertion/deletion in random order.
- ExpectOperationCounts(56540, 134212, values, &tracker, &set4);
- ExpectOperationCounts(386718, 129807, values, &tracker, &set61);
- ExpectOperationCounts(586761, 130310, values, &tracker, &set100);
-
- // Test key insertion/deletion in sorted order.
- std::sort(values.begin(), values.end());
- ExpectOperationCounts(24972, 85563, values, &tracker, &set4);
- ExpectOperationCounts(20208, 87757, values, &tracker, &set61);
- ExpectOperationCounts(20124, 96583, values, &tracker, &set100);
-
- // Test key insertion/deletion in reverse sorted order.
- std::reverse(values.begin(), values.end());
- ExpectOperationCounts(54949, 127531, values, &tracker, &set4);
- ExpectOperationCounts(338813, 118266, values, &tracker, &set61);
- ExpectOperationCounts(534529, 125279, values, &tracker, &set100);
-}
-
-struct MovableOnlyInstanceThreeWayCompare {
- absl::weak_ordering operator()(const MovableOnlyInstance &a,
- const MovableOnlyInstance &b) const {
- return a.compare(b);
- }
-};
-
-// Note: when the values in this test change, it is expected to have an impact
-// on performance.
-TEST(Btree, MovesComparisonsCopiesSwapsTrackingThreeWayCompare) {
- InstanceTracker tracker;
- // Note: this is minimum number of values per node.
- SizedBtreeSet<MovableOnlyInstance, /*TargetValuesPerNode=*/4,
- MovableOnlyInstanceThreeWayCompare>
- set4;
- // Note: this is the default number of values per node for a set of int32s
- // (with 64-bit pointers).
- SizedBtreeSet<MovableOnlyInstance, /*TargetValuesPerNode=*/61,
- MovableOnlyInstanceThreeWayCompare>
- set61;
- SizedBtreeSet<MovableOnlyInstance, /*TargetValuesPerNode=*/100,
- MovableOnlyInstanceThreeWayCompare>
- set100;
-
- // Don't depend on flags for random values because then the expectations will
- // fail if the flags change.
- std::vector<int> values =
- GenerateValuesWithSeed<int>(10000, 1 << 22, /*seed=*/23);
-
- EXPECT_EQ(BtreeNodePeer::GetNumSlotsPerNode<decltype(set4)>(), 4);
- EXPECT_EQ(BtreeNodePeer::GetNumSlotsPerNode<decltype(set61)>(), 61);
- EXPECT_EQ(BtreeNodePeer::GetNumSlotsPerNode<decltype(set100)>(), 100);
- if (sizeof(void *) == 8) {
- EXPECT_EQ(
- BtreeNodePeer::GetNumSlotsPerNode<absl::btree_set<int32_t>>(),
- // When we have generations, there is one fewer slot.
- BtreeNodePeer::UsesGenerations<absl::btree_set<int32_t>>() ? 60 : 61);
- }
-
- // Test key insertion/deletion in random order.
- ExpectOperationCounts(56540, 124221, values, &tracker, &set4);
- ExpectOperationCounts(386718, 119816, values, &tracker, &set61);
- ExpectOperationCounts(586761, 120319, values, &tracker, &set100);
-
- // Test key insertion/deletion in sorted order.
- std::sort(values.begin(), values.end());
- ExpectOperationCounts(24972, 85563, values, &tracker, &set4);
- ExpectOperationCounts(20208, 87757, values, &tracker, &set61);
- ExpectOperationCounts(20124, 96583, values, &tracker, &set100);
-
- // Test key insertion/deletion in reverse sorted order.
- std::reverse(values.begin(), values.end());
- ExpectOperationCounts(54949, 117532, values, &tracker, &set4);
- ExpectOperationCounts(338813, 108267, values, &tracker, &set61);
- ExpectOperationCounts(534529, 115280, values, &tracker, &set100);
-}
-
-struct NoDefaultCtor {
- int num;
- explicit NoDefaultCtor(int i) : num(i) {}
-
- friend bool operator<(const NoDefaultCtor &a, const NoDefaultCtor &b) {
- return a.num < b.num;
- }
-};
-
-TEST(Btree, BtreeMapCanHoldNoDefaultCtorTypes) {
- absl::btree_map<NoDefaultCtor, NoDefaultCtor> m;
-
- for (int i = 1; i <= 99; ++i) {
- SCOPED_TRACE(i);
- EXPECT_TRUE(m.emplace(NoDefaultCtor(i), NoDefaultCtor(100 - i)).second);
- }
- EXPECT_FALSE(m.emplace(NoDefaultCtor(78), NoDefaultCtor(0)).second);
-
- auto iter99 = m.find(NoDefaultCtor(99));
- ASSERT_NE(iter99, m.end());
- EXPECT_EQ(iter99->second.num, 1);
-
- auto iter1 = m.find(NoDefaultCtor(1));
- ASSERT_NE(iter1, m.end());
- EXPECT_EQ(iter1->second.num, 99);
-
- auto iter50 = m.find(NoDefaultCtor(50));
- ASSERT_NE(iter50, m.end());
- EXPECT_EQ(iter50->second.num, 50);
-
- auto iter25 = m.find(NoDefaultCtor(25));
- ASSERT_NE(iter25, m.end());
- EXPECT_EQ(iter25->second.num, 75);
-}
-
-TEST(Btree, BtreeMultimapCanHoldNoDefaultCtorTypes) {
- absl::btree_multimap<NoDefaultCtor, NoDefaultCtor> m;
-
- for (int i = 1; i <= 99; ++i) {
- SCOPED_TRACE(i);
- m.emplace(NoDefaultCtor(i), NoDefaultCtor(100 - i));
- }
-
- auto iter99 = m.find(NoDefaultCtor(99));
- ASSERT_NE(iter99, m.end());
- EXPECT_EQ(iter99->second.num, 1);
-
- auto iter1 = m.find(NoDefaultCtor(1));
- ASSERT_NE(iter1, m.end());
- EXPECT_EQ(iter1->second.num, 99);
-
- auto iter50 = m.find(NoDefaultCtor(50));
- ASSERT_NE(iter50, m.end());
- EXPECT_EQ(iter50->second.num, 50);
-
- auto iter25 = m.find(NoDefaultCtor(25));
- ASSERT_NE(iter25, m.end());
- EXPECT_EQ(iter25->second.num, 75);
-}
-
-TEST(Btree, MapAt) {
- absl::btree_map<int, int> map = {{1, 2}, {2, 4}};
- EXPECT_EQ(map.at(1), 2);
- EXPECT_EQ(map.at(2), 4);
- map.at(2) = 8;
- const absl::btree_map<int, int> &const_map = map;
- EXPECT_EQ(const_map.at(1), 2);
- EXPECT_EQ(const_map.at(2), 8);
-#ifdef ABSL_HAVE_EXCEPTIONS
- EXPECT_THROW(map.at(3), std::out_of_range);
-#else
- EXPECT_DEATH_IF_SUPPORTED(map.at(3), "absl::btree_map::at");
-#endif
-}
-
-TEST(Btree, BtreeMultisetEmplace) {
- const int value_to_insert = 123456;
- absl::btree_multiset<int> s;
- auto iter = s.emplace(value_to_insert);
- ASSERT_NE(iter, s.end());
- EXPECT_EQ(*iter, value_to_insert);
- auto iter2 = s.emplace(value_to_insert);
- EXPECT_NE(iter2, iter);
- ASSERT_NE(iter2, s.end());
- EXPECT_EQ(*iter2, value_to_insert);
- auto result = s.equal_range(value_to_insert);
- EXPECT_EQ(std::distance(result.first, result.second), 2);
-}
-
-TEST(Btree, BtreeMultisetEmplaceHint) {
- const int value_to_insert = 123456;
- absl::btree_multiset<int> s;
- auto iter = s.emplace(value_to_insert);
- ASSERT_NE(iter, s.end());
- EXPECT_EQ(*iter, value_to_insert);
- auto emplace_iter = s.emplace_hint(iter, value_to_insert);
- EXPECT_NE(emplace_iter, iter);
- ASSERT_NE(emplace_iter, s.end());
- EXPECT_EQ(*emplace_iter, value_to_insert);
-}
-
-TEST(Btree, BtreeMultimapEmplace) {
- const int key_to_insert = 123456;
- const char value0[] = "a";
- absl::btree_multimap<int, std::string> s;
- auto iter = s.emplace(key_to_insert, value0);
- ASSERT_NE(iter, s.end());
- EXPECT_EQ(iter->first, key_to_insert);
- EXPECT_EQ(iter->second, value0);
- const char value1[] = "b";
- auto iter2 = s.emplace(key_to_insert, value1);
- EXPECT_NE(iter2, iter);
- ASSERT_NE(iter2, s.end());
- EXPECT_EQ(iter2->first, key_to_insert);
- EXPECT_EQ(iter2->second, value1);
- auto result = s.equal_range(key_to_insert);
- EXPECT_EQ(std::distance(result.first, result.second), 2);
-}
-
-TEST(Btree, BtreeMultimapEmplaceHint) {
- const int key_to_insert = 123456;
- const char value0[] = "a";
- absl::btree_multimap<int, std::string> s;
- auto iter = s.emplace(key_to_insert, value0);
- ASSERT_NE(iter, s.end());
- EXPECT_EQ(iter->first, key_to_insert);
- EXPECT_EQ(iter->second, value0);
- const char value1[] = "b";
- auto emplace_iter = s.emplace_hint(iter, key_to_insert, value1);
- EXPECT_NE(emplace_iter, iter);
- ASSERT_NE(emplace_iter, s.end());
- EXPECT_EQ(emplace_iter->first, key_to_insert);
- EXPECT_EQ(emplace_iter->second, value1);
-}
-
-TEST(Btree, ConstIteratorAccessors) {
- absl::btree_set<int> set;
- for (int i = 0; i < 100; ++i) {
- set.insert(i);
- }
-
- auto it = set.cbegin();
- auto r_it = set.crbegin();
- for (int i = 0; i < 100; ++i, ++it, ++r_it) {
- ASSERT_EQ(*it, i);
- ASSERT_EQ(*r_it, 99 - i);
- }
- EXPECT_EQ(it, set.cend());
- EXPECT_EQ(r_it, set.crend());
-}
-
-TEST(Btree, StrSplitCompatible) {
- const absl::btree_set<std::string> split_set = absl::StrSplit("a,b,c", ',');
- const absl::btree_set<std::string> expected_set = {"a", "b", "c"};
-
- EXPECT_EQ(split_set, expected_set);
-}
-
-TEST(Btree, KeyComp) {
- absl::btree_set<int> s;
- EXPECT_TRUE(s.key_comp()(1, 2));
- EXPECT_FALSE(s.key_comp()(2, 2));
- EXPECT_FALSE(s.key_comp()(2, 1));
-
- absl::btree_map<int, int> m1;
- EXPECT_TRUE(m1.key_comp()(1, 2));
- EXPECT_FALSE(m1.key_comp()(2, 2));
- EXPECT_FALSE(m1.key_comp()(2, 1));
-
- // Even though we internally adapt the comparator of `m2` to be three-way and
- // heterogeneous, the comparator we expose through key_comp() is the original
- // unadapted comparator.
- absl::btree_map<std::string, int> m2;
- EXPECT_TRUE(m2.key_comp()("a", "b"));
- EXPECT_FALSE(m2.key_comp()("b", "b"));
- EXPECT_FALSE(m2.key_comp()("b", "a"));
-}
-
-TEST(Btree, ValueComp) {
- absl::btree_set<int> s;
- EXPECT_TRUE(s.value_comp()(1, 2));
- EXPECT_FALSE(s.value_comp()(2, 2));
- EXPECT_FALSE(s.value_comp()(2, 1));
-
- absl::btree_map<int, int> m1;
- EXPECT_TRUE(m1.value_comp()(std::make_pair(1, 0), std::make_pair(2, 0)));
- EXPECT_FALSE(m1.value_comp()(std::make_pair(2, 0), std::make_pair(2, 0)));
- EXPECT_FALSE(m1.value_comp()(std::make_pair(2, 0), std::make_pair(1, 0)));
-
- // Even though we internally adapt the comparator of `m2` to be three-way and
- // heterogeneous, the comparator we expose through value_comp() is based on
- // the original unadapted comparator.
- absl::btree_map<std::string, int> m2;
- EXPECT_TRUE(m2.value_comp()(std::make_pair("a", 0), std::make_pair("b", 0)));
- EXPECT_FALSE(m2.value_comp()(std::make_pair("b", 0), std::make_pair("b", 0)));
- EXPECT_FALSE(m2.value_comp()(std::make_pair("b", 0), std::make_pair("a", 0)));
-}
-
-// Test that we have the protected members from the std::map::value_compare API.
-// See https://en.cppreference.com/w/cpp/container/map/value_compare.
-TEST(Btree, MapValueCompProtected) {
- struct key_compare {
- bool operator()(int l, int r) const { return l < r; }
- int id;
- };
- using value_compare = absl::btree_map<int, int, key_compare>::value_compare;
- struct value_comp_child : public value_compare {
- explicit value_comp_child(key_compare kc) : value_compare(kc) {}
- int GetId() const { return comp.id; }
- };
- value_comp_child c(key_compare{10});
- EXPECT_EQ(c.GetId(), 10);
-}
-
-TEST(Btree, DefaultConstruction) {
- absl::btree_set<int> s;
- absl::btree_map<int, int> m;
- absl::btree_multiset<int> ms;
- absl::btree_multimap<int, int> mm;
-
- EXPECT_TRUE(s.empty());
- EXPECT_TRUE(m.empty());
- EXPECT_TRUE(ms.empty());
- EXPECT_TRUE(mm.empty());
-}
-
-TEST(Btree, SwissTableHashable) {
- static constexpr int kValues = 10000;
- std::vector<int> values(kValues);
- std::iota(values.begin(), values.end(), 0);
- std::vector<std::pair<int, int>> map_values;
- for (int v : values) map_values.emplace_back(v, -v);
-
- using set = absl::btree_set<int>;
- EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly({
- set{},
- set{1},
- set{2},
- set{1, 2},
- set{2, 1},
- set(values.begin(), values.end()),
- set(values.rbegin(), values.rend()),
- }));
-
- using mset = absl::btree_multiset<int>;
- EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly({
- mset{},
- mset{1},
- mset{1, 1},
- mset{2},
- mset{2, 2},
- mset{1, 2},
- mset{1, 1, 2},
- mset{1, 2, 2},
- mset{1, 1, 2, 2},
- mset(values.begin(), values.end()),
- mset(values.rbegin(), values.rend()),
- }));
-
- using map = absl::btree_map<int, int>;
- EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly({
- map{},
- map{{1, 0}},
- map{{1, 1}},
- map{{2, 0}},
- map{{2, 2}},
- map{{1, 0}, {2, 1}},
- map(map_values.begin(), map_values.end()),
- map(map_values.rbegin(), map_values.rend()),
- }));
-
- using mmap = absl::btree_multimap<int, int>;
- EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly({
- mmap{},
- mmap{{1, 0}},
- mmap{{1, 1}},
- mmap{{1, 0}, {1, 1}},
- mmap{{1, 1}, {1, 0}},
- mmap{{2, 0}},
- mmap{{2, 2}},
- mmap{{1, 0}, {2, 1}},
- mmap(map_values.begin(), map_values.end()),
- mmap(map_values.rbegin(), map_values.rend()),
- }));
-}
-
-TEST(Btree, ComparableSet) {
- absl::btree_set<int> s1 = {1, 2};
- absl::btree_set<int> s2 = {2, 3};
- EXPECT_LT(s1, s2);
- EXPECT_LE(s1, s2);
- EXPECT_LE(s1, s1);
- EXPECT_GT(s2, s1);
- EXPECT_GE(s2, s1);
- EXPECT_GE(s1, s1);
-}
-
-TEST(Btree, ComparableSetsDifferentLength) {
- absl::btree_set<int> s1 = {1, 2};
- absl::btree_set<int> s2 = {1, 2, 3};
- EXPECT_LT(s1, s2);
- EXPECT_LE(s1, s2);
- EXPECT_GT(s2, s1);
- EXPECT_GE(s2, s1);
-}
-
-TEST(Btree, ComparableMultiset) {
- absl::btree_multiset<int> s1 = {1, 2};
- absl::btree_multiset<int> s2 = {2, 3};
- EXPECT_LT(s1, s2);
- EXPECT_LE(s1, s2);
- EXPECT_LE(s1, s1);
- EXPECT_GT(s2, s1);
- EXPECT_GE(s2, s1);
- EXPECT_GE(s1, s1);
-}
-
-TEST(Btree, ComparableMap) {
- absl::btree_map<int, int> s1 = {{1, 2}};
- absl::btree_map<int, int> s2 = {{2, 3}};
- EXPECT_LT(s1, s2);
- EXPECT_LE(s1, s2);
- EXPECT_LE(s1, s1);
- EXPECT_GT(s2, s1);
- EXPECT_GE(s2, s1);
- EXPECT_GE(s1, s1);
-}
-
-TEST(Btree, ComparableMultimap) {
- absl::btree_multimap<int, int> s1 = {{1, 2}};
- absl::btree_multimap<int, int> s2 = {{2, 3}};
- EXPECT_LT(s1, s2);
- EXPECT_LE(s1, s2);
- EXPECT_LE(s1, s1);
- EXPECT_GT(s2, s1);
- EXPECT_GE(s2, s1);
- EXPECT_GE(s1, s1);
-}
-
-TEST(Btree, ComparableSetWithCustomComparator) {
- // As specified by
- // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf section
- // [container.requirements.general].12, ordering associative containers always
- // uses default '<' operator
- // - even if otherwise the container uses custom functor.
- absl::btree_set<int, std::greater<int>> s1 = {1, 2};
- absl::btree_set<int, std::greater<int>> s2 = {2, 3};
- EXPECT_LT(s1, s2);
- EXPECT_LE(s1, s2);
- EXPECT_LE(s1, s1);
- EXPECT_GT(s2, s1);
- EXPECT_GE(s2, s1);
- EXPECT_GE(s1, s1);
-}
-
-TEST(Btree, EraseReturnsIterator) {
- absl::btree_set<int> set = {1, 2, 3, 4, 5};
- auto result_it = set.erase(set.begin(), set.find(3));
- EXPECT_EQ(result_it, set.find(3));
- result_it = set.erase(set.find(5));
- EXPECT_EQ(result_it, set.end());
-}
-
-TEST(Btree, ExtractAndInsertNodeHandleSet) {
- absl::btree_set<int> src1 = {1, 2, 3, 4, 5};
- auto nh = src1.extract(src1.find(3));
- EXPECT_THAT(src1, ElementsAre(1, 2, 4, 5));
- absl::btree_set<int> other;
- absl::btree_set<int>::insert_return_type res = other.insert(std::move(nh));
- EXPECT_THAT(other, ElementsAre(3));
- EXPECT_EQ(res.position, other.find(3));
- EXPECT_TRUE(res.inserted);
- EXPECT_TRUE(res.node.empty());
-
- absl::btree_set<int> src2 = {3, 4};
- nh = src2.extract(src2.find(3));
- EXPECT_THAT(src2, ElementsAre(4));
- res = other.insert(std::move(nh));
- EXPECT_THAT(other, ElementsAre(3));
- EXPECT_EQ(res.position, other.find(3));
- EXPECT_FALSE(res.inserted);
- ASSERT_FALSE(res.node.empty());
- EXPECT_EQ(res.node.value(), 3);
-}
-
-template <typename Set>
-void TestExtractWithTrackingForSet() {
- InstanceTracker tracker;
- {
- Set s;
- // Add enough elements to make sure we test internal nodes too.
- const size_t kSize = 1000;
- while (s.size() < kSize) {
- s.insert(MovableOnlyInstance(s.size()));
- }
- for (int i = 0; i < kSize; ++i) {
- // Extract with key
- auto nh = s.extract(MovableOnlyInstance(i));
- EXPECT_EQ(s.size(), kSize - 1);
- EXPECT_EQ(nh.value().value(), i);
- // Insert with node
- s.insert(std::move(nh));
- EXPECT_EQ(s.size(), kSize);
-
- // Extract with iterator
- auto it = s.find(MovableOnlyInstance(i));
- nh = s.extract(it);
- EXPECT_EQ(s.size(), kSize - 1);
- EXPECT_EQ(nh.value().value(), i);
- // Insert with node and hint
- s.insert(s.begin(), std::move(nh));
- EXPECT_EQ(s.size(), kSize);
- }
- }
- EXPECT_EQ(0, tracker.instances());
-}
-
-template <typename Map>
-void TestExtractWithTrackingForMap() {
- InstanceTracker tracker;
- {
- Map m;
- // Add enough elements to make sure we test internal nodes too.
- const size_t kSize = 1000;
- while (m.size() < kSize) {
- m.insert(
- {CopyableMovableInstance(m.size()), MovableOnlyInstance(m.size())});
- }
- for (int i = 0; i < kSize; ++i) {
- // Extract with key
- auto nh = m.extract(CopyableMovableInstance(i));
- EXPECT_EQ(m.size(), kSize - 1);
- EXPECT_EQ(nh.key().value(), i);
- EXPECT_EQ(nh.mapped().value(), i);
- // Insert with node
- m.insert(std::move(nh));
- EXPECT_EQ(m.size(), kSize);
-
- // Extract with iterator
- auto it = m.find(CopyableMovableInstance(i));
- nh = m.extract(it);
- EXPECT_EQ(m.size(), kSize - 1);
- EXPECT_EQ(nh.key().value(), i);
- EXPECT_EQ(nh.mapped().value(), i);
- // Insert with node and hint
- m.insert(m.begin(), std::move(nh));
- EXPECT_EQ(m.size(), kSize);
- }
- }
- EXPECT_EQ(0, tracker.instances());
-}
-
-TEST(Btree, ExtractTracking) {
- TestExtractWithTrackingForSet<absl::btree_set<MovableOnlyInstance>>();
- TestExtractWithTrackingForSet<absl::btree_multiset<MovableOnlyInstance>>();
- TestExtractWithTrackingForMap<
- absl::btree_map<CopyableMovableInstance, MovableOnlyInstance>>();
- TestExtractWithTrackingForMap<
- absl::btree_multimap<CopyableMovableInstance, MovableOnlyInstance>>();
-}
-
-TEST(Btree, ExtractAndInsertNodeHandleMultiSet) {
- absl::btree_multiset<int> src1 = {1, 2, 3, 3, 4, 5};
- auto nh = src1.extract(src1.find(3));
- EXPECT_THAT(src1, ElementsAre(1, 2, 3, 4, 5));
- absl::btree_multiset<int> other;
- auto res = other.insert(std::move(nh));
- EXPECT_THAT(other, ElementsAre(3));
- EXPECT_EQ(res, other.find(3));
-
- absl::btree_multiset<int> src2 = {3, 4};
- nh = src2.extract(src2.find(3));
- EXPECT_THAT(src2, ElementsAre(4));
- res = other.insert(std::move(nh));
- EXPECT_THAT(other, ElementsAre(3, 3));
- EXPECT_EQ(res, ++other.find(3));
-}
-
-TEST(Btree, ExtractAndInsertNodeHandleMap) {
- absl::btree_map<int, int> src1 = {{1, 2}, {3, 4}, {5, 6}};
- auto nh = src1.extract(src1.find(3));
- EXPECT_THAT(src1, ElementsAre(Pair(1, 2), Pair(5, 6)));
- absl::btree_map<int, int> other;
- absl::btree_map<int, int>::insert_return_type res =
- other.insert(std::move(nh));
- EXPECT_THAT(other, ElementsAre(Pair(3, 4)));
- EXPECT_EQ(res.position, other.find(3));
- EXPECT_TRUE(res.inserted);
- EXPECT_TRUE(res.node.empty());
-
- absl::btree_map<int, int> src2 = {{3, 6}};
- nh = src2.extract(src2.find(3));
- EXPECT_TRUE(src2.empty());
- res = other.insert(std::move(nh));
- EXPECT_THAT(other, ElementsAre(Pair(3, 4)));
- EXPECT_EQ(res.position, other.find(3));
- EXPECT_FALSE(res.inserted);
- ASSERT_FALSE(res.node.empty());
- EXPECT_EQ(res.node.key(), 3);
- EXPECT_EQ(res.node.mapped(), 6);
-}
-
-TEST(Btree, ExtractAndInsertNodeHandleMultiMap) {
- absl::btree_multimap<int, int> src1 = {{1, 2}, {3, 4}, {5, 6}};
- auto nh = src1.extract(src1.find(3));
- EXPECT_THAT(src1, ElementsAre(Pair(1, 2), Pair(5, 6)));
- absl::btree_multimap<int, int> other;
- auto res = other.insert(std::move(nh));
- EXPECT_THAT(other, ElementsAre(Pair(3, 4)));
- EXPECT_EQ(res, other.find(3));
-
- absl::btree_multimap<int, int> src2 = {{3, 6}};
- nh = src2.extract(src2.find(3));
- EXPECT_TRUE(src2.empty());
- res = other.insert(std::move(nh));
- EXPECT_THAT(other, ElementsAre(Pair(3, 4), Pair(3, 6)));
- EXPECT_EQ(res, ++other.begin());
-}
-
-TEST(Btree, ExtractMultiMapEquivalentKeys) {
- // Note: using string keys means a three-way comparator.
- absl::btree_multimap<std::string, int> map;
- for (int i = 0; i < 100; ++i) {
- for (int j = 0; j < 100; ++j) {
- map.insert({absl::StrCat(i), j});
- }
- }
-
- for (int i = 0; i < 100; ++i) {
- const std::string key = absl::StrCat(i);
- auto node_handle = map.extract(key);
- EXPECT_EQ(node_handle.key(), key);
- EXPECT_EQ(node_handle.mapped(), 0) << i;
- }
-
- for (int i = 0; i < 100; ++i) {
- const std::string key = absl::StrCat(i);
- auto node_handle = map.extract(key);
- EXPECT_EQ(node_handle.key(), key);
- EXPECT_EQ(node_handle.mapped(), 1) << i;
- }
-}
-
-// For multisets, insert with hint also affects correctness because we need to
-// insert immediately before the hint if possible.
-struct InsertMultiHintData {
- int key;
- int not_key;
- bool operator==(const InsertMultiHintData other) const {
- return key == other.key && not_key == other.not_key;
- }
-};
-
-struct InsertMultiHintDataKeyCompare {
- using is_transparent = void;
- bool operator()(const InsertMultiHintData a,
- const InsertMultiHintData b) const {
- return a.key < b.key;
- }
- bool operator()(const int a, const InsertMultiHintData b) const {
- return a < b.key;
- }
- bool operator()(const InsertMultiHintData a, const int b) const {
- return a.key < b;
- }
-};
-
-TEST(Btree, InsertHintNodeHandle) {
- // For unique sets, insert with hint is just a performance optimization.
- // Test that insert works correctly when the hint is right or wrong.
- {
- absl::btree_set<int> src = {1, 2, 3, 4, 5};
- auto nh = src.extract(src.find(3));
- EXPECT_THAT(src, ElementsAre(1, 2, 4, 5));
- absl::btree_set<int> other = {0, 100};
- // Test a correct hint.
- auto it = other.insert(other.lower_bound(3), std::move(nh));
- EXPECT_THAT(other, ElementsAre(0, 3, 100));
- EXPECT_EQ(it, other.find(3));
-
- nh = src.extract(src.find(5));
- // Test an incorrect hint.
- it = other.insert(other.end(), std::move(nh));
- EXPECT_THAT(other, ElementsAre(0, 3, 5, 100));
- EXPECT_EQ(it, other.find(5));
- }
-
- absl::btree_multiset<InsertMultiHintData, InsertMultiHintDataKeyCompare> src =
- {{1, 2}, {3, 4}, {3, 5}};
- auto nh = src.extract(src.lower_bound(3));
- EXPECT_EQ(nh.value(), (InsertMultiHintData{3, 4}));
- absl::btree_multiset<InsertMultiHintData, InsertMultiHintDataKeyCompare>
- other = {{3, 1}, {3, 2}, {3, 3}};
- auto it = other.insert(--other.end(), std::move(nh));
- EXPECT_THAT(
- other, ElementsAre(InsertMultiHintData{3, 1}, InsertMultiHintData{3, 2},
- InsertMultiHintData{3, 4}, InsertMultiHintData{3, 3}));
- EXPECT_EQ(it, --(--other.end()));
-
- nh = src.extract(src.find(3));
- EXPECT_EQ(nh.value(), (InsertMultiHintData{3, 5}));
- it = other.insert(other.begin(), std::move(nh));
- EXPECT_THAT(other,
- ElementsAre(InsertMultiHintData{3, 5}, InsertMultiHintData{3, 1},
- InsertMultiHintData{3, 2}, InsertMultiHintData{3, 4},
- InsertMultiHintData{3, 3}));
- EXPECT_EQ(it, other.begin());
-}
-
-struct IntCompareToCmp {
- absl::weak_ordering operator()(int a, int b) const {
- if (a < b) return absl::weak_ordering::less;
- if (a > b) return absl::weak_ordering::greater;
- return absl::weak_ordering::equivalent;
- }
-};
-
-TEST(Btree, MergeIntoUniqueContainers) {
- absl::btree_set<int, IntCompareToCmp> src1 = {1, 2, 3};
- absl::btree_multiset<int> src2 = {3, 4, 4, 5};
- absl::btree_set<int> dst;
-
- dst.merge(src1);
- EXPECT_TRUE(src1.empty());
- EXPECT_THAT(dst, ElementsAre(1, 2, 3));
- dst.merge(src2);
- EXPECT_THAT(src2, ElementsAre(3, 4));
- EXPECT_THAT(dst, ElementsAre(1, 2, 3, 4, 5));
-}
-
-TEST(Btree, MergeIntoUniqueContainersWithCompareTo) {
- absl::btree_set<int, IntCompareToCmp> src1 = {1, 2, 3};
- absl::btree_multiset<int> src2 = {3, 4, 4, 5};
- absl::btree_set<int, IntCompareToCmp> dst;
-
- dst.merge(src1);
- EXPECT_TRUE(src1.empty());
- EXPECT_THAT(dst, ElementsAre(1, 2, 3));
- dst.merge(src2);
- EXPECT_THAT(src2, ElementsAre(3, 4));
- EXPECT_THAT(dst, ElementsAre(1, 2, 3, 4, 5));
-}
-
-TEST(Btree, MergeIntoMultiContainers) {
- absl::btree_set<int, IntCompareToCmp> src1 = {1, 2, 3};
- absl::btree_multiset<int> src2 = {3, 4, 4, 5};
- absl::btree_multiset<int> dst;
-
- dst.merge(src1);
- EXPECT_TRUE(src1.empty());
- EXPECT_THAT(dst, ElementsAre(1, 2, 3));
- dst.merge(src2);
- EXPECT_TRUE(src2.empty());
- EXPECT_THAT(dst, ElementsAre(1, 2, 3, 3, 4, 4, 5));
-}
-
-TEST(Btree, MergeIntoMultiContainersWithCompareTo) {
- absl::btree_set<int, IntCompareToCmp> src1 = {1, 2, 3};
- absl::btree_multiset<int> src2 = {3, 4, 4, 5};
- absl::btree_multiset<int, IntCompareToCmp> dst;
-
- dst.merge(src1);
- EXPECT_TRUE(src1.empty());
- EXPECT_THAT(dst, ElementsAre(1, 2, 3));
- dst.merge(src2);
- EXPECT_TRUE(src2.empty());
- EXPECT_THAT(dst, ElementsAre(1, 2, 3, 3, 4, 4, 5));
-}
-
-TEST(Btree, MergeIntoMultiMapsWithDifferentComparators) {
- absl::btree_map<int, int, IntCompareToCmp> src1 = {{1, 1}, {2, 2}, {3, 3}};
- absl::btree_multimap<int, int, std::greater<int>> src2 = {
- {5, 5}, {4, 1}, {4, 4}, {3, 2}};
- absl::btree_multimap<int, int> dst;
-
- dst.merge(src1);
- EXPECT_TRUE(src1.empty());
- EXPECT_THAT(dst, ElementsAre(Pair(1, 1), Pair(2, 2), Pair(3, 3)));
- dst.merge(src2);
- EXPECT_TRUE(src2.empty());
- EXPECT_THAT(dst, ElementsAre(Pair(1, 1), Pair(2, 2), Pair(3, 3), Pair(3, 2),
- Pair(4, 1), Pair(4, 4), Pair(5, 5)));
-}
-
-TEST(Btree, MergeIntoSetMovableOnly) {
- absl::btree_set<MovableOnlyInstance> src;
- src.insert(MovableOnlyInstance(1));
- absl::btree_multiset<MovableOnlyInstance> dst1;
- dst1.insert(MovableOnlyInstance(2));
- absl::btree_set<MovableOnlyInstance> dst2;
-
- // Test merge into multiset.
- dst1.merge(src);
-
- EXPECT_TRUE(src.empty());
- // ElementsAre/ElementsAreArray don't work with move-only types.
- ASSERT_THAT(dst1, SizeIs(2));
- EXPECT_EQ(*dst1.begin(), MovableOnlyInstance(1));
- EXPECT_EQ(*std::next(dst1.begin()), MovableOnlyInstance(2));
-
- // Test merge into set.
- dst2.merge(dst1);
-
- EXPECT_TRUE(dst1.empty());
- ASSERT_THAT(dst2, SizeIs(2));
- EXPECT_EQ(*dst2.begin(), MovableOnlyInstance(1));
- EXPECT_EQ(*std::next(dst2.begin()), MovableOnlyInstance(2));
-}
-
-struct KeyCompareToWeakOrdering {
- template <typename T>
- absl::weak_ordering operator()(const T &a, const T &b) const {
- return a < b ? absl::weak_ordering::less
- : a == b ? absl::weak_ordering::equivalent
- : absl::weak_ordering::greater;
- }
-};
-
-struct KeyCompareToStrongOrdering {
- template <typename T>
- absl::strong_ordering operator()(const T &a, const T &b) const {
- return a < b ? absl::strong_ordering::less
- : a == b ? absl::strong_ordering::equal
- : absl::strong_ordering::greater;
- }
-};
-
-TEST(Btree, UserProvidedKeyCompareToComparators) {
- absl::btree_set<int, KeyCompareToWeakOrdering> weak_set = {1, 2, 3};
- EXPECT_TRUE(weak_set.contains(2));
- EXPECT_FALSE(weak_set.contains(4));
-
- absl::btree_set<int, KeyCompareToStrongOrdering> strong_set = {1, 2, 3};
- EXPECT_TRUE(strong_set.contains(2));
- EXPECT_FALSE(strong_set.contains(4));
-}
-
-TEST(Btree, TryEmplaceBasicTest) {
- absl::btree_map<int, std::string> m;
-
- // Should construct a string from the literal.
- m.try_emplace(1, "one");
- EXPECT_EQ(1, m.size());
-
- // Try other string constructors and const lvalue key.
- const int key(42);
- m.try_emplace(key, 3, 'a');
- m.try_emplace(2, std::string("two"));
-
- EXPECT_TRUE(std::is_sorted(m.begin(), m.end()));
- EXPECT_THAT(m, ElementsAreArray(std::vector<std::pair<int, std::string>>{
- {1, "one"}, {2, "two"}, {42, "aaa"}}));
-}
-
-TEST(Btree, TryEmplaceWithHintWorks) {
- // Use a counting comparator here to verify that hint is used.
- int calls = 0;
- auto cmp = [&calls](int x, int y) {
- ++calls;
- return x < y;
- };
- using Cmp = decltype(cmp);
-
- // Use a map that is opted out of key_compare being adapted so we can expect
- // strict comparison call limits.
- absl::btree_map<int, int, CheckedCompareOptedOutCmp<Cmp>> m(cmp);
- for (int i = 0; i < 128; ++i) {
- m.emplace(i, i);
- }
-
- // Sanity check for the comparator
- calls = 0;
- m.emplace(127, 127);
- EXPECT_GE(calls, 4);
-
- // Try with begin hint:
- calls = 0;
- auto it = m.try_emplace(m.begin(), -1, -1);
- EXPECT_EQ(129, m.size());
- EXPECT_EQ(it, m.begin());
- EXPECT_LE(calls, 2);
-
- // Try with end hint:
- calls = 0;
- std::pair<int, int> pair1024 = {1024, 1024};
- it = m.try_emplace(m.end(), pair1024.first, pair1024.second);
- EXPECT_EQ(130, m.size());
- EXPECT_EQ(it, --m.end());
- EXPECT_LE(calls, 2);
-
- // Try value already present, bad hint; ensure no duplicate added:
- calls = 0;
- it = m.try_emplace(m.end(), 16, 17);
- EXPECT_EQ(130, m.size());
- EXPECT_GE(calls, 4);
- EXPECT_EQ(it, m.find(16));
-
- // Try value already present, hint points directly to it:
- calls = 0;
- it = m.try_emplace(it, 16, 17);
- EXPECT_EQ(130, m.size());
- EXPECT_LE(calls, 2);
- EXPECT_EQ(it, m.find(16));
-
- m.erase(2);
- EXPECT_EQ(129, m.size());
- auto hint = m.find(3);
- // Try emplace in the middle of two other elements.
- calls = 0;
- m.try_emplace(hint, 2, 2);
- EXPECT_EQ(130, m.size());
- EXPECT_LE(calls, 2);
-
- EXPECT_TRUE(std::is_sorted(m.begin(), m.end()));
-}
-
-TEST(Btree, TryEmplaceWithBadHint) {
- absl::btree_map<int, int> m = {{1, 1}, {9, 9}};
-
- // Bad hint (too small), should still emplace:
- auto it = m.try_emplace(m.begin(), 2, 2);
- EXPECT_EQ(it, ++m.begin());
- EXPECT_THAT(m, ElementsAreArray(
- std::vector<std::pair<int, int>>{{1, 1}, {2, 2}, {9, 9}}));
-
- // Bad hint, too large this time:
- it = m.try_emplace(++(++m.begin()), 0, 0);
- EXPECT_EQ(it, m.begin());
- EXPECT_THAT(m, ElementsAreArray(std::vector<std::pair<int, int>>{
- {0, 0}, {1, 1}, {2, 2}, {9, 9}}));
-}
-
-TEST(Btree, TryEmplaceMaintainsSortedOrder) {
- absl::btree_map<int, std::string> m;
- std::pair<int, std::string> pair5 = {5, "five"};
-
- // Test both lvalue & rvalue emplace.
- m.try_emplace(10, "ten");
- m.try_emplace(pair5.first, pair5.second);
- EXPECT_EQ(2, m.size());
- EXPECT_TRUE(std::is_sorted(m.begin(), m.end()));
-
- int int100{100};
- m.try_emplace(int100, "hundred");
- m.try_emplace(1, "one");
- EXPECT_EQ(4, m.size());
- EXPECT_TRUE(std::is_sorted(m.begin(), m.end()));
-}
-
-TEST(Btree, TryEmplaceWithHintAndNoValueArgsWorks) {
- absl::btree_map<int, int> m;
- m.try_emplace(m.end(), 1);
- EXPECT_EQ(0, m[1]);
-}
-
-TEST(Btree, TryEmplaceWithHintAndMultipleValueArgsWorks) {
- absl::btree_map<int, std::string> m;
- m.try_emplace(m.end(), 1, 10, 'a');
- EXPECT_EQ(std::string(10, 'a'), m[1]);
-}
-
-TEST(Btree, MoveAssignmentAllocatorPropagation) {
- InstanceTracker tracker;
-
- int64_t bytes1 = 0, bytes2 = 0;
- PropagatingCountingAlloc<MovableOnlyInstance> allocator1(&bytes1);
- PropagatingCountingAlloc<MovableOnlyInstance> allocator2(&bytes2);
- std::less<MovableOnlyInstance> cmp;
-
- // Test propagating allocator_type.
- {
- absl::btree_set<MovableOnlyInstance, std::less<MovableOnlyInstance>,
- PropagatingCountingAlloc<MovableOnlyInstance>>
- set1(cmp, allocator1), set2(cmp, allocator2);
-
- for (int i = 0; i < 100; ++i) set1.insert(MovableOnlyInstance(i));
-
- tracker.ResetCopiesMovesSwaps();
- set2 = std::move(set1);
- EXPECT_EQ(tracker.moves(), 0);
- }
- // Test non-propagating allocator_type with equal allocators.
- {
- absl::btree_set<MovableOnlyInstance, std::less<MovableOnlyInstance>,
- CountingAllocator<MovableOnlyInstance>>
- set1(cmp, allocator1), set2(cmp, allocator1);
-
- for (int i = 0; i < 100; ++i) set1.insert(MovableOnlyInstance(i));
-
- tracker.ResetCopiesMovesSwaps();
- set2 = std::move(set1);
- EXPECT_EQ(tracker.moves(), 0);
- }
- // Test non-propagating allocator_type with different allocators.
- {
- absl::btree_set<MovableOnlyInstance, std::less<MovableOnlyInstance>,
- CountingAllocator<MovableOnlyInstance>>
- set1(cmp, allocator1), set2(cmp, allocator2);
-
- for (int i = 0; i < 100; ++i) set1.insert(MovableOnlyInstance(i));
-
- tracker.ResetCopiesMovesSwaps();
- set2 = std::move(set1);
- EXPECT_GE(tracker.moves(), 100);
- }
-}
-
-TEST(Btree, EmptyTree) {
- absl::btree_set<int> s;
- EXPECT_TRUE(s.empty());
- EXPECT_EQ(s.size(), 0);
- EXPECT_GT(s.max_size(), 0);
-}
-
-bool IsEven(int k) { return k % 2 == 0; }
-
-TEST(Btree, EraseIf) {
- // Test that erase_if works with all the container types and supports lambdas.
- {
- absl::btree_set<int> s = {1, 3, 5, 6, 100};
- EXPECT_EQ(erase_if(s, [](int k) { return k > 3; }), 3);
- EXPECT_THAT(s, ElementsAre(1, 3));
- }
- {
- absl::btree_multiset<int> s = {1, 3, 3, 5, 6, 6, 100};
- EXPECT_EQ(erase_if(s, [](int k) { return k <= 3; }), 3);
- EXPECT_THAT(s, ElementsAre(5, 6, 6, 100));
- }
- {
- absl::btree_map<int, int> m = {{1, 1}, {3, 3}, {6, 6}, {100, 100}};
- EXPECT_EQ(
- erase_if(m, [](std::pair<const int, int> kv) { return kv.first > 3; }),
- 2);
- EXPECT_THAT(m, ElementsAre(Pair(1, 1), Pair(3, 3)));
- }
- {
- absl::btree_multimap<int, int> m = {{1, 1}, {3, 3}, {3, 6},
- {6, 6}, {6, 7}, {100, 6}};
- EXPECT_EQ(
- erase_if(m,
- [](std::pair<const int, int> kv) { return kv.second == 6; }),
- 3);
- EXPECT_THAT(m, ElementsAre(Pair(1, 1), Pair(3, 3), Pair(6, 7)));
- }
- // Test that erasing all elements from a large set works and test support for
- // function pointers.
- {
- absl::btree_set<int> s;
- for (int i = 0; i < 1000; ++i) s.insert(2 * i);
- EXPECT_EQ(erase_if(s, IsEven), 1000);
- EXPECT_THAT(s, IsEmpty());
- }
- // Test that erase_if supports other format of function pointers.
- {
- absl::btree_set<int> s = {1, 3, 5, 6, 100};
- EXPECT_EQ(erase_if(s, &IsEven), 2);
- EXPECT_THAT(s, ElementsAre(1, 3, 5));
- }
- // Test that erase_if invokes the predicate once per element.
- {
- absl::btree_set<int> s;
- for (int i = 0; i < 1000; ++i) s.insert(i);
- int pred_calls = 0;
- EXPECT_EQ(erase_if(s,
- [&pred_calls](int k) {
- ++pred_calls;
- return k % 2;
- }),
- 500);
- EXPECT_THAT(s, SizeIs(500));
- EXPECT_EQ(pred_calls, 1000);
- }
-}
-
-TEST(Btree, InsertOrAssign) {
- absl::btree_map<int, int> m = {{1, 1}, {3, 3}};
- using value_type = typename decltype(m)::value_type;
-
- auto ret = m.insert_or_assign(4, 4);
- EXPECT_EQ(*ret.first, value_type(4, 4));
- EXPECT_TRUE(ret.second);
- ret = m.insert_or_assign(3, 100);
- EXPECT_EQ(*ret.first, value_type(3, 100));
- EXPECT_FALSE(ret.second);
-
- auto hint_ret = m.insert_or_assign(ret.first, 3, 200);
- EXPECT_EQ(*hint_ret, value_type(3, 200));
- hint_ret = m.insert_or_assign(m.find(1), 0, 1);
- EXPECT_EQ(*hint_ret, value_type(0, 1));
- // Test with bad hint.
- hint_ret = m.insert_or_assign(m.end(), -1, 1);
- EXPECT_EQ(*hint_ret, value_type(-1, 1));
-
- EXPECT_THAT(m, ElementsAre(Pair(-1, 1), Pair(0, 1), Pair(1, 1), Pair(3, 200),
- Pair(4, 4)));
-}
-
-TEST(Btree, InsertOrAssignMovableOnly) {
- absl::btree_map<int, MovableOnlyInstance> m;
- using value_type = typename decltype(m)::value_type;
-
- auto ret = m.insert_or_assign(4, MovableOnlyInstance(4));
- EXPECT_EQ(*ret.first, value_type(4, MovableOnlyInstance(4)));
- EXPECT_TRUE(ret.second);
- ret = m.insert_or_assign(4, MovableOnlyInstance(100));
- EXPECT_EQ(*ret.first, value_type(4, MovableOnlyInstance(100)));
- EXPECT_FALSE(ret.second);
-
- auto hint_ret = m.insert_or_assign(ret.first, 3, MovableOnlyInstance(200));
- EXPECT_EQ(*hint_ret, value_type(3, MovableOnlyInstance(200)));
-
- EXPECT_EQ(m.size(), 2);
-}
-
-TEST(Btree, BitfieldArgument) {
- union {
- int n : 1;
- };
- n = 0;
- absl::btree_map<int, int> m;
- m.erase(n);
- m.count(n);
- m.find(n);
- m.contains(n);
- m.equal_range(n);
- m.insert_or_assign(n, n);
- m.insert_or_assign(m.end(), n, n);
- m.try_emplace(n);
- m.try_emplace(m.end(), n);
- m.at(n);
- m[n];
-}
-
-TEST(Btree, SetRangeConstructorAndInsertSupportExplicitConversionComparable) {
- const absl::string_view names[] = {"n1", "n2"};
-
- absl::btree_set<std::string> name_set1{std::begin(names), std::end(names)};
- EXPECT_THAT(name_set1, ElementsAreArray(names));
-
- absl::btree_set<std::string> name_set2;
- name_set2.insert(std::begin(names), std::end(names));
- EXPECT_THAT(name_set2, ElementsAreArray(names));
-}
-
-// A type that is explicitly convertible from int and counts constructor calls.
-struct ConstructorCounted {
- explicit ConstructorCounted(int i) : i(i) { ++constructor_calls; }
- bool operator==(int other) const { return i == other; }
-
- int i;
- static int constructor_calls;
-};
-int ConstructorCounted::constructor_calls = 0;
-
-struct ConstructorCountedCompare {
- bool operator()(int a, const ConstructorCounted &b) const { return a < b.i; }
- bool operator()(const ConstructorCounted &a, int b) const { return a.i < b; }
- bool operator()(const ConstructorCounted &a,
- const ConstructorCounted &b) const {
- return a.i < b.i;
- }
- using is_transparent = void;
-};
-
-TEST(Btree,
- SetRangeConstructorAndInsertExplicitConvComparableLimitConstruction) {
- const int i[] = {0, 1, 1};
- ConstructorCounted::constructor_calls = 0;
-
- absl::btree_set<ConstructorCounted, ConstructorCountedCompare> set{
- std::begin(i), std::end(i)};
- EXPECT_THAT(set, ElementsAre(0, 1));
- EXPECT_EQ(ConstructorCounted::constructor_calls, 2);
-
- set.insert(std::begin(i), std::end(i));
- EXPECT_THAT(set, ElementsAre(0, 1));
- EXPECT_EQ(ConstructorCounted::constructor_calls, 2);
-}
-
-TEST(Btree,
- SetRangeConstructorAndInsertSupportExplicitConversionNonComparable) {
- const int i[] = {0, 1};
-
- absl::btree_set<std::vector<void *>> s1{std::begin(i), std::end(i)};
- EXPECT_THAT(s1, ElementsAre(IsEmpty(), ElementsAre(IsNull())));
-
- absl::btree_set<std::vector<void *>> s2;
- s2.insert(std::begin(i), std::end(i));
- EXPECT_THAT(s2, ElementsAre(IsEmpty(), ElementsAre(IsNull())));
-}
-
-// libstdc++ included with GCC 4.9 has a bug in the std::pair constructors that
-// prevents explicit conversions between pair types.
-// We only run this test for the libstdc++ from GCC 7 or newer because we can't
-// reliably check the libstdc++ version prior to that release.
-#if !defined(__GLIBCXX__) || \
- (defined(_GLIBCXX_RELEASE) && _GLIBCXX_RELEASE >= 7)
-TEST(Btree, MapRangeConstructorAndInsertSupportExplicitConversionComparable) {
- const std::pair<absl::string_view, int> names[] = {{"n1", 1}, {"n2", 2}};
-
- absl::btree_map<std::string, int> name_map1{std::begin(names),
- std::end(names)};
- EXPECT_THAT(name_map1, ElementsAre(Pair("n1", 1), Pair("n2", 2)));
-
- absl::btree_map<std::string, int> name_map2;
- name_map2.insert(std::begin(names), std::end(names));
- EXPECT_THAT(name_map2, ElementsAre(Pair("n1", 1), Pair("n2", 2)));
-}
-
-TEST(Btree,
- MapRangeConstructorAndInsertExplicitConvComparableLimitConstruction) {
- const std::pair<int, int> i[] = {{0, 1}, {1, 2}, {1, 3}};
- ConstructorCounted::constructor_calls = 0;
-
- absl::btree_map<ConstructorCounted, int, ConstructorCountedCompare> map{
- std::begin(i), std::end(i)};
- EXPECT_THAT(map, ElementsAre(Pair(0, 1), Pair(1, 2)));
- EXPECT_EQ(ConstructorCounted::constructor_calls, 2);
-
- map.insert(std::begin(i), std::end(i));
- EXPECT_THAT(map, ElementsAre(Pair(0, 1), Pair(1, 2)));
- EXPECT_EQ(ConstructorCounted::constructor_calls, 2);
-}
-
-TEST(Btree,
- MapRangeConstructorAndInsertSupportExplicitConversionNonComparable) {
- const std::pair<int, int> i[] = {{0, 1}, {1, 2}};
-
- absl::btree_map<std::vector<void *>, int> m1{std::begin(i), std::end(i)};
- EXPECT_THAT(m1,
- ElementsAre(Pair(IsEmpty(), 1), Pair(ElementsAre(IsNull()), 2)));
-
- absl::btree_map<std::vector<void *>, int> m2;
- m2.insert(std::begin(i), std::end(i));
- EXPECT_THAT(m2,
- ElementsAre(Pair(IsEmpty(), 1), Pair(ElementsAre(IsNull()), 2)));
-}
-
-TEST(Btree, HeterogeneousTryEmplace) {
- absl::btree_map<std::string, int> m;
- std::string s = "key";
- absl::string_view sv = s;
- m.try_emplace(sv, 1);
- EXPECT_EQ(m[s], 1);
-
- m.try_emplace(m.end(), sv, 2);
- EXPECT_EQ(m[s], 1);
-}
-
-TEST(Btree, HeterogeneousOperatorMapped) {
- absl::btree_map<std::string, int> m;
- std::string s = "key";
- absl::string_view sv = s;
- m[sv] = 1;
- EXPECT_EQ(m[s], 1);
-
- m[sv] = 2;
- EXPECT_EQ(m[s], 2);
-}
-
-TEST(Btree, HeterogeneousInsertOrAssign) {
- absl::btree_map<std::string, int> m;
- std::string s = "key";
- absl::string_view sv = s;
- m.insert_or_assign(sv, 1);
- EXPECT_EQ(m[s], 1);
-
- m.insert_or_assign(m.end(), sv, 2);
- EXPECT_EQ(m[s], 2);
-}
-#endif
-
-// This test requires std::launder for mutable key access in node handles.
-#if defined(__cpp_lib_launder) && __cpp_lib_launder >= 201606
-TEST(Btree, NodeHandleMutableKeyAccess) {
- {
- absl::btree_map<std::string, std::string> map;
-
- map["key1"] = "mapped";
-
- auto nh = map.extract(map.begin());
- nh.key().resize(3);
- map.insert(std::move(nh));
-
- EXPECT_THAT(map, ElementsAre(Pair("key", "mapped")));
- }
- // Also for multimap.
- {
- absl::btree_multimap<std::string, std::string> map;
-
- map.emplace("key1", "mapped");
-
- auto nh = map.extract(map.begin());
- nh.key().resize(3);
- map.insert(std::move(nh));
-
- EXPECT_THAT(map, ElementsAre(Pair("key", "mapped")));
- }
-}
-#endif
-
-struct MultiKey {
- int i1;
- int i2;
-};
-
-bool operator==(const MultiKey a, const MultiKey b) {
- return a.i1 == b.i1 && a.i2 == b.i2;
-}
-
-// A heterogeneous comparator that has different equivalence classes for
-// different lookup types.
-struct MultiKeyComp {
- using is_transparent = void;
- bool operator()(const MultiKey a, const MultiKey b) const {
- if (a.i1 != b.i1) return a.i1 < b.i1;
- return a.i2 < b.i2;
- }
- bool operator()(const int a, const MultiKey b) const { return a < b.i1; }
- bool operator()(const MultiKey a, const int b) const { return a.i1 < b; }
-};
-
-// A heterogeneous, three-way comparator that has different equivalence classes
-// for different lookup types.
-struct MultiKeyThreeWayComp {
- using is_transparent = void;
- absl::weak_ordering operator()(const MultiKey a, const MultiKey b) const {
- if (a.i1 < b.i1) return absl::weak_ordering::less;
- if (a.i1 > b.i1) return absl::weak_ordering::greater;
- if (a.i2 < b.i2) return absl::weak_ordering::less;
- if (a.i2 > b.i2) return absl::weak_ordering::greater;
- return absl::weak_ordering::equivalent;
- }
- absl::weak_ordering operator()(const int a, const MultiKey b) const {
- if (a < b.i1) return absl::weak_ordering::less;
- if (a > b.i1) return absl::weak_ordering::greater;
- return absl::weak_ordering::equivalent;
- }
- absl::weak_ordering operator()(const MultiKey a, const int b) const {
- if (a.i1 < b) return absl::weak_ordering::less;
- if (a.i1 > b) return absl::weak_ordering::greater;
- return absl::weak_ordering::equivalent;
- }
-};
-
-template <typename Compare>
-class BtreeMultiKeyTest : public ::testing::Test {};
-using MultiKeyComps = ::testing::Types<MultiKeyComp, MultiKeyThreeWayComp>;
-TYPED_TEST_SUITE(BtreeMultiKeyTest, MultiKeyComps);
-
-TYPED_TEST(BtreeMultiKeyTest, EqualRange) {
- absl::btree_set<MultiKey, TypeParam> set;
- for (int i = 0; i < 100; ++i) {
- for (int j = 0; j < 100; ++j) {
- set.insert({i, j});
- }
- }
-
- for (int i = 0; i < 100; ++i) {
- auto equal_range = set.equal_range(i);
- EXPECT_EQ(equal_range.first->i1, i);
- EXPECT_EQ(equal_range.first->i2, 0) << i;
- EXPECT_EQ(std::distance(equal_range.first, equal_range.second), 100) << i;
- }
-}
-
-TYPED_TEST(BtreeMultiKeyTest, Extract) {
- absl::btree_set<MultiKey, TypeParam> set;
- for (int i = 0; i < 100; ++i) {
- for (int j = 0; j < 100; ++j) {
- set.insert({i, j});
- }
- }
-
- for (int i = 0; i < 100; ++i) {
- auto node_handle = set.extract(i);
- EXPECT_EQ(node_handle.value().i1, i);
- EXPECT_EQ(node_handle.value().i2, 0) << i;
- }
-
- for (int i = 0; i < 100; ++i) {
- auto node_handle = set.extract(i);
- EXPECT_EQ(node_handle.value().i1, i);
- EXPECT_EQ(node_handle.value().i2, 1) << i;
- }
-}
-
-TYPED_TEST(BtreeMultiKeyTest, Erase) {
- absl::btree_set<MultiKey, TypeParam> set = {
- {1, 1}, {2, 1}, {2, 2}, {3, 1}};
- EXPECT_EQ(set.erase(2), 2);
- EXPECT_THAT(set, ElementsAre(MultiKey{1, 1}, MultiKey{3, 1}));
-}
-
-TYPED_TEST(BtreeMultiKeyTest, Count) {
- const absl::btree_set<MultiKey, TypeParam> set = {
- {1, 1}, {2, 1}, {2, 2}, {3, 1}};
- EXPECT_EQ(set.count(2), 2);
-}
-
-TEST(Btree, AllocConstructor) {
- using Alloc = CountingAllocator<int>;
- using Set = absl::btree_set<int, std::less<int>, Alloc>;
- int64_t bytes_used = 0;
- Alloc alloc(&bytes_used);
- Set set(alloc);
-
- set.insert({1, 2, 3});
-
- EXPECT_THAT(set, ElementsAre(1, 2, 3));
- EXPECT_GT(bytes_used, set.size() * sizeof(int));
-}
-
-TEST(Btree, AllocInitializerListConstructor) {
- using Alloc = CountingAllocator<int>;
- using Set = absl::btree_set<int, std::less<int>, Alloc>;
- int64_t bytes_used = 0;
- Alloc alloc(&bytes_used);
- Set set({1, 2, 3}, alloc);
-
- EXPECT_THAT(set, ElementsAre(1, 2, 3));
- EXPECT_GT(bytes_used, set.size() * sizeof(int));
-}
-
-TEST(Btree, AllocRangeConstructor) {
- using Alloc = CountingAllocator<int>;
- using Set = absl::btree_set<int, std::less<int>, Alloc>;
- int64_t bytes_used = 0;
- Alloc alloc(&bytes_used);
- std::vector<int> v = {1, 2, 3};
- Set set(v.begin(), v.end(), alloc);
-
- EXPECT_THAT(set, ElementsAre(1, 2, 3));
- EXPECT_GT(bytes_used, set.size() * sizeof(int));
-}
-
-TEST(Btree, AllocCopyConstructor) {
- using Alloc = CountingAllocator<int>;
- using Set = absl::btree_set<int, std::less<int>, Alloc>;
- int64_t bytes_used1 = 0;
- Alloc alloc1(&bytes_used1);
- Set set1(alloc1);
-
- set1.insert({1, 2, 3});
-
- int64_t bytes_used2 = 0;
- Alloc alloc2(&bytes_used2);
- Set set2(set1, alloc2);
-
- EXPECT_THAT(set1, ElementsAre(1, 2, 3));
- EXPECT_THAT(set2, ElementsAre(1, 2, 3));
- EXPECT_GT(bytes_used1, set1.size() * sizeof(int));
- EXPECT_EQ(bytes_used1, bytes_used2);
-}
-
-TEST(Btree, AllocMoveConstructor_SameAlloc) {
- using Alloc = CountingAllocator<int>;
- using Set = absl::btree_set<int, std::less<int>, Alloc>;
- int64_t bytes_used = 0;
- Alloc alloc(&bytes_used);
- Set set1(alloc);
-
- set1.insert({1, 2, 3});
-
- const int64_t original_bytes_used = bytes_used;
- EXPECT_GT(original_bytes_used, set1.size() * sizeof(int));
-
- Set set2(std::move(set1), alloc);
-
- EXPECT_THAT(set2, ElementsAre(1, 2, 3));
- EXPECT_EQ(bytes_used, original_bytes_used);
-}
-
-TEST(Btree, AllocMoveConstructor_DifferentAlloc) {
- using Alloc = CountingAllocator<int>;
- using Set = absl::btree_set<int, std::less<int>, Alloc>;
- int64_t bytes_used1 = 0;
- Alloc alloc1(&bytes_used1);
- Set set1(alloc1);
-
- set1.insert({1, 2, 3});
-
- const int64_t original_bytes_used = bytes_used1;
- EXPECT_GT(original_bytes_used, set1.size() * sizeof(int));
-
- int64_t bytes_used2 = 0;
- Alloc alloc2(&bytes_used2);
- Set set2(std::move(set1), alloc2);
-
- EXPECT_THAT(set2, ElementsAre(1, 2, 3));
- // We didn't free these bytes allocated by `set1` yet.
- EXPECT_EQ(bytes_used1, original_bytes_used);
- EXPECT_EQ(bytes_used2, original_bytes_used);
-}
-
-bool IntCmp(const int a, const int b) { return a < b; }
-
-TEST(Btree, SupportsFunctionPtrComparator) {
- absl::btree_set<int, decltype(IntCmp) *> set(IntCmp);
- set.insert({1, 2, 3});
- EXPECT_THAT(set, ElementsAre(1, 2, 3));
- EXPECT_TRUE(set.key_comp()(1, 2));
- EXPECT_TRUE(set.value_comp()(1, 2));
-
- absl::btree_map<int, int, decltype(IntCmp) *> map(&IntCmp);
- map[1] = 1;
- EXPECT_THAT(map, ElementsAre(Pair(1, 1)));
- EXPECT_TRUE(map.key_comp()(1, 2));
- EXPECT_TRUE(map.value_comp()(std::make_pair(1, 1), std::make_pair(2, 2)));
-}
-
-template <typename Compare>
-struct TransparentPassThroughComp {
- using is_transparent = void;
-
- // This will fail compilation if we attempt a comparison that Compare does not
- // support, and the failure will happen inside the function implementation so
- // it can't be avoided by using SFINAE on this comparator.
- template <typename T, typename U>
- bool operator()(const T &lhs, const U &rhs) const {
- return Compare()(lhs, rhs);
- }
-};
-
-TEST(Btree,
- SupportsTransparentComparatorThatDoesNotImplementAllVisibleOperators) {
- absl::btree_set<MultiKey, TransparentPassThroughComp<MultiKeyComp>> set;
- set.insert(MultiKey{1, 2});
- EXPECT_TRUE(set.contains(1));
-}
-
-TEST(Btree, ConstructImplicitlyWithUnadaptedComparator) {
- absl::btree_set<MultiKey, MultiKeyComp> set = {{}, MultiKeyComp{}};
-}
-
-#ifndef NDEBUG
-TEST(Btree, InvalidComparatorsCaught) {
- {
- struct ZeroAlwaysLessCmp {
- bool operator()(int lhs, int rhs) const {
- if (lhs == 0) return true;
- return lhs < rhs;
- }
- };
- absl::btree_set<int, ZeroAlwaysLessCmp> set;
- EXPECT_DEATH(set.insert({0, 1, 2}), "is_self_equivalent");
- }
- {
- struct ThreeWayAlwaysLessCmp {
- absl::weak_ordering operator()(int, int) const {
- return absl::weak_ordering::less;
- }
- };
- absl::btree_set<int, ThreeWayAlwaysLessCmp> set;
- EXPECT_DEATH(set.insert({0, 1, 2}), "is_self_equivalent");
- }
- {
- struct SumGreaterZeroCmp {
- bool operator()(int lhs, int rhs) const {
- // First, do equivalence correctly - so we can test later condition.
- if (lhs == rhs) return false;
- return lhs + rhs > 0;
- }
- };
- absl::btree_set<int, SumGreaterZeroCmp> set;
- // Note: '!' only needs to be escaped when it's the first character.
- EXPECT_DEATH(set.insert({0, 1, 2}),
- R"regex(\!lhs_comp_rhs \|\| !comp\(\)\(rhs, lhs\))regex");
- }
- {
- struct ThreeWaySumGreaterZeroCmp {
- absl::weak_ordering operator()(int lhs, int rhs) const {
- // First, do equivalence correctly - so we can test later condition.
- if (lhs == rhs) return absl::weak_ordering::equivalent;
-
- if (lhs + rhs > 0) return absl::weak_ordering::less;
- if (lhs + rhs == 0) return absl::weak_ordering::equivalent;
- return absl::weak_ordering::greater;
- }
- };
- absl::btree_set<int, ThreeWaySumGreaterZeroCmp> set;
- EXPECT_DEATH(set.insert({0, 1, 2}), "lhs_comp_rhs < 0 -> rhs_comp_lhs > 0");
- }
-}
-#endif
-
-#ifndef _MSC_VER
-// This test crashes on MSVC.
-TEST(Btree, InvalidIteratorUse) {
- if (!BtreeNodePeer::UsesGenerations<absl::btree_set<int>>())
- GTEST_SKIP() << "Generation validation for iterators is disabled.";
-
- {
- absl::btree_set<int> set;
- for (int i = 0; i < 10; ++i) set.insert(i);
- auto it = set.begin();
- set.erase(it++);
- EXPECT_DEATH(set.erase(it++), "invalidated iterator");
- }
- {
- absl::btree_set<int> set;
- for (int i = 0; i < 10; ++i) set.insert(i);
- auto it = set.insert(20).first;
- set.insert(30);
- EXPECT_DEATH(*it, "invalidated iterator");
- }
- {
- absl::btree_set<int> set;
- for (int i = 0; i < 10000; ++i) set.insert(i);
- auto it = set.find(5000);
- ASSERT_NE(it, set.end());
- set.erase(1);
- EXPECT_DEATH(*it, "invalidated iterator");
- }
-}
-#endif
-
-class OnlyConstructibleByAllocator {
- explicit OnlyConstructibleByAllocator(int i) : i_(i) {}
-
- public:
- OnlyConstructibleByAllocator(const OnlyConstructibleByAllocator &other)
- : i_(other.i_) {}
- OnlyConstructibleByAllocator &operator=(
- const OnlyConstructibleByAllocator &other) {
- i_ = other.i_;
- return *this;
- }
- int Get() const { return i_; }
- bool operator==(int i) const { return i_ == i; }
-
- private:
- template <typename T>
- friend class OnlyConstructibleAllocator;
-
- int i_;
-};
-
-template <typename T = OnlyConstructibleByAllocator>
-class OnlyConstructibleAllocator : public std::allocator<T> {
- public:
- OnlyConstructibleAllocator() = default;
- template <class U>
- explicit OnlyConstructibleAllocator(const OnlyConstructibleAllocator<U> &) {}
-
- void construct(OnlyConstructibleByAllocator *p, int i) {
- new (p) OnlyConstructibleByAllocator(i);
- }
- template <typename Pair>
- void construct(Pair *p, const int i) {
- OnlyConstructibleByAllocator only(i);
- new (p) Pair(std::move(only), i);
- }
-
- template <class U>
- struct rebind {
- using other = OnlyConstructibleAllocator<U>;
- };
-};
-
-struct OnlyConstructibleByAllocatorComp {
- using is_transparent = void;
- bool operator()(OnlyConstructibleByAllocator a,
- OnlyConstructibleByAllocator b) const {
- return a.Get() < b.Get();
- }
- bool operator()(int a, OnlyConstructibleByAllocator b) const {
- return a < b.Get();
- }
- bool operator()(OnlyConstructibleByAllocator a, int b) const {
- return a.Get() < b;
- }
-};
-
-TEST(Btree, OnlyConstructibleByAllocatorType) {
- const std::array<int, 2> arr = {3, 4};
- {
- absl::btree_set<OnlyConstructibleByAllocator,
- OnlyConstructibleByAllocatorComp,
- OnlyConstructibleAllocator<>>
- set;
- set.emplace(1);
- set.emplace_hint(set.end(), 2);
- set.insert(arr.begin(), arr.end());
- EXPECT_THAT(set, ElementsAre(1, 2, 3, 4));
- }
- {
- absl::btree_multiset<OnlyConstructibleByAllocator,
- OnlyConstructibleByAllocatorComp,
- OnlyConstructibleAllocator<>>
- set;
- set.emplace(1);
- set.emplace_hint(set.end(), 2);
- // TODO(ezb): fix insert_multi to allow this to compile.
- // set.insert(arr.begin(), arr.end());
- EXPECT_THAT(set, ElementsAre(1, 2));
- }
- {
- absl::btree_map<OnlyConstructibleByAllocator, int,
- OnlyConstructibleByAllocatorComp,
- OnlyConstructibleAllocator<>>
- map;
- map.emplace(1);
- map.emplace_hint(map.end(), 2);
- map.insert(arr.begin(), arr.end());
- EXPECT_THAT(map,
- ElementsAre(Pair(1, 1), Pair(2, 2), Pair(3, 3), Pair(4, 4)));
- }
- {
- absl::btree_multimap<OnlyConstructibleByAllocator, int,
- OnlyConstructibleByAllocatorComp,
- OnlyConstructibleAllocator<>>
- map;
- map.emplace(1);
- map.emplace_hint(map.end(), 2);
- // TODO(ezb): fix insert_multi to allow this to compile.
- // map.insert(arr.begin(), arr.end());
- EXPECT_THAT(map, ElementsAre(Pair(1, 1), Pair(2, 2)));
- }
-}
-
-class NotAssignable {
- public:
- explicit NotAssignable(int i) : i_(i) {}
- NotAssignable(const NotAssignable &other) : i_(other.i_) {}
- NotAssignable &operator=(NotAssignable &&other) = delete;
- int Get() const { return i_; }
- bool operator==(int i) const { return i_ == i; }
- friend bool operator<(NotAssignable a, NotAssignable b) {
- return a.i_ < b.i_;
- }
-
- private:
- int i_;
-};
-
-TEST(Btree, NotAssignableType) {
- {
- absl::btree_set<NotAssignable> set;
- set.emplace(1);
- set.emplace_hint(set.end(), 2);
- set.insert(NotAssignable(3));
- set.insert(set.end(), NotAssignable(4));
- EXPECT_THAT(set, ElementsAre(1, 2, 3, 4));
- set.erase(set.begin());
- EXPECT_THAT(set, ElementsAre(2, 3, 4));
- }
- {
- absl::btree_multiset<NotAssignable> set;
- set.emplace(1);
- set.emplace_hint(set.end(), 2);
- set.insert(NotAssignable(2));
- set.insert(set.end(), NotAssignable(3));
- EXPECT_THAT(set, ElementsAre(1, 2, 2, 3));
- set.erase(set.begin());
- EXPECT_THAT(set, ElementsAre(2, 2, 3));
- }
- {
- absl::btree_map<NotAssignable, int> map;
- map.emplace(NotAssignable(1), 1);
- map.emplace_hint(map.end(), NotAssignable(2), 2);
- map.insert({NotAssignable(3), 3});
- map.insert(map.end(), {NotAssignable(4), 4});
- EXPECT_THAT(map,
- ElementsAre(Pair(1, 1), Pair(2, 2), Pair(3, 3), Pair(4, 4)));
- map.erase(map.begin());
- EXPECT_THAT(map, ElementsAre(Pair(2, 2), Pair(3, 3), Pair(4, 4)));
- }
- {
- absl::btree_multimap<NotAssignable, int> map;
- map.emplace(NotAssignable(1), 1);
- map.emplace_hint(map.end(), NotAssignable(2), 2);
- map.insert({NotAssignable(2), 3});
- map.insert(map.end(), {NotAssignable(3), 3});
- EXPECT_THAT(map,
- ElementsAre(Pair(1, 1), Pair(2, 2), Pair(2, 3), Pair(3, 3)));
- map.erase(map.begin());
- EXPECT_THAT(map, ElementsAre(Pair(2, 2), Pair(2, 3), Pair(3, 3)));
- }
-}
-
-struct ArenaLike {
- void* recycled = nullptr;
- size_t recycled_size = 0;
-};
-
-// A very simple implementation of arena allocation.
-template <typename T>
-class ArenaLikeAllocator : public std::allocator<T> {
- public:
- // Standard library containers require the ability to allocate objects of
- // different types which they can do so via rebind.other.
- template <typename U>
- struct rebind {
- using other = ArenaLikeAllocator<U>;
- };
-
- explicit ArenaLikeAllocator(ArenaLike* arena) noexcept : arena_(arena) {}
-
- ~ArenaLikeAllocator() {
- if (arena_->recycled != nullptr) {
- delete [] static_cast<T*>(arena_->recycled);
- arena_->recycled = nullptr;
- }
- }
-
- template<typename U>
- explicit ArenaLikeAllocator(const ArenaLikeAllocator<U>& other) noexcept
- : arena_(other.arena_) {}
-
- T* allocate(size_t num_objects, const void* = nullptr) {
- size_t size = num_objects * sizeof(T);
- if (arena_->recycled != nullptr && arena_->recycled_size == size) {
- T* result = static_cast<T*>(arena_->recycled);
- arena_->recycled = nullptr;
- return result;
- }
- return new T[num_objects];
- }
-
- void deallocate(T* p, size_t num_objects) {
- size_t size = num_objects * sizeof(T);
-
- // Simulate writing to the freed memory as an actual arena allocator might
- // do. This triggers an error report if the memory is poisoned.
- memset(p, 0xde, size);
-
- if (arena_->recycled == nullptr) {
- arena_->recycled = p;
- arena_->recycled_size = size;
- } else {
- delete [] p;
- }
- }
-
- ArenaLike* arena_;
-};
-
-// This test verifies that an arena allocator that reuses memory will not be
-// asked to free poisoned BTree memory.
-TEST(Btree, ReusePoisonMemory) {
- using Alloc = ArenaLikeAllocator<int64_t>;
- using Set = absl::btree_set<int64_t, std::less<int64_t>, Alloc>;
- ArenaLike arena;
- Alloc alloc(&arena);
- Set set(alloc);
-
- set.insert(0);
- set.erase(0);
- set.insert(0);
-}
-
-TEST(Btree, IteratorSubtraction) {
- absl::BitGen bitgen;
- std::vector<int> vec;
- // Randomize the set's insertion order so the nodes aren't all full.
- for (int i = 0; i < 1000000; ++i) vec.push_back(i);
- absl::c_shuffle(vec, bitgen);
-
- absl::btree_set<int> set;
- for (int i : vec) set.insert(i);
-
- for (int i = 0; i < 1000; ++i) {
- size_t begin = absl::Uniform(bitgen, 0u, set.size());
- size_t end = absl::Uniform(bitgen, begin, set.size());
- ASSERT_EQ(end - begin, set.find(end) - set.find(begin))
- << begin << " " << end;
- }
-}
-
-#ifndef NDEBUG
-TEST(Btree, DereferencingEndIterator) {
- absl::btree_set<int> set;
- for (int i = 0; i < 1000; ++i) set.insert(i);
- EXPECT_DEATH(*set.end(), R"regex(Dereferencing end\(\) iterator)regex");
-}
-#endif
-
-} // namespace
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/container/btree_test.h b/third_party/abseil-cpp/absl/container/btree_test.h
deleted file mode 100644
index 6249080..0000000
--- a/third_party/abseil-cpp/absl/container/btree_test.h
+++ /dev/null
@@ -1,166 +0,0 @@
-// Copyright 2018 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_CONTAINER_BTREE_TEST_H_
-#define ABSL_CONTAINER_BTREE_TEST_H_
-
-#include <algorithm>
-#include <cassert>
-#include <random>
-#include <string>
-#include <utility>
-#include <vector>
-
-#include "absl/container/btree_map.h"
-#include "absl/container/btree_set.h"
-#include "absl/container/flat_hash_set.h"
-#include "absl/strings/cord.h"
-#include "absl/time/time.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-
-// Like remove_const but propagates the removal through std::pair.
-template <typename T>
-struct remove_pair_const {
- using type = typename std::remove_const<T>::type;
-};
-template <typename T, typename U>
-struct remove_pair_const<std::pair<T, U> > {
- using type = std::pair<typename remove_pair_const<T>::type,
- typename remove_pair_const<U>::type>;
-};
-
-// Utility class to provide an accessor for a key given a value. The default
-// behavior is to treat the value as a pair and return the first element.
-template <typename K, typename V>
-struct KeyOfValue {
- struct type {
- const K& operator()(const V& p) const { return p.first; }
- };
-};
-
-// Partial specialization of KeyOfValue class for when the key and value are
-// the same type such as in set<> and btree_set<>.
-template <typename K>
-struct KeyOfValue<K, K> {
- struct type {
- const K& operator()(const K& k) const { return k; }
- };
-};
-
-inline char* GenerateDigits(char buf[16], unsigned val, unsigned maxval) {
- assert(val <= maxval);
- constexpr unsigned kBase = 64; // avoid integer division.
- unsigned p = 15;
- buf[p--] = 0;
- while (maxval > 0) {
- buf[p--] = ' ' + (val % kBase);
- val /= kBase;
- maxval /= kBase;
- }
- return buf + p + 1;
-}
-
-template <typename K>
-struct Generator {
- int maxval;
- explicit Generator(int m) : maxval(m) {}
- K operator()(int i) const {
- assert(i <= maxval);
- return K(i);
- }
-};
-
-template <>
-struct Generator<absl::Time> {
- int maxval;
- explicit Generator(int m) : maxval(m) {}
- absl::Time operator()(int i) const { return absl::FromUnixMillis(i); }
-};
-
-template <>
-struct Generator<std::string> {
- int maxval;
- explicit Generator(int m) : maxval(m) {}
- std::string operator()(int i) const {
- char buf[16];
- return GenerateDigits(buf, i, maxval);
- }
-};
-
-template <>
-struct Generator<Cord> {
- int maxval;
- explicit Generator(int m) : maxval(m) {}
- Cord operator()(int i) const {
- char buf[16];
- return Cord(GenerateDigits(buf, i, maxval));
- }
-};
-
-template <typename T, typename U>
-struct Generator<std::pair<T, U> > {
- Generator<typename remove_pair_const<T>::type> tgen;
- Generator<typename remove_pair_const<U>::type> ugen;
-
- explicit Generator(int m) : tgen(m), ugen(m) {}
- std::pair<T, U> operator()(int i) const {
- return std::make_pair(tgen(i), ugen(i));
- }
-};
-
-// Generate n values for our tests and benchmarks. Value range is [0, maxval].
-inline std::vector<int> GenerateNumbersWithSeed(int n, int maxval, int seed) {
- // NOTE: Some tests rely on generated numbers not changing between test runs.
- // We use std::minstd_rand0 because it is well-defined, but don't use
- // std::uniform_int_distribution because platforms use different algorithms.
- std::minstd_rand0 rng(seed);
-
- std::vector<int> values;
- absl::flat_hash_set<int> unique_values;
- if (values.size() < n) {
- for (int i = values.size(); i < n; i++) {
- int value;
- do {
- value = static_cast<int>(rng()) % (maxval + 1);
- } while (!unique_values.insert(value).second);
-
- values.push_back(value);
- }
- }
- return values;
-}
-
-// Generates n values in the range [0, maxval].
-template <typename V>
-std::vector<V> GenerateValuesWithSeed(int n, int maxval, int seed) {
- const std::vector<int> nums = GenerateNumbersWithSeed(n, maxval, seed);
- Generator<V> gen(maxval);
- std::vector<V> vec;
-
- vec.reserve(n);
- for (int i = 0; i < n; i++) {
- vec.push_back(gen(nums[i]));
- }
-
- return vec;
-}
-
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_BTREE_TEST_H_
diff --git a/third_party/abseil-cpp/absl/container/fixed_array.h b/third_party/abseil-cpp/absl/container/fixed_array.h
deleted file mode 100644
index 5543243..0000000
--- a/third_party/abseil-cpp/absl/container/fixed_array.h
+++ /dev/null
@@ -1,532 +0,0 @@
-// Copyright 2018 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.
-//
-// -----------------------------------------------------------------------------
-// File: fixed_array.h
-// -----------------------------------------------------------------------------
-//
-// A `FixedArray<T>` represents a non-resizable array of `T` where the length of
-// the array can be determined at run-time. It is a good replacement for
-// non-standard and deprecated uses of `alloca()` and variable length arrays
-// within the GCC extension. (See
-// https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html).
-//
-// `FixedArray` allocates small arrays inline, keeping performance fast by
-// avoiding heap operations. It also helps reduce the chances of
-// accidentally overflowing your stack if large input is passed to
-// your function.
-
-#ifndef ABSL_CONTAINER_FIXED_ARRAY_H_
-#define ABSL_CONTAINER_FIXED_ARRAY_H_
-
-#include <algorithm>
-#include <cassert>
-#include <cstddef>
-#include <initializer_list>
-#include <iterator>
-#include <limits>
-#include <memory>
-#include <new>
-#include <type_traits>
-
-#include "absl/algorithm/algorithm.h"
-#include "absl/base/config.h"
-#include "absl/base/dynamic_annotations.h"
-#include "absl/base/internal/throw_delegate.h"
-#include "absl/base/macros.h"
-#include "absl/base/optimization.h"
-#include "absl/base/port.h"
-#include "absl/container/internal/compressed_tuple.h"
-#include "absl/memory/memory.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-
-constexpr static auto kFixedArrayUseDefault = static_cast<size_t>(-1);
-
-// -----------------------------------------------------------------------------
-// FixedArray
-// -----------------------------------------------------------------------------
-//
-// A `FixedArray` provides a run-time fixed-size array, allocating a small array
-// inline for efficiency.
-//
-// Most users should not specify an `inline_elements` argument and let
-// `FixedArray` automatically determine the number of elements
-// to store inline based on `sizeof(T)`. If `inline_elements` is specified, the
-// `FixedArray` implementation will use inline storage for arrays with a
-// length <= `inline_elements`.
-//
-// Note that a `FixedArray` constructed with a `size_type` argument will
-// default-initialize its values by leaving trivially constructible types
-// uninitialized (e.g. int, int[4], double), and others default-constructed.
-// This matches the behavior of c-style arrays and `std::array`, but not
-// `std::vector`.
-template <typename T, size_t N = kFixedArrayUseDefault,
- typename A = std::allocator<T>>
-class FixedArray {
- static_assert(!std::is_array<T>::value || std::extent<T>::value > 0,
- "Arrays with unknown bounds cannot be used with FixedArray.");
-
- static constexpr size_t kInlineBytesDefault = 256;
-
- using AllocatorTraits = std::allocator_traits<A>;
- // std::iterator_traits isn't guaranteed to be SFINAE-friendly until C++17,
- // but this seems to be mostly pedantic.
- template <typename Iterator>
- using EnableIfForwardIterator = absl::enable_if_t<std::is_convertible<
- typename std::iterator_traits<Iterator>::iterator_category,
- std::forward_iterator_tag>::value>;
- static constexpr bool NoexceptCopyable() {
- return std::is_nothrow_copy_constructible<StorageElement>::value &&
- absl::allocator_is_nothrow<allocator_type>::value;
- }
- static constexpr bool NoexceptMovable() {
- return std::is_nothrow_move_constructible<StorageElement>::value &&
- absl::allocator_is_nothrow<allocator_type>::value;
- }
- static constexpr bool DefaultConstructorIsNonTrivial() {
- return !absl::is_trivially_default_constructible<StorageElement>::value;
- }
-
- public:
- using allocator_type = typename AllocatorTraits::allocator_type;
- using value_type = typename AllocatorTraits::value_type;
- using pointer = typename AllocatorTraits::pointer;
- using const_pointer = typename AllocatorTraits::const_pointer;
- using reference = value_type&;
- using const_reference = const value_type&;
- using size_type = typename AllocatorTraits::size_type;
- using difference_type = typename AllocatorTraits::difference_type;
- using iterator = pointer;
- using const_iterator = const_pointer;
- using reverse_iterator = std::reverse_iterator<iterator>;
- using const_reverse_iterator = std::reverse_iterator<const_iterator>;
-
- static constexpr size_type inline_elements =
- (N == kFixedArrayUseDefault ? kInlineBytesDefault / sizeof(value_type)
- : static_cast<size_type>(N));
-
- FixedArray(
- const FixedArray& other,
- const allocator_type& a = allocator_type()) noexcept(NoexceptCopyable())
- : FixedArray(other.begin(), other.end(), a) {}
-
- FixedArray(
- FixedArray&& other,
- const allocator_type& a = allocator_type()) noexcept(NoexceptMovable())
- : FixedArray(std::make_move_iterator(other.begin()),
- std::make_move_iterator(other.end()), a) {}
-
- // Creates an array object that can store `n` elements.
- // Note that trivially constructible elements will be uninitialized.
- explicit FixedArray(size_type n, const allocator_type& a = allocator_type())
- : storage_(n, a) {
- if (DefaultConstructorIsNonTrivial()) {
- memory_internal::ConstructRange(storage_.alloc(), storage_.begin(),
- storage_.end());
- }
- }
-
- // Creates an array initialized with `n` copies of `val`.
- FixedArray(size_type n, const value_type& val,
- const allocator_type& a = allocator_type())
- : storage_(n, a) {
- memory_internal::ConstructRange(storage_.alloc(), storage_.begin(),
- storage_.end(), val);
- }
-
- // Creates an array initialized with the size and contents of `init_list`.
- FixedArray(std::initializer_list<value_type> init_list,
- const allocator_type& a = allocator_type())
- : FixedArray(init_list.begin(), init_list.end(), a) {}
-
- // Creates an array initialized with the elements from the input
- // range. The array's size will always be `std::distance(first, last)`.
- // REQUIRES: Iterator must be a forward_iterator or better.
- template <typename Iterator, EnableIfForwardIterator<Iterator>* = nullptr>
- FixedArray(Iterator first, Iterator last,
- const allocator_type& a = allocator_type())
- : storage_(std::distance(first, last), a) {
- memory_internal::CopyRange(storage_.alloc(), storage_.begin(), first, last);
- }
-
- ~FixedArray() noexcept {
- for (auto* cur = storage_.begin(); cur != storage_.end(); ++cur) {
- AllocatorTraits::destroy(storage_.alloc(), cur);
- }
- }
-
- // Assignments are deleted because they break the invariant that the size of a
- // `FixedArray` never changes.
- void operator=(FixedArray&&) = delete;
- void operator=(const FixedArray&) = delete;
-
- // FixedArray::size()
- //
- // Returns the length of the fixed array.
- size_type size() const { return storage_.size(); }
-
- // FixedArray::max_size()
- //
- // Returns the largest possible value of `std::distance(begin(), end())` for a
- // `FixedArray<T>`. This is equivalent to the most possible addressable bytes
- // over the number of bytes taken by T.
- constexpr size_type max_size() const {
- return (std::numeric_limits<difference_type>::max)() / sizeof(value_type);
- }
-
- // FixedArray::empty()
- //
- // Returns whether or not the fixed array is empty.
- bool empty() const { return size() == 0; }
-
- // FixedArray::memsize()
- //
- // Returns the memory size of the fixed array in bytes.
- size_t memsize() const { return size() * sizeof(value_type); }
-
- // FixedArray::data()
- //
- // Returns a const T* pointer to elements of the `FixedArray`. This pointer
- // can be used to access (but not modify) the contained elements.
- const_pointer data() const { return AsValueType(storage_.begin()); }
-
- // Overload of FixedArray::data() to return a T* pointer to elements of the
- // fixed array. This pointer can be used to access and modify the contained
- // elements.
- pointer data() { return AsValueType(storage_.begin()); }
-
- // FixedArray::operator[]
- //
- // Returns a reference the ith element of the fixed array.
- // REQUIRES: 0 <= i < size()
- reference operator[](size_type i) {
- ABSL_HARDENING_ASSERT(i < size());
- return data()[i];
- }
-
- // Overload of FixedArray::operator()[] to return a const reference to the
- // ith element of the fixed array.
- // REQUIRES: 0 <= i < size()
- const_reference operator[](size_type i) const {
- ABSL_HARDENING_ASSERT(i < size());
- return data()[i];
- }
-
- // FixedArray::at
- //
- // Bounds-checked access. Returns a reference to the ith element of the fixed
- // array, or throws std::out_of_range
- reference at(size_type i) {
- if (ABSL_PREDICT_FALSE(i >= size())) {
- base_internal::ThrowStdOutOfRange("FixedArray::at failed bounds check");
- }
- return data()[i];
- }
-
- // Overload of FixedArray::at() to return a const reference to the ith element
- // of the fixed array.
- const_reference at(size_type i) const {
- if (ABSL_PREDICT_FALSE(i >= size())) {
- base_internal::ThrowStdOutOfRange("FixedArray::at failed bounds check");
- }
- return data()[i];
- }
-
- // FixedArray::front()
- //
- // Returns a reference to the first element of the fixed array.
- reference front() {
- ABSL_HARDENING_ASSERT(!empty());
- return data()[0];
- }
-
- // Overload of FixedArray::front() to return a reference to the first element
- // of a fixed array of const values.
- const_reference front() const {
- ABSL_HARDENING_ASSERT(!empty());
- return data()[0];
- }
-
- // FixedArray::back()
- //
- // Returns a reference to the last element of the fixed array.
- reference back() {
- ABSL_HARDENING_ASSERT(!empty());
- return data()[size() - 1];
- }
-
- // Overload of FixedArray::back() to return a reference to the last element
- // of a fixed array of const values.
- const_reference back() const {
- ABSL_HARDENING_ASSERT(!empty());
- return data()[size() - 1];
- }
-
- // FixedArray::begin()
- //
- // Returns an iterator to the beginning of the fixed array.
- iterator begin() { return data(); }
-
- // Overload of FixedArray::begin() to return a const iterator to the
- // beginning of the fixed array.
- const_iterator begin() const { return data(); }
-
- // FixedArray::cbegin()
- //
- // Returns a const iterator to the beginning of the fixed array.
- const_iterator cbegin() const { return begin(); }
-
- // FixedArray::end()
- //
- // Returns an iterator to the end of the fixed array.
- iterator end() { return data() + size(); }
-
- // Overload of FixedArray::end() to return a const iterator to the end of the
- // fixed array.
- const_iterator end() const { return data() + size(); }
-
- // FixedArray::cend()
- //
- // Returns a const iterator to the end of the fixed array.
- const_iterator cend() const { return end(); }
-
- // FixedArray::rbegin()
- //
- // Returns a reverse iterator from the end of the fixed array.
- reverse_iterator rbegin() { return reverse_iterator(end()); }
-
- // Overload of FixedArray::rbegin() to return a const reverse iterator from
- // the end of the fixed array.
- const_reverse_iterator rbegin() const {
- return const_reverse_iterator(end());
- }
-
- // FixedArray::crbegin()
- //
- // Returns a const reverse iterator from the end of the fixed array.
- const_reverse_iterator crbegin() const { return rbegin(); }
-
- // FixedArray::rend()
- //
- // Returns a reverse iterator from the beginning of the fixed array.
- reverse_iterator rend() { return reverse_iterator(begin()); }
-
- // Overload of FixedArray::rend() for returning a const reverse iterator
- // from the beginning of the fixed array.
- const_reverse_iterator rend() const {
- return const_reverse_iterator(begin());
- }
-
- // FixedArray::crend()
- //
- // Returns a reverse iterator from the beginning of the fixed array.
- const_reverse_iterator crend() const { return rend(); }
-
- // FixedArray::fill()
- //
- // Assigns the given `value` to all elements in the fixed array.
- void fill(const value_type& val) { std::fill(begin(), end(), val); }
-
- // Relational operators. Equality operators are elementwise using
- // `operator==`, while order operators order FixedArrays lexicographically.
- friend bool operator==(const FixedArray& lhs, const FixedArray& rhs) {
- return absl::equal(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
- }
-
- friend bool operator!=(const FixedArray& lhs, const FixedArray& rhs) {
- return !(lhs == rhs);
- }
-
- friend bool operator<(const FixedArray& lhs, const FixedArray& rhs) {
- return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(),
- rhs.end());
- }
-
- friend bool operator>(const FixedArray& lhs, const FixedArray& rhs) {
- return rhs < lhs;
- }
-
- friend bool operator<=(const FixedArray& lhs, const FixedArray& rhs) {
- return !(rhs < lhs);
- }
-
- friend bool operator>=(const FixedArray& lhs, const FixedArray& rhs) {
- return !(lhs < rhs);
- }
-
- template <typename H>
- friend H AbslHashValue(H h, const FixedArray& v) {
- return H::combine(H::combine_contiguous(std::move(h), v.data(), v.size()),
- v.size());
- }
-
- private:
- // StorageElement
- //
- // For FixedArrays with a C-style-array value_type, StorageElement is a POD
- // wrapper struct called StorageElementWrapper that holds the value_type
- // instance inside. This is needed for construction and destruction of the
- // entire array regardless of how many dimensions it has. For all other cases,
- // StorageElement is just an alias of value_type.
- //
- // Maintainer's Note: The simpler solution would be to simply wrap value_type
- // in a struct whether it's an array or not. That causes some paranoid
- // diagnostics to misfire, believing that 'data()' returns a pointer to a
- // single element, rather than the packed array that it really is.
- // e.g.:
- //
- // FixedArray<char> buf(1);
- // sprintf(buf.data(), "foo");
- //
- // error: call to int __builtin___sprintf_chk(etc...)
- // will always overflow destination buffer [-Werror]
- //
- template <typename OuterT, typename InnerT = absl::remove_extent_t<OuterT>,
- size_t InnerN = std::extent<OuterT>::value>
- struct StorageElementWrapper {
- InnerT array[InnerN];
- };
-
- using StorageElement =
- absl::conditional_t<std::is_array<value_type>::value,
- StorageElementWrapper<value_type>, value_type>;
-
- static pointer AsValueType(pointer ptr) { return ptr; }
- static pointer AsValueType(StorageElementWrapper<value_type>* ptr) {
- return std::addressof(ptr->array);
- }
-
- static_assert(sizeof(StorageElement) == sizeof(value_type), "");
- static_assert(alignof(StorageElement) == alignof(value_type), "");
-
- class NonEmptyInlinedStorage {
- public:
- StorageElement* data() { return reinterpret_cast<StorageElement*>(buff_); }
- void AnnotateConstruct(size_type n);
- void AnnotateDestruct(size_type n);
-
-#ifdef ABSL_HAVE_ADDRESS_SANITIZER
- void* RedzoneBegin() { return &redzone_begin_; }
- void* RedzoneEnd() { return &redzone_end_ + 1; }
-#endif // ABSL_HAVE_ADDRESS_SANITIZER
-
- private:
- ABSL_ADDRESS_SANITIZER_REDZONE(redzone_begin_);
- alignas(StorageElement) char buff_[sizeof(StorageElement[inline_elements])];
- ABSL_ADDRESS_SANITIZER_REDZONE(redzone_end_);
- };
-
- class EmptyInlinedStorage {
- public:
- StorageElement* data() { return nullptr; }
- void AnnotateConstruct(size_type) {}
- void AnnotateDestruct(size_type) {}
- };
-
- using InlinedStorage =
- absl::conditional_t<inline_elements == 0, EmptyInlinedStorage,
- NonEmptyInlinedStorage>;
-
- // Storage
- //
- // An instance of Storage manages the inline and out-of-line memory for
- // instances of FixedArray. This guarantees that even when construction of
- // individual elements fails in the FixedArray constructor body, the
- // destructor for Storage will still be called and out-of-line memory will be
- // properly deallocated.
- //
- class Storage : public InlinedStorage {
- public:
- Storage(size_type n, const allocator_type& a)
- : size_alloc_(n, a), data_(InitializeData()) {}
-
- ~Storage() noexcept {
- if (UsingInlinedStorage(size())) {
- InlinedStorage::AnnotateDestruct(size());
- } else {
- AllocatorTraits::deallocate(alloc(), AsValueType(begin()), size());
- }
- }
-
- size_type size() const { return size_alloc_.template get<0>(); }
- StorageElement* begin() const { return data_; }
- StorageElement* end() const { return begin() + size(); }
- allocator_type& alloc() { return size_alloc_.template get<1>(); }
-
- private:
- static bool UsingInlinedStorage(size_type n) {
- return n <= inline_elements;
- }
-
-#ifdef ABSL_HAVE_ADDRESS_SANITIZER
- ABSL_ATTRIBUTE_NOINLINE
-#endif // ABSL_HAVE_ADDRESS_SANITIZER
- StorageElement* InitializeData() {
- if (UsingInlinedStorage(size())) {
- InlinedStorage::AnnotateConstruct(size());
- return InlinedStorage::data();
- } else {
- return reinterpret_cast<StorageElement*>(
- AllocatorTraits::allocate(alloc(), size()));
- }
- }
-
- // `CompressedTuple` takes advantage of EBCO for stateless `allocator_type`s
- container_internal::CompressedTuple<size_type, allocator_type> size_alloc_;
- StorageElement* data_;
- };
-
- Storage storage_;
-};
-
-#ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL
-template <typename T, size_t N, typename A>
-constexpr size_t FixedArray<T, N, A>::kInlineBytesDefault;
-
-template <typename T, size_t N, typename A>
-constexpr typename FixedArray<T, N, A>::size_type
- FixedArray<T, N, A>::inline_elements;
-#endif
-
-template <typename T, size_t N, typename A>
-void FixedArray<T, N, A>::NonEmptyInlinedStorage::AnnotateConstruct(
- typename FixedArray<T, N, A>::size_type n) {
-#ifdef ABSL_HAVE_ADDRESS_SANITIZER
- if (!n) return;
- ABSL_ANNOTATE_CONTIGUOUS_CONTAINER(data(), RedzoneEnd(), RedzoneEnd(),
- data() + n);
- ABSL_ANNOTATE_CONTIGUOUS_CONTAINER(RedzoneBegin(), data(), data(),
- RedzoneBegin());
-#endif // ABSL_HAVE_ADDRESS_SANITIZER
- static_cast<void>(n); // Mark used when not in asan mode
-}
-
-template <typename T, size_t N, typename A>
-void FixedArray<T, N, A>::NonEmptyInlinedStorage::AnnotateDestruct(
- typename FixedArray<T, N, A>::size_type n) {
-#ifdef ABSL_HAVE_ADDRESS_SANITIZER
- if (!n) return;
- ABSL_ANNOTATE_CONTIGUOUS_CONTAINER(data(), RedzoneEnd(), data() + n,
- RedzoneEnd());
- ABSL_ANNOTATE_CONTIGUOUS_CONTAINER(RedzoneBegin(), data(), RedzoneBegin(),
- data());
-#endif // ABSL_HAVE_ADDRESS_SANITIZER
- static_cast<void>(n); // Mark used when not in asan mode
-}
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_FIXED_ARRAY_H_
diff --git a/third_party/abseil-cpp/absl/container/fixed_array_benchmark.cc b/third_party/abseil-cpp/absl/container/fixed_array_benchmark.cc
deleted file mode 100644
index db6663e..0000000
--- a/third_party/abseil-cpp/absl/container/fixed_array_benchmark.cc
+++ /dev/null
@@ -1,67 +0,0 @@
-// Copyright 2019 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 <stddef.h>
-
-#include <string>
-
-#include "absl/container/fixed_array.h"
-#include "benchmark/benchmark.h"
-
-namespace {
-
-// For benchmarking -- simple class with constructor and destructor that
-// set an int to a constant..
-class SimpleClass {
- public:
- SimpleClass() : i(3) {}
- ~SimpleClass() { i = 0; }
-
- private:
- int i;
-};
-
-template <typename C, size_t stack_size>
-void BM_FixedArray(benchmark::State& state) {
- const int size = state.range(0);
- for (auto _ : state) {
- absl::FixedArray<C, stack_size> fa(size);
- benchmark::DoNotOptimize(fa.data());
- }
-}
-BENCHMARK_TEMPLATE(BM_FixedArray, char, absl::kFixedArrayUseDefault)
- ->Range(0, 1 << 16);
-BENCHMARK_TEMPLATE(BM_FixedArray, char, 0)->Range(0, 1 << 16);
-BENCHMARK_TEMPLATE(BM_FixedArray, char, 1)->Range(0, 1 << 16);
-BENCHMARK_TEMPLATE(BM_FixedArray, char, 16)->Range(0, 1 << 16);
-BENCHMARK_TEMPLATE(BM_FixedArray, char, 256)->Range(0, 1 << 16);
-BENCHMARK_TEMPLATE(BM_FixedArray, char, 65536)->Range(0, 1 << 16);
-
-BENCHMARK_TEMPLATE(BM_FixedArray, SimpleClass, absl::kFixedArrayUseDefault)
- ->Range(0, 1 << 16);
-BENCHMARK_TEMPLATE(BM_FixedArray, SimpleClass, 0)->Range(0, 1 << 16);
-BENCHMARK_TEMPLATE(BM_FixedArray, SimpleClass, 1)->Range(0, 1 << 16);
-BENCHMARK_TEMPLATE(BM_FixedArray, SimpleClass, 16)->Range(0, 1 << 16);
-BENCHMARK_TEMPLATE(BM_FixedArray, SimpleClass, 256)->Range(0, 1 << 16);
-BENCHMARK_TEMPLATE(BM_FixedArray, SimpleClass, 65536)->Range(0, 1 << 16);
-
-BENCHMARK_TEMPLATE(BM_FixedArray, std::string, absl::kFixedArrayUseDefault)
- ->Range(0, 1 << 16);
-BENCHMARK_TEMPLATE(BM_FixedArray, std::string, 0)->Range(0, 1 << 16);
-BENCHMARK_TEMPLATE(BM_FixedArray, std::string, 1)->Range(0, 1 << 16);
-BENCHMARK_TEMPLATE(BM_FixedArray, std::string, 16)->Range(0, 1 << 16);
-BENCHMARK_TEMPLATE(BM_FixedArray, std::string, 256)->Range(0, 1 << 16);
-BENCHMARK_TEMPLATE(BM_FixedArray, std::string, 65536)->Range(0, 1 << 16);
-
-} // namespace
diff --git a/third_party/abseil-cpp/absl/container/fixed_array_exception_safety_test.cc b/third_party/abseil-cpp/absl/container/fixed_array_exception_safety_test.cc
deleted file mode 100644
index e5f5929..0000000
--- a/third_party/abseil-cpp/absl/container/fixed_array_exception_safety_test.cc
+++ /dev/null
@@ -1,201 +0,0 @@
-// Copyright 2019 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/config.h"
-#include "absl/container/fixed_array.h"
-
-#ifdef ABSL_HAVE_EXCEPTIONS
-
-#include <initializer_list>
-
-#include "gtest/gtest.h"
-#include "absl/base/internal/exception_safety_testing.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-
-namespace {
-
-constexpr size_t kInlined = 25;
-constexpr size_t kSmallSize = kInlined / 2;
-constexpr size_t kLargeSize = kInlined * 2;
-
-constexpr int kInitialValue = 5;
-constexpr int kUpdatedValue = 10;
-
-using ::testing::TestThrowingCtor;
-
-using Thrower = testing::ThrowingValue<testing::TypeSpec::kEverythingThrows>;
-using ThrowAlloc =
- testing::ThrowingAllocator<Thrower, testing::AllocSpec::kEverythingThrows>;
-using MoveThrower = testing::ThrowingValue<testing::TypeSpec::kNoThrowMove>;
-using MoveThrowAlloc =
- testing::ThrowingAllocator<MoveThrower,
- testing::AllocSpec::kEverythingThrows>;
-
-using FixedArr = absl::FixedArray<Thrower, kInlined>;
-using FixedArrWithAlloc = absl::FixedArray<Thrower, kInlined, ThrowAlloc>;
-
-using MoveFixedArr = absl::FixedArray<MoveThrower, kInlined>;
-using MoveFixedArrWithAlloc =
- absl::FixedArray<MoveThrower, kInlined, MoveThrowAlloc>;
-
-TEST(FixedArrayExceptionSafety, CopyConstructor) {
- auto small = FixedArr(kSmallSize);
- TestThrowingCtor<FixedArr>(small);
-
- auto large = FixedArr(kLargeSize);
- TestThrowingCtor<FixedArr>(large);
-}
-
-TEST(FixedArrayExceptionSafety, CopyConstructorWithAlloc) {
- auto small = FixedArrWithAlloc(kSmallSize);
- TestThrowingCtor<FixedArrWithAlloc>(small);
-
- auto large = FixedArrWithAlloc(kLargeSize);
- TestThrowingCtor<FixedArrWithAlloc>(large);
-}
-
-TEST(FixedArrayExceptionSafety, MoveConstructor) {
- TestThrowingCtor<FixedArr>(FixedArr(kSmallSize));
- TestThrowingCtor<FixedArr>(FixedArr(kLargeSize));
-
- // TypeSpec::kNoThrowMove
- TestThrowingCtor<MoveFixedArr>(MoveFixedArr(kSmallSize));
- TestThrowingCtor<MoveFixedArr>(MoveFixedArr(kLargeSize));
-}
-
-TEST(FixedArrayExceptionSafety, MoveConstructorWithAlloc) {
- TestThrowingCtor<FixedArrWithAlloc>(FixedArrWithAlloc(kSmallSize));
- TestThrowingCtor<FixedArrWithAlloc>(FixedArrWithAlloc(kLargeSize));
-
- // TypeSpec::kNoThrowMove
- TestThrowingCtor<MoveFixedArrWithAlloc>(MoveFixedArrWithAlloc(kSmallSize));
- TestThrowingCtor<MoveFixedArrWithAlloc>(MoveFixedArrWithAlloc(kLargeSize));
-}
-
-TEST(FixedArrayExceptionSafety, SizeConstructor) {
- TestThrowingCtor<FixedArr>(kSmallSize);
- TestThrowingCtor<FixedArr>(kLargeSize);
-}
-
-TEST(FixedArrayExceptionSafety, SizeConstructorWithAlloc) {
- TestThrowingCtor<FixedArrWithAlloc>(kSmallSize);
- TestThrowingCtor<FixedArrWithAlloc>(kLargeSize);
-}
-
-TEST(FixedArrayExceptionSafety, SizeValueConstructor) {
- TestThrowingCtor<FixedArr>(kSmallSize, Thrower());
- TestThrowingCtor<FixedArr>(kLargeSize, Thrower());
-}
-
-TEST(FixedArrayExceptionSafety, SizeValueConstructorWithAlloc) {
- TestThrowingCtor<FixedArrWithAlloc>(kSmallSize, Thrower());
- TestThrowingCtor<FixedArrWithAlloc>(kLargeSize, Thrower());
-}
-
-TEST(FixedArrayExceptionSafety, IteratorConstructor) {
- auto small = FixedArr(kSmallSize);
- TestThrowingCtor<FixedArr>(small.begin(), small.end());
-
- auto large = FixedArr(kLargeSize);
- TestThrowingCtor<FixedArr>(large.begin(), large.end());
-}
-
-TEST(FixedArrayExceptionSafety, IteratorConstructorWithAlloc) {
- auto small = FixedArrWithAlloc(kSmallSize);
- TestThrowingCtor<FixedArrWithAlloc>(small.begin(), small.end());
-
- auto large = FixedArrWithAlloc(kLargeSize);
- TestThrowingCtor<FixedArrWithAlloc>(large.begin(), large.end());
-}
-
-TEST(FixedArrayExceptionSafety, InitListConstructor) {
- constexpr int small_inlined = 3;
- using SmallFixedArr = absl::FixedArray<Thrower, small_inlined>;
-
- TestThrowingCtor<SmallFixedArr>(std::initializer_list<Thrower>{});
- // Test inlined allocation
- TestThrowingCtor<SmallFixedArr>(
- std::initializer_list<Thrower>{Thrower{}, Thrower{}});
- // Test out of line allocation
- TestThrowingCtor<SmallFixedArr>(std::initializer_list<Thrower>{
- Thrower{}, Thrower{}, Thrower{}, Thrower{}, Thrower{}});
-}
-
-TEST(FixedArrayExceptionSafety, InitListConstructorWithAlloc) {
- constexpr int small_inlined = 3;
- using SmallFixedArrWithAlloc =
- absl::FixedArray<Thrower, small_inlined, ThrowAlloc>;
-
- TestThrowingCtor<SmallFixedArrWithAlloc>(std::initializer_list<Thrower>{});
- // Test inlined allocation
- TestThrowingCtor<SmallFixedArrWithAlloc>(
- std::initializer_list<Thrower>{Thrower{}, Thrower{}});
- // Test out of line allocation
- TestThrowingCtor<SmallFixedArrWithAlloc>(std::initializer_list<Thrower>{
- Thrower{}, Thrower{}, Thrower{}, Thrower{}, Thrower{}});
-}
-
-template <typename FixedArrT>
-testing::AssertionResult ReadMemory(FixedArrT* fixed_arr) {
- int sum = 0;
- for (const auto& thrower : *fixed_arr) {
- sum += thrower.Get();
- }
- return testing::AssertionSuccess() << "Values sum to [" << sum << "]";
-}
-
-TEST(FixedArrayExceptionSafety, Fill) {
- auto test_fill = testing::MakeExceptionSafetyTester()
- .WithContracts(ReadMemory<FixedArr>)
- .WithOperation([&](FixedArr* fixed_arr_ptr) {
- auto thrower =
- Thrower(kUpdatedValue, testing::nothrow_ctor);
- fixed_arr_ptr->fill(thrower);
- });
-
- EXPECT_TRUE(
- test_fill.WithInitialValue(FixedArr(kSmallSize, Thrower(kInitialValue)))
- .Test());
- EXPECT_TRUE(
- test_fill.WithInitialValue(FixedArr(kLargeSize, Thrower(kInitialValue)))
- .Test());
-}
-
-TEST(FixedArrayExceptionSafety, FillWithAlloc) {
- auto test_fill = testing::MakeExceptionSafetyTester()
- .WithContracts(ReadMemory<FixedArrWithAlloc>)
- .WithOperation([&](FixedArrWithAlloc* fixed_arr_ptr) {
- auto thrower =
- Thrower(kUpdatedValue, testing::nothrow_ctor);
- fixed_arr_ptr->fill(thrower);
- });
-
- EXPECT_TRUE(test_fill
- .WithInitialValue(
- FixedArrWithAlloc(kSmallSize, Thrower(kInitialValue)))
- .Test());
- EXPECT_TRUE(test_fill
- .WithInitialValue(
- FixedArrWithAlloc(kLargeSize, Thrower(kInitialValue)))
- .Test());
-}
-
-} // namespace
-
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_HAVE_EXCEPTIONS
diff --git a/third_party/abseil-cpp/absl/container/fixed_array_test.cc b/third_party/abseil-cpp/absl/container/fixed_array_test.cc
deleted file mode 100644
index 49598e7..0000000
--- a/third_party/abseil-cpp/absl/container/fixed_array_test.cc
+++ /dev/null
@@ -1,837 +0,0 @@
-// Copyright 2019 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/container/fixed_array.h"
-
-#include <stdio.h>
-
-#include <cstring>
-#include <list>
-#include <memory>
-#include <numeric>
-#include <scoped_allocator>
-#include <stdexcept>
-#include <string>
-#include <vector>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/base/config.h"
-#include "absl/base/internal/exception_testing.h"
-#include "absl/base/options.h"
-#include "absl/container/internal/counting_allocator.h"
-#include "absl/hash/hash_testing.h"
-#include "absl/memory/memory.h"
-
-using ::testing::ElementsAreArray;
-
-namespace {
-
-// Helper routine to determine if a absl::FixedArray used stack allocation.
-template <typename ArrayType>
-static bool IsOnStack(const ArrayType& a) {
- return a.size() <= ArrayType::inline_elements;
-}
-
-class ConstructionTester {
- public:
- ConstructionTester() : self_ptr_(this), value_(0) { constructions++; }
- ~ConstructionTester() {
- assert(self_ptr_ == this);
- self_ptr_ = nullptr;
- destructions++;
- }
-
- // These are incremented as elements are constructed and destructed so we can
- // be sure all elements are properly cleaned up.
- static int constructions;
- static int destructions;
-
- void CheckConstructed() { assert(self_ptr_ == this); }
-
- void set(int value) { value_ = value; }
- int get() { return value_; }
-
- private:
- // self_ptr_ should always point to 'this' -- that's how we can be sure the
- // constructor has been called.
- ConstructionTester* self_ptr_;
- int value_;
-};
-
-int ConstructionTester::constructions = 0;
-int ConstructionTester::destructions = 0;
-
-// ThreeInts will initialize its three ints to the value stored in
-// ThreeInts::counter. The constructor increments counter so that each object
-// in an array of ThreeInts will have different values.
-class ThreeInts {
- public:
- ThreeInts() {
- x_ = counter;
- y_ = counter;
- z_ = counter;
- ++counter;
- }
-
- static int counter;
-
- int x_, y_, z_;
-};
-
-int ThreeInts::counter = 0;
-
-TEST(FixedArrayTest, CopyCtor) {
- absl::FixedArray<int, 10> on_stack(5);
- std::iota(on_stack.begin(), on_stack.end(), 0);
- absl::FixedArray<int, 10> stack_copy = on_stack;
- EXPECT_THAT(stack_copy, ElementsAreArray(on_stack));
- EXPECT_TRUE(IsOnStack(stack_copy));
-
- absl::FixedArray<int, 10> allocated(15);
- std::iota(allocated.begin(), allocated.end(), 0);
- absl::FixedArray<int, 10> alloced_copy = allocated;
- EXPECT_THAT(alloced_copy, ElementsAreArray(allocated));
- EXPECT_FALSE(IsOnStack(alloced_copy));
-}
-
-TEST(FixedArrayTest, MoveCtor) {
- absl::FixedArray<std::unique_ptr<int>, 10> on_stack(5);
- for (int i = 0; i < 5; ++i) {
- on_stack[i] = absl::make_unique<int>(i);
- }
-
- absl::FixedArray<std::unique_ptr<int>, 10> stack_copy = std::move(on_stack);
- for (int i = 0; i < 5; ++i) EXPECT_EQ(*(stack_copy[i]), i);
- EXPECT_EQ(stack_copy.size(), on_stack.size());
-
- absl::FixedArray<std::unique_ptr<int>, 10> allocated(15);
- for (int i = 0; i < 15; ++i) {
- allocated[i] = absl::make_unique<int>(i);
- }
-
- absl::FixedArray<std::unique_ptr<int>, 10> alloced_copy =
- std::move(allocated);
- for (int i = 0; i < 15; ++i) EXPECT_EQ(*(alloced_copy[i]), i);
- EXPECT_EQ(allocated.size(), alloced_copy.size());
-}
-
-TEST(FixedArrayTest, SmallObjects) {
- // Small object arrays
- {
- // Short arrays should be on the stack
- absl::FixedArray<int> array(4);
- EXPECT_TRUE(IsOnStack(array));
- }
-
- {
- // Large arrays should be on the heap
- absl::FixedArray<int> array(1048576);
- EXPECT_FALSE(IsOnStack(array));
- }
-
- {
- // Arrays of <= default size should be on the stack
- absl::FixedArray<int, 100> array(100);
- EXPECT_TRUE(IsOnStack(array));
- }
-
- {
- // Arrays of > default size should be on the heap
- absl::FixedArray<int, 100> array(101);
- EXPECT_FALSE(IsOnStack(array));
- }
-
- {
- // Arrays with different size elements should use approximately
- // same amount of stack space
- absl::FixedArray<int> array1(0);
- absl::FixedArray<char> array2(0);
- EXPECT_LE(sizeof(array1), sizeof(array2) + 100);
- EXPECT_LE(sizeof(array2), sizeof(array1) + 100);
- }
-
- {
- // Ensure that vectors are properly constructed inside a fixed array.
- absl::FixedArray<std::vector<int>> array(2);
- EXPECT_EQ(0, array[0].size());
- EXPECT_EQ(0, array[1].size());
- }
-
- {
- // Regardless of absl::FixedArray implementation, check that a type with a
- // low alignment requirement and a non power-of-two size is initialized
- // correctly.
- ThreeInts::counter = 1;
- absl::FixedArray<ThreeInts> array(2);
- EXPECT_EQ(1, array[0].x_);
- EXPECT_EQ(1, array[0].y_);
- EXPECT_EQ(1, array[0].z_);
- EXPECT_EQ(2, array[1].x_);
- EXPECT_EQ(2, array[1].y_);
- EXPECT_EQ(2, array[1].z_);
- }
-}
-
-TEST(FixedArrayTest, AtThrows) {
- absl::FixedArray<int> a = {1, 2, 3};
- EXPECT_EQ(a.at(2), 3);
- ABSL_BASE_INTERNAL_EXPECT_FAIL(a.at(3), std::out_of_range,
- "failed bounds check");
-}
-
-TEST(FixedArrayTest, Hardened) {
-#if !defined(NDEBUG) || ABSL_OPTION_HARDENED
- absl::FixedArray<int> a = {1, 2, 3};
- EXPECT_EQ(a[2], 3);
- EXPECT_DEATH_IF_SUPPORTED(a[3], "");
- EXPECT_DEATH_IF_SUPPORTED(a[-1], "");
-
- absl::FixedArray<int> empty(0);
- EXPECT_DEATH_IF_SUPPORTED(empty[0], "");
- EXPECT_DEATH_IF_SUPPORTED(empty[-1], "");
- EXPECT_DEATH_IF_SUPPORTED(empty.front(), "");
- EXPECT_DEATH_IF_SUPPORTED(empty.back(), "");
-#endif
-}
-
-TEST(FixedArrayRelationalsTest, EqualArrays) {
- for (int i = 0; i < 10; ++i) {
- absl::FixedArray<int, 5> a1(i);
- std::iota(a1.begin(), a1.end(), 0);
- absl::FixedArray<int, 5> a2(a1.begin(), a1.end());
-
- EXPECT_TRUE(a1 == a2);
- EXPECT_FALSE(a1 != a2);
- EXPECT_TRUE(a2 == a1);
- EXPECT_FALSE(a2 != a1);
- EXPECT_FALSE(a1 < a2);
- EXPECT_FALSE(a1 > a2);
- EXPECT_FALSE(a2 < a1);
- EXPECT_FALSE(a2 > a1);
- EXPECT_TRUE(a1 <= a2);
- EXPECT_TRUE(a1 >= a2);
- EXPECT_TRUE(a2 <= a1);
- EXPECT_TRUE(a2 >= a1);
- }
-}
-
-TEST(FixedArrayRelationalsTest, UnequalArrays) {
- for (int i = 1; i < 10; ++i) {
- absl::FixedArray<int, 5> a1(i);
- std::iota(a1.begin(), a1.end(), 0);
- absl::FixedArray<int, 5> a2(a1.begin(), a1.end());
- --a2[i / 2];
-
- EXPECT_FALSE(a1 == a2);
- EXPECT_TRUE(a1 != a2);
- EXPECT_FALSE(a2 == a1);
- EXPECT_TRUE(a2 != a1);
- EXPECT_FALSE(a1 < a2);
- EXPECT_TRUE(a1 > a2);
- EXPECT_TRUE(a2 < a1);
- EXPECT_FALSE(a2 > a1);
- EXPECT_FALSE(a1 <= a2);
- EXPECT_TRUE(a1 >= a2);
- EXPECT_TRUE(a2 <= a1);
- EXPECT_FALSE(a2 >= a1);
- }
-}
-
-template <int stack_elements>
-static void TestArray(int n) {
- SCOPED_TRACE(n);
- SCOPED_TRACE(stack_elements);
- ConstructionTester::constructions = 0;
- ConstructionTester::destructions = 0;
- {
- absl::FixedArray<ConstructionTester, stack_elements> array(n);
-
- EXPECT_THAT(array.size(), n);
- EXPECT_THAT(array.memsize(), sizeof(ConstructionTester) * n);
- EXPECT_THAT(array.begin() + n, array.end());
-
- // Check that all elements were constructed
- for (int i = 0; i < n; i++) {
- array[i].CheckConstructed();
- }
- // Check that no other elements were constructed
- EXPECT_THAT(ConstructionTester::constructions, n);
-
- // Test operator[]
- for (int i = 0; i < n; i++) {
- array[i].set(i);
- }
- for (int i = 0; i < n; i++) {
- EXPECT_THAT(array[i].get(), i);
- EXPECT_THAT(array.data()[i].get(), i);
- }
-
- // Test data()
- for (int i = 0; i < n; i++) {
- array.data()[i].set(i + 1);
- }
- for (int i = 0; i < n; i++) {
- EXPECT_THAT(array[i].get(), i + 1);
- EXPECT_THAT(array.data()[i].get(), i + 1);
- }
- } // Close scope containing 'array'.
-
- // Check that all constructed elements were destructed.
- EXPECT_EQ(ConstructionTester::constructions,
- ConstructionTester::destructions);
-}
-
-template <int elements_per_inner_array, int inline_elements>
-static void TestArrayOfArrays(int n) {
- SCOPED_TRACE(n);
- SCOPED_TRACE(inline_elements);
- SCOPED_TRACE(elements_per_inner_array);
- ConstructionTester::constructions = 0;
- ConstructionTester::destructions = 0;
- {
- using InnerArray = ConstructionTester[elements_per_inner_array];
- // Heap-allocate the FixedArray to avoid blowing the stack frame.
- auto array_ptr =
- absl::make_unique<absl::FixedArray<InnerArray, inline_elements>>(n);
- auto& array = *array_ptr;
-
- ASSERT_EQ(array.size(), n);
- ASSERT_EQ(array.memsize(),
- sizeof(ConstructionTester) * elements_per_inner_array * n);
- ASSERT_EQ(array.begin() + n, array.end());
-
- // Check that all elements were constructed
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < elements_per_inner_array; j++) {
- (array[i])[j].CheckConstructed();
- }
- }
- // Check that no other elements were constructed
- ASSERT_EQ(ConstructionTester::constructions, n * elements_per_inner_array);
-
- // Test operator[]
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < elements_per_inner_array; j++) {
- (array[i])[j].set(i * elements_per_inner_array + j);
- }
- }
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < elements_per_inner_array; j++) {
- ASSERT_EQ((array[i])[j].get(), i * elements_per_inner_array + j);
- ASSERT_EQ((array.data()[i])[j].get(), i * elements_per_inner_array + j);
- }
- }
-
- // Test data()
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < elements_per_inner_array; j++) {
- (array.data()[i])[j].set((i + 1) * elements_per_inner_array + j);
- }
- }
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < elements_per_inner_array; j++) {
- ASSERT_EQ((array[i])[j].get(), (i + 1) * elements_per_inner_array + j);
- ASSERT_EQ((array.data()[i])[j].get(),
- (i + 1) * elements_per_inner_array + j);
- }
- }
- } // Close scope containing 'array'.
-
- // Check that all constructed elements were destructed.
- EXPECT_EQ(ConstructionTester::constructions,
- ConstructionTester::destructions);
-}
-
-TEST(IteratorConstructorTest, NonInline) {
- int const kInput[] = {2, 3, 5, 7, 11, 13, 17};
- absl::FixedArray<int, ABSL_ARRAYSIZE(kInput) - 1> const fixed(
- kInput, kInput + ABSL_ARRAYSIZE(kInput));
- ASSERT_EQ(ABSL_ARRAYSIZE(kInput), fixed.size());
- for (size_t i = 0; i < ABSL_ARRAYSIZE(kInput); ++i) {
- ASSERT_EQ(kInput[i], fixed[i]);
- }
-}
-
-TEST(IteratorConstructorTest, Inline) {
- int const kInput[] = {2, 3, 5, 7, 11, 13, 17};
- absl::FixedArray<int, ABSL_ARRAYSIZE(kInput)> const fixed(
- kInput, kInput + ABSL_ARRAYSIZE(kInput));
- ASSERT_EQ(ABSL_ARRAYSIZE(kInput), fixed.size());
- for (size_t i = 0; i < ABSL_ARRAYSIZE(kInput); ++i) {
- ASSERT_EQ(kInput[i], fixed[i]);
- }
-}
-
-TEST(IteratorConstructorTest, NonPod) {
- char const* kInput[] = {"red", "orange", "yellow", "green",
- "blue", "indigo", "violet"};
- absl::FixedArray<std::string> const fixed(kInput,
- kInput + ABSL_ARRAYSIZE(kInput));
- ASSERT_EQ(ABSL_ARRAYSIZE(kInput), fixed.size());
- for (size_t i = 0; i < ABSL_ARRAYSIZE(kInput); ++i) {
- ASSERT_EQ(kInput[i], fixed[i]);
- }
-}
-
-TEST(IteratorConstructorTest, FromEmptyVector) {
- std::vector<int> const empty;
- absl::FixedArray<int> const fixed(empty.begin(), empty.end());
- EXPECT_EQ(0, fixed.size());
- EXPECT_EQ(empty.size(), fixed.size());
-}
-
-TEST(IteratorConstructorTest, FromNonEmptyVector) {
- int const kInput[] = {2, 3, 5, 7, 11, 13, 17};
- std::vector<int> const items(kInput, kInput + ABSL_ARRAYSIZE(kInput));
- absl::FixedArray<int> const fixed(items.begin(), items.end());
- ASSERT_EQ(items.size(), fixed.size());
- for (size_t i = 0; i < items.size(); ++i) {
- ASSERT_EQ(items[i], fixed[i]);
- }
-}
-
-TEST(IteratorConstructorTest, FromBidirectionalIteratorRange) {
- int const kInput[] = {2, 3, 5, 7, 11, 13, 17};
- std::list<int> const items(kInput, kInput + ABSL_ARRAYSIZE(kInput));
- absl::FixedArray<int> const fixed(items.begin(), items.end());
- EXPECT_THAT(fixed, testing::ElementsAreArray(kInput));
-}
-
-TEST(InitListConstructorTest, InitListConstruction) {
- absl::FixedArray<int> fixed = {1, 2, 3};
- EXPECT_THAT(fixed, testing::ElementsAreArray({1, 2, 3}));
-}
-
-TEST(FillConstructorTest, NonEmptyArrays) {
- absl::FixedArray<int> stack_array(4, 1);
- EXPECT_THAT(stack_array, testing::ElementsAreArray({1, 1, 1, 1}));
-
- absl::FixedArray<int, 0> heap_array(4, 1);
- EXPECT_THAT(stack_array, testing::ElementsAreArray({1, 1, 1, 1}));
-}
-
-TEST(FillConstructorTest, EmptyArray) {
- absl::FixedArray<int> empty_fill(0, 1);
- absl::FixedArray<int> empty_size(0);
- EXPECT_EQ(empty_fill, empty_size);
-}
-
-TEST(FillConstructorTest, NotTriviallyCopyable) {
- std::string str = "abcd";
- absl::FixedArray<std::string> strings = {str, str, str, str};
-
- absl::FixedArray<std::string> array(4, str);
- EXPECT_EQ(array, strings);
-}
-
-TEST(FillConstructorTest, Disambiguation) {
- absl::FixedArray<size_t> a(1, 2);
- EXPECT_THAT(a, testing::ElementsAre(2));
-}
-
-TEST(FixedArrayTest, ManySizedArrays) {
- std::vector<int> sizes;
- for (int i = 1; i < 100; i++) sizes.push_back(i);
- for (int i = 100; i <= 1000; i += 100) sizes.push_back(i);
- for (int n : sizes) {
- TestArray<0>(n);
- TestArray<1>(n);
- TestArray<64>(n);
- TestArray<1000>(n);
- }
-}
-
-TEST(FixedArrayTest, ManySizedArraysOfArraysOf1) {
- for (int n = 1; n < 1000; n++) {
- ASSERT_NO_FATAL_FAILURE((TestArrayOfArrays<1, 0>(n)));
- ASSERT_NO_FATAL_FAILURE((TestArrayOfArrays<1, 1>(n)));
- ASSERT_NO_FATAL_FAILURE((TestArrayOfArrays<1, 64>(n)));
- ASSERT_NO_FATAL_FAILURE((TestArrayOfArrays<1, 1000>(n)));
- }
-}
-
-TEST(FixedArrayTest, ManySizedArraysOfArraysOf2) {
- for (int n = 1; n < 1000; n++) {
- TestArrayOfArrays<2, 0>(n);
- TestArrayOfArrays<2, 1>(n);
- TestArrayOfArrays<2, 64>(n);
- TestArrayOfArrays<2, 1000>(n);
- }
-}
-
-// If value_type is put inside of a struct container,
-// we might evoke this error in a hardened build unless data() is carefully
-// written, so check on that.
-// error: call to int __builtin___sprintf_chk(etc...)
-// will always overflow destination buffer [-Werror]
-TEST(FixedArrayTest, AvoidParanoidDiagnostics) {
- absl::FixedArray<char, 32> buf(32);
- sprintf(buf.data(), "foo"); // NOLINT(runtime/printf)
-}
-
-TEST(FixedArrayTest, TooBigInlinedSpace) {
- struct TooBig {
- char c[1 << 20];
- }; // too big for even one on the stack
-
- // Simulate the data members of absl::FixedArray, a pointer and a size_t.
- struct Data {
- TooBig* p;
- size_t size;
- };
-
- // Make sure TooBig objects are not inlined for 0 or default size.
- static_assert(sizeof(absl::FixedArray<TooBig, 0>) == sizeof(Data),
- "0-sized absl::FixedArray should have same size as Data.");
- static_assert(alignof(absl::FixedArray<TooBig, 0>) == alignof(Data),
- "0-sized absl::FixedArray should have same alignment as Data.");
- static_assert(sizeof(absl::FixedArray<TooBig>) == sizeof(Data),
- "default-sized absl::FixedArray should have same size as Data");
- static_assert(
- alignof(absl::FixedArray<TooBig>) == alignof(Data),
- "default-sized absl::FixedArray should have same alignment as Data.");
-}
-
-// PickyDelete EXPECTs its class-scope deallocation funcs are unused.
-struct PickyDelete {
- PickyDelete() {}
- ~PickyDelete() {}
- void operator delete(void* p) {
- EXPECT_TRUE(false) << __FUNCTION__;
- ::operator delete(p);
- }
- void operator delete[](void* p) {
- EXPECT_TRUE(false) << __FUNCTION__;
- ::operator delete[](p);
- }
-};
-
-TEST(FixedArrayTest, UsesGlobalAlloc) { absl::FixedArray<PickyDelete, 0> a(5); }
-
-TEST(FixedArrayTest, Data) {
- static const int kInput[] = {2, 3, 5, 7, 11, 13, 17};
- absl::FixedArray<int> fa(std::begin(kInput), std::end(kInput));
- EXPECT_EQ(fa.data(), &*fa.begin());
- EXPECT_EQ(fa.data(), &fa[0]);
-
- const absl::FixedArray<int>& cfa = fa;
- EXPECT_EQ(cfa.data(), &*cfa.begin());
- EXPECT_EQ(cfa.data(), &cfa[0]);
-}
-
-TEST(FixedArrayTest, Empty) {
- absl::FixedArray<int> empty(0);
- absl::FixedArray<int> inline_filled(1);
- absl::FixedArray<int, 0> heap_filled(1);
- EXPECT_TRUE(empty.empty());
- EXPECT_FALSE(inline_filled.empty());
- EXPECT_FALSE(heap_filled.empty());
-}
-
-TEST(FixedArrayTest, FrontAndBack) {
- absl::FixedArray<int, 3 * sizeof(int)> inlined = {1, 2, 3};
- EXPECT_EQ(inlined.front(), 1);
- EXPECT_EQ(inlined.back(), 3);
-
- absl::FixedArray<int, 0> allocated = {1, 2, 3};
- EXPECT_EQ(allocated.front(), 1);
- EXPECT_EQ(allocated.back(), 3);
-
- absl::FixedArray<int> one_element = {1};
- EXPECT_EQ(one_element.front(), one_element.back());
-}
-
-TEST(FixedArrayTest, ReverseIteratorInlined) {
- absl::FixedArray<int, 5 * sizeof(int)> a = {0, 1, 2, 3, 4};
-
- int counter = 5;
- for (absl::FixedArray<int>::reverse_iterator iter = a.rbegin();
- iter != a.rend(); ++iter) {
- counter--;
- EXPECT_EQ(counter, *iter);
- }
- EXPECT_EQ(counter, 0);
-
- counter = 5;
- for (absl::FixedArray<int>::const_reverse_iterator iter = a.rbegin();
- iter != a.rend(); ++iter) {
- counter--;
- EXPECT_EQ(counter, *iter);
- }
- EXPECT_EQ(counter, 0);
-
- counter = 5;
- for (auto iter = a.crbegin(); iter != a.crend(); ++iter) {
- counter--;
- EXPECT_EQ(counter, *iter);
- }
- EXPECT_EQ(counter, 0);
-}
-
-TEST(FixedArrayTest, ReverseIteratorAllocated) {
- absl::FixedArray<int, 0> a = {0, 1, 2, 3, 4};
-
- int counter = 5;
- for (absl::FixedArray<int>::reverse_iterator iter = a.rbegin();
- iter != a.rend(); ++iter) {
- counter--;
- EXPECT_EQ(counter, *iter);
- }
- EXPECT_EQ(counter, 0);
-
- counter = 5;
- for (absl::FixedArray<int>::const_reverse_iterator iter = a.rbegin();
- iter != a.rend(); ++iter) {
- counter--;
- EXPECT_EQ(counter, *iter);
- }
- EXPECT_EQ(counter, 0);
-
- counter = 5;
- for (auto iter = a.crbegin(); iter != a.crend(); ++iter) {
- counter--;
- EXPECT_EQ(counter, *iter);
- }
- EXPECT_EQ(counter, 0);
-}
-
-TEST(FixedArrayTest, Fill) {
- absl::FixedArray<int, 5 * sizeof(int)> inlined(5);
- int fill_val = 42;
- inlined.fill(fill_val);
- for (int i : inlined) EXPECT_EQ(i, fill_val);
-
- absl::FixedArray<int, 0> allocated(5);
- allocated.fill(fill_val);
- for (int i : allocated) EXPECT_EQ(i, fill_val);
-
- // It doesn't do anything, just make sure this compiles.
- absl::FixedArray<int> empty(0);
- empty.fill(fill_val);
-}
-
-#ifndef __GNUC__
-TEST(FixedArrayTest, DefaultCtorDoesNotValueInit) {
- using T = char;
- constexpr auto capacity = 10;
- using FixedArrType = absl::FixedArray<T, capacity>;
- constexpr auto scrubbed_bits = 0x95;
- constexpr auto length = capacity / 2;
-
- alignas(FixedArrType) unsigned char buff[sizeof(FixedArrType)];
- std::memset(std::addressof(buff), scrubbed_bits, sizeof(FixedArrType));
-
- FixedArrType* arr =
- ::new (static_cast<void*>(std::addressof(buff))) FixedArrType(length);
- EXPECT_THAT(*arr, testing::Each(scrubbed_bits));
- arr->~FixedArrType();
-}
-#endif // __GNUC__
-
-TEST(AllocatorSupportTest, CountInlineAllocations) {
- constexpr size_t inlined_size = 4;
- using Alloc = absl::container_internal::CountingAllocator<int>;
- using AllocFxdArr = absl::FixedArray<int, inlined_size, Alloc>;
-
- int64_t allocated = 0;
- int64_t active_instances = 0;
-
- {
- const int ia[] = {0, 1, 2, 3, 4, 5, 6, 7};
-
- Alloc alloc(&allocated, &active_instances);
-
- AllocFxdArr arr(ia, ia + inlined_size, alloc);
- static_cast<void>(arr);
- }
-
- EXPECT_EQ(allocated, 0);
- EXPECT_EQ(active_instances, 0);
-}
-
-TEST(AllocatorSupportTest, CountOutoflineAllocations) {
- constexpr size_t inlined_size = 4;
- using Alloc = absl::container_internal::CountingAllocator<int>;
- using AllocFxdArr = absl::FixedArray<int, inlined_size, Alloc>;
-
- int64_t allocated = 0;
- int64_t active_instances = 0;
-
- {
- const int ia[] = {0, 1, 2, 3, 4, 5, 6, 7};
- Alloc alloc(&allocated, &active_instances);
-
- AllocFxdArr arr(ia, ia + ABSL_ARRAYSIZE(ia), alloc);
-
- EXPECT_EQ(allocated, arr.size() * sizeof(int));
- static_cast<void>(arr);
- }
-
- EXPECT_EQ(active_instances, 0);
-}
-
-TEST(AllocatorSupportTest, CountCopyInlineAllocations) {
- constexpr size_t inlined_size = 4;
- using Alloc = absl::container_internal::CountingAllocator<int>;
- using AllocFxdArr = absl::FixedArray<int, inlined_size, Alloc>;
-
- int64_t allocated1 = 0;
- int64_t allocated2 = 0;
- int64_t active_instances = 0;
- Alloc alloc(&allocated1, &active_instances);
- Alloc alloc2(&allocated2, &active_instances);
-
- {
- int initial_value = 1;
-
- AllocFxdArr arr1(inlined_size / 2, initial_value, alloc);
-
- EXPECT_EQ(allocated1, 0);
-
- AllocFxdArr arr2(arr1, alloc2);
-
- EXPECT_EQ(allocated2, 0);
- static_cast<void>(arr1);
- static_cast<void>(arr2);
- }
-
- EXPECT_EQ(active_instances, 0);
-}
-
-TEST(AllocatorSupportTest, CountCopyOutoflineAllocations) {
- constexpr size_t inlined_size = 4;
- using Alloc = absl::container_internal::CountingAllocator<int>;
- using AllocFxdArr = absl::FixedArray<int, inlined_size, Alloc>;
-
- int64_t allocated1 = 0;
- int64_t allocated2 = 0;
- int64_t active_instances = 0;
- Alloc alloc(&allocated1, &active_instances);
- Alloc alloc2(&allocated2, &active_instances);
-
- {
- int initial_value = 1;
-
- AllocFxdArr arr1(inlined_size * 2, initial_value, alloc);
-
- EXPECT_EQ(allocated1, arr1.size() * sizeof(int));
-
- AllocFxdArr arr2(arr1, alloc2);
-
- EXPECT_EQ(allocated2, inlined_size * 2 * sizeof(int));
- static_cast<void>(arr1);
- static_cast<void>(arr2);
- }
-
- EXPECT_EQ(active_instances, 0);
-}
-
-TEST(AllocatorSupportTest, SizeValAllocConstructor) {
- using testing::AllOf;
- using testing::Each;
- using testing::SizeIs;
-
- constexpr size_t inlined_size = 4;
- using Alloc = absl::container_internal::CountingAllocator<int>;
- using AllocFxdArr = absl::FixedArray<int, inlined_size, Alloc>;
-
- {
- auto len = inlined_size / 2;
- auto val = 0;
- int64_t allocated = 0;
- AllocFxdArr arr(len, val, Alloc(&allocated));
-
- EXPECT_EQ(allocated, 0);
- EXPECT_THAT(arr, AllOf(SizeIs(len), Each(0)));
- }
-
- {
- auto len = inlined_size * 2;
- auto val = 0;
- int64_t allocated = 0;
- AllocFxdArr arr(len, val, Alloc(&allocated));
-
- EXPECT_EQ(allocated, len * sizeof(int));
- EXPECT_THAT(arr, AllOf(SizeIs(len), Each(0)));
- }
-}
-
-#ifdef ABSL_HAVE_ADDRESS_SANITIZER
-TEST(FixedArrayTest, AddressSanitizerAnnotations1) {
- absl::FixedArray<int, 32> a(10);
- int* raw = a.data();
- raw[0] = 0;
- raw[9] = 0;
- EXPECT_DEATH_IF_SUPPORTED(raw[-2] = 0, "container-overflow");
- EXPECT_DEATH_IF_SUPPORTED(raw[-1] = 0, "container-overflow");
- EXPECT_DEATH_IF_SUPPORTED(raw[10] = 0, "container-overflow");
- EXPECT_DEATH_IF_SUPPORTED(raw[31] = 0, "container-overflow");
-}
-
-TEST(FixedArrayTest, AddressSanitizerAnnotations2) {
- absl::FixedArray<char, 17> a(12);
- char* raw = a.data();
- raw[0] = 0;
- raw[11] = 0;
- EXPECT_DEATH_IF_SUPPORTED(raw[-7] = 0, "container-overflow");
- EXPECT_DEATH_IF_SUPPORTED(raw[-1] = 0, "container-overflow");
- EXPECT_DEATH_IF_SUPPORTED(raw[12] = 0, "container-overflow");
- EXPECT_DEATH_IF_SUPPORTED(raw[17] = 0, "container-overflow");
-}
-
-TEST(FixedArrayTest, AddressSanitizerAnnotations3) {
- absl::FixedArray<uint64_t, 20> a(20);
- uint64_t* raw = a.data();
- raw[0] = 0;
- raw[19] = 0;
- EXPECT_DEATH_IF_SUPPORTED(raw[-1] = 0, "container-overflow");
- EXPECT_DEATH_IF_SUPPORTED(raw[20] = 0, "container-overflow");
-}
-
-TEST(FixedArrayTest, AddressSanitizerAnnotations4) {
- absl::FixedArray<ThreeInts> a(10);
- ThreeInts* raw = a.data();
- raw[0] = ThreeInts();
- raw[9] = ThreeInts();
- // Note: raw[-1] is pointing to 12 bytes before the container range. However,
- // there is only a 8-byte red zone before the container range, so we only
- // access the last 4 bytes of the struct to make sure it stays within the red
- // zone.
- EXPECT_DEATH_IF_SUPPORTED(raw[-1].z_ = 0, "container-overflow");
- EXPECT_DEATH_IF_SUPPORTED(raw[10] = ThreeInts(), "container-overflow");
- // The actual size of storage is kDefaultBytes=256, 21*12 = 252,
- // so reading raw[21] should still trigger the correct warning.
- EXPECT_DEATH_IF_SUPPORTED(raw[21] = ThreeInts(), "container-overflow");
-}
-#endif // ABSL_HAVE_ADDRESS_SANITIZER
-
-TEST(FixedArrayTest, AbslHashValueWorks) {
- using V = absl::FixedArray<int>;
- std::vector<V> cases;
-
- // Generate a variety of vectors some of these are small enough for the inline
- // space but are stored out of line.
- for (int i = 0; i < 10; ++i) {
- V v(i);
- for (int j = 0; j < i; ++j) {
- v[j] = j;
- }
- cases.push_back(v);
- }
-
- EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(cases));
-}
-
-} // namespace
diff --git a/third_party/abseil-cpp/absl/container/flat_hash_map.h b/third_party/abseil-cpp/absl/container/flat_hash_map.h
deleted file mode 100644
index e6bdbd9..0000000
--- a/third_party/abseil-cpp/absl/container/flat_hash_map.h
+++ /dev/null
@@ -1,613 +0,0 @@
-// Copyright 2018 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.
-//
-// -----------------------------------------------------------------------------
-// File: flat_hash_map.h
-// -----------------------------------------------------------------------------
-//
-// An `absl::flat_hash_map<K, V>` is an unordered associative container of
-// unique keys and associated values designed to be a more efficient replacement
-// for `std::unordered_map`. Like `unordered_map`, search, insertion, and
-// deletion of map elements can be done as an `O(1)` operation. However,
-// `flat_hash_map` (and other unordered associative containers known as the
-// collection of Abseil "Swiss tables") contain other optimizations that result
-// in both memory and computation advantages.
-//
-// In most cases, your default choice for a hash map should be a map of type
-// `flat_hash_map`.
-
-#ifndef ABSL_CONTAINER_FLAT_HASH_MAP_H_
-#define ABSL_CONTAINER_FLAT_HASH_MAP_H_
-
-#include <cstddef>
-#include <new>
-#include <type_traits>
-#include <utility>
-
-#include "absl/algorithm/container.h"
-#include "absl/base/macros.h"
-#include "absl/container/internal/container_memory.h"
-#include "absl/container/internal/hash_function_defaults.h" // IWYU pragma: export
-#include "absl/container/internal/raw_hash_map.h" // IWYU pragma: export
-#include "absl/memory/memory.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-template <class K, class V>
-struct FlatHashMapPolicy;
-} // namespace container_internal
-
-// -----------------------------------------------------------------------------
-// absl::flat_hash_map
-// -----------------------------------------------------------------------------
-//
-// An `absl::flat_hash_map<K, V>` is an unordered associative container which
-// has been optimized for both speed and memory footprint in most common use
-// cases. Its interface is similar to that of `std::unordered_map<K, V>` with
-// the following notable differences:
-//
-// * Requires keys that are CopyConstructible
-// * Requires values that are MoveConstructible
-// * Supports heterogeneous lookup, through `find()`, `operator[]()` and
-// `insert()`, provided that the map is provided a compatible heterogeneous
-// hashing function and equality operator.
-// * Invalidates any references and pointers to elements within the table after
-// `rehash()`.
-// * Contains a `capacity()` member function indicating the number of element
-// slots (open, deleted, and empty) within the hash map.
-// * Returns `void` from the `erase(iterator)` overload.
-//
-// By default, `flat_hash_map` uses the `absl::Hash` hashing framework.
-// All fundamental and Abseil types that support the `absl::Hash` framework have
-// a compatible equality operator for comparing insertions into `flat_hash_map`.
-// If your type is not yet supported by the `absl::Hash` framework, see
-// absl/hash/hash.h for information on extending Abseil hashing to user-defined
-// types.
-//
-// Using `absl::flat_hash_map` at interface boundaries in dynamically loaded
-// libraries (e.g. .dll, .so) is unsupported due to way `absl::Hash` values may
-// be randomized across dynamically loaded libraries.
-//
-// NOTE: A `flat_hash_map` stores its value types directly inside its
-// implementation array to avoid memory indirection. Because a `flat_hash_map`
-// is designed to move data when rehashed, map values will not retain pointer
-// stability. If you require pointer stability, or if your values are large,
-// consider using `absl::flat_hash_map<Key, std::unique_ptr<Value>>` instead.
-// If your types are not moveable or you require pointer stability for keys,
-// consider `absl::node_hash_map`.
-//
-// Example:
-//
-// // Create a flat hash map of three strings (that map to strings)
-// absl::flat_hash_map<std::string, std::string> ducks =
-// {{"a", "huey"}, {"b", "dewey"}, {"c", "louie"}};
-//
-// // Insert a new element into the flat hash map
-// ducks.insert({"d", "donald"});
-//
-// // Force a rehash of the flat hash map
-// ducks.rehash(0);
-//
-// // Find the element with the key "b"
-// std::string search_key = "b";
-// auto result = ducks.find(search_key);
-// if (result != ducks.end()) {
-// std::cout << "Result: " << result->second << std::endl;
-// }
-template <class K, class V,
- class Hash = absl::container_internal::hash_default_hash<K>,
- class Eq = absl::container_internal::hash_default_eq<K>,
- class Allocator = std::allocator<std::pair<const K, V>>>
-class flat_hash_map : public absl::container_internal::raw_hash_map<
- absl::container_internal::FlatHashMapPolicy<K, V>,
- Hash, Eq, Allocator> {
- using Base = typename flat_hash_map::raw_hash_map;
-
- public:
- // Constructors and Assignment Operators
- //
- // A flat_hash_map supports the same overload set as `std::unordered_map`
- // for construction and assignment:
- //
- // * Default constructor
- //
- // // No allocation for the table's elements is made.
- // absl::flat_hash_map<int, std::string> map1;
- //
- // * Initializer List constructor
- //
- // absl::flat_hash_map<int, std::string> map2 =
- // {{1, "huey"}, {2, "dewey"}, {3, "louie"},};
- //
- // * Copy constructor
- //
- // absl::flat_hash_map<int, std::string> map3(map2);
- //
- // * Copy assignment operator
- //
- // // Hash functor and Comparator are copied as well
- // absl::flat_hash_map<int, std::string> map4;
- // map4 = map3;
- //
- // * Move constructor
- //
- // // Move is guaranteed efficient
- // absl::flat_hash_map<int, std::string> map5(std::move(map4));
- //
- // * Move assignment operator
- //
- // // May be efficient if allocators are compatible
- // absl::flat_hash_map<int, std::string> map6;
- // map6 = std::move(map5);
- //
- // * Range constructor
- //
- // std::vector<std::pair<int, std::string>> v = {{1, "a"}, {2, "b"}};
- // absl::flat_hash_map<int, std::string> map7(v.begin(), v.end());
- flat_hash_map() {}
- using Base::Base;
-
- // flat_hash_map::begin()
- //
- // Returns an iterator to the beginning of the `flat_hash_map`.
- using Base::begin;
-
- // flat_hash_map::cbegin()
- //
- // Returns a const iterator to the beginning of the `flat_hash_map`.
- using Base::cbegin;
-
- // flat_hash_map::cend()
- //
- // Returns a const iterator to the end of the `flat_hash_map`.
- using Base::cend;
-
- // flat_hash_map::end()
- //
- // Returns an iterator to the end of the `flat_hash_map`.
- using Base::end;
-
- // flat_hash_map::capacity()
- //
- // Returns the number of element slots (assigned, deleted, and empty)
- // available within the `flat_hash_map`.
- //
- // NOTE: this member function is particular to `absl::flat_hash_map` and is
- // not provided in the `std::unordered_map` API.
- using Base::capacity;
-
- // flat_hash_map::empty()
- //
- // Returns whether or not the `flat_hash_map` is empty.
- using Base::empty;
-
- // flat_hash_map::max_size()
- //
- // Returns the largest theoretical possible number of elements within a
- // `flat_hash_map` under current memory constraints. This value can be thought
- // of the largest value of `std::distance(begin(), end())` for a
- // `flat_hash_map<K, V>`.
- using Base::max_size;
-
- // flat_hash_map::size()
- //
- // Returns the number of elements currently within the `flat_hash_map`.
- using Base::size;
-
- // flat_hash_map::clear()
- //
- // Removes all elements from the `flat_hash_map`. Invalidates any references,
- // pointers, or iterators referring to contained elements.
- //
- // NOTE: this operation may shrink the underlying buffer. To avoid shrinking
- // the underlying buffer call `erase(begin(), end())`.
- using Base::clear;
-
- // flat_hash_map::erase()
- //
- // Erases elements within the `flat_hash_map`. Erasing does not trigger a
- // rehash. Overloads are listed below.
- //
- // void erase(const_iterator pos):
- //
- // Erases the element at `position` of the `flat_hash_map`, returning
- // `void`.
- //
- // NOTE: returning `void` in this case is different than that of STL
- // containers in general and `std::unordered_map` in particular (which
- // return an iterator to the element following the erased element). If that
- // iterator is needed, simply post increment the iterator:
- //
- // map.erase(it++);
- //
- // iterator erase(const_iterator first, const_iterator last):
- //
- // Erases the elements in the open interval [`first`, `last`), returning an
- // iterator pointing to `last`.
- //
- // size_type erase(const key_type& key):
- //
- // Erases the element with the matching key, if it exists, returning the
- // number of elements erased (0 or 1).
- using Base::erase;
-
- // flat_hash_map::insert()
- //
- // Inserts an element of the specified value into the `flat_hash_map`,
- // returning an iterator pointing to the newly inserted element, provided that
- // an element with the given key does not already exist. If rehashing occurs
- // due to the insertion, all iterators are invalidated. Overloads are listed
- // below.
- //
- // std::pair<iterator,bool> insert(const init_type& value):
- //
- // Inserts a value into the `flat_hash_map`. Returns a pair consisting of an
- // iterator to the inserted element (or to the element that prevented the
- // insertion) and a bool denoting whether the insertion took place.
- //
- // std::pair<iterator,bool> insert(T&& value):
- // std::pair<iterator,bool> insert(init_type&& value):
- //
- // Inserts a moveable value into the `flat_hash_map`. Returns a pair
- // consisting of an iterator to the inserted element (or to the element that
- // prevented the insertion) and a bool denoting whether the insertion took
- // place.
- //
- // iterator insert(const_iterator hint, const init_type& value):
- // iterator insert(const_iterator hint, T&& value):
- // iterator insert(const_iterator hint, init_type&& value);
- //
- // Inserts a value, using the position of `hint` as a non-binding suggestion
- // for where to begin the insertion search. Returns an iterator to the
- // inserted element, or to the existing element that prevented the
- // insertion.
- //
- // void insert(InputIterator first, InputIterator last):
- //
- // Inserts a range of values [`first`, `last`).
- //
- // NOTE: Although the STL does not specify which element may be inserted if
- // multiple keys compare equivalently, for `flat_hash_map` we guarantee the
- // first match is inserted.
- //
- // void insert(std::initializer_list<init_type> ilist):
- //
- // Inserts the elements within the initializer list `ilist`.
- //
- // NOTE: Although the STL does not specify which element may be inserted if
- // multiple keys compare equivalently within the initializer list, for
- // `flat_hash_map` we guarantee the first match is inserted.
- using Base::insert;
-
- // flat_hash_map::insert_or_assign()
- //
- // Inserts an element of the specified value into the `flat_hash_map` provided
- // that a value with the given key does not already exist, or replaces it with
- // the element value if a key for that value already exists, returning an
- // iterator pointing to the newly inserted element. If rehashing occurs due
- // to the insertion, all existing iterators are invalidated. Overloads are
- // listed below.
- //
- // pair<iterator, bool> insert_or_assign(const init_type& k, T&& obj):
- // pair<iterator, bool> insert_or_assign(init_type&& k, T&& obj):
- //
- // Inserts/Assigns (or moves) the element of the specified key into the
- // `flat_hash_map`.
- //
- // iterator insert_or_assign(const_iterator hint,
- // const init_type& k, T&& obj):
- // iterator insert_or_assign(const_iterator hint, init_type&& k, T&& obj):
- //
- // Inserts/Assigns (or moves) the element of the specified key into the
- // `flat_hash_map` using the position of `hint` as a non-binding suggestion
- // for where to begin the insertion search.
- using Base::insert_or_assign;
-
- // flat_hash_map::emplace()
- //
- // Inserts an element of the specified value by constructing it in-place
- // within the `flat_hash_map`, provided that no element with the given key
- // already exists.
- //
- // The element may be constructed even if there already is an element with the
- // key in the container, in which case the newly constructed element will be
- // destroyed immediately. Prefer `try_emplace()` unless your key is not
- // copyable or moveable.
- //
- // If rehashing occurs due to the insertion, all iterators are invalidated.
- using Base::emplace;
-
- // flat_hash_map::emplace_hint()
- //
- // Inserts an element of the specified value by constructing it in-place
- // within the `flat_hash_map`, using the position of `hint` as a non-binding
- // suggestion for where to begin the insertion search, and only inserts
- // provided that no element with the given key already exists.
- //
- // The element may be constructed even if there already is an element with the
- // key in the container, in which case the newly constructed element will be
- // destroyed immediately. Prefer `try_emplace()` unless your key is not
- // copyable or moveable.
- //
- // If rehashing occurs due to the insertion, all iterators are invalidated.
- using Base::emplace_hint;
-
- // flat_hash_map::try_emplace()
- //
- // Inserts an element of the specified value by constructing it in-place
- // within the `flat_hash_map`, provided that no element with the given key
- // already exists. Unlike `emplace()`, if an element with the given key
- // already exists, we guarantee that no element is constructed.
- //
- // If rehashing occurs due to the insertion, all iterators are invalidated.
- // Overloads are listed below.
- //
- // pair<iterator, bool> try_emplace(const key_type& k, Args&&... args):
- // pair<iterator, bool> try_emplace(key_type&& k, Args&&... args):
- //
- // Inserts (via copy or move) the element of the specified key into the
- // `flat_hash_map`.
- //
- // iterator try_emplace(const_iterator hint,
- // const key_type& k, Args&&... args):
- // iterator try_emplace(const_iterator hint, key_type&& k, Args&&... args):
- //
- // Inserts (via copy or move) the element of the specified key into the
- // `flat_hash_map` using the position of `hint` as a non-binding suggestion
- // for where to begin the insertion search.
- //
- // All `try_emplace()` overloads make the same guarantees regarding rvalue
- // arguments as `std::unordered_map::try_emplace()`, namely that these
- // functions will not move from rvalue arguments if insertions do not happen.
- using Base::try_emplace;
-
- // flat_hash_map::extract()
- //
- // Extracts the indicated element, erasing it in the process, and returns it
- // as a C++17-compatible node handle. Overloads are listed below.
- //
- // node_type extract(const_iterator position):
- //
- // Extracts the key,value pair of the element at the indicated position and
- // returns a node handle owning that extracted data.
- //
- // node_type extract(const key_type& x):
- //
- // Extracts the key,value pair of the element with a key matching the passed
- // key value and returns a node handle owning that extracted data. If the
- // `flat_hash_map` does not contain an element with a matching key, this
- // function returns an empty node handle.
- //
- // NOTE: when compiled in an earlier version of C++ than C++17,
- // `node_type::key()` returns a const reference to the key instead of a
- // mutable reference. We cannot safely return a mutable reference without
- // std::launder (which is not available before C++17).
- using Base::extract;
-
- // flat_hash_map::merge()
- //
- // Extracts elements from a given `source` flat hash map into this
- // `flat_hash_map`. If the destination `flat_hash_map` already contains an
- // element with an equivalent key, that element is not extracted.
- using Base::merge;
-
- // flat_hash_map::swap(flat_hash_map& other)
- //
- // Exchanges the contents of this `flat_hash_map` with those of the `other`
- // flat hash map, avoiding invocation of any move, copy, or swap operations on
- // individual elements.
- //
- // All iterators and references on the `flat_hash_map` remain valid, excepting
- // for the past-the-end iterator, which is invalidated.
- //
- // `swap()` requires that the flat hash map's hashing and key equivalence
- // functions be Swappable, and are exchanged using unqualified calls to
- // non-member `swap()`. If the map's allocator has
- // `std::allocator_traits<allocator_type>::propagate_on_container_swap::value`
- // set to `true`, the allocators are also exchanged using an unqualified call
- // to non-member `swap()`; otherwise, the allocators are not swapped.
- using Base::swap;
-
- // flat_hash_map::rehash(count)
- //
- // Rehashes the `flat_hash_map`, setting the number of slots to be at least
- // the passed value. If the new number of slots increases the load factor more
- // than the current maximum load factor
- // (`count` < `size()` / `max_load_factor()`), then the new number of slots
- // will be at least `size()` / `max_load_factor()`.
- //
- // To force a rehash, pass rehash(0).
- //
- // NOTE: unlike behavior in `std::unordered_map`, references are also
- // invalidated upon a `rehash()`.
- using Base::rehash;
-
- // flat_hash_map::reserve(count)
- //
- // Sets the number of slots in the `flat_hash_map` to the number needed to
- // accommodate at least `count` total elements without exceeding the current
- // maximum load factor, and may rehash the container if needed.
- using Base::reserve;
-
- // flat_hash_map::at()
- //
- // Returns a reference to the mapped value of the element with key equivalent
- // to the passed key.
- using Base::at;
-
- // flat_hash_map::contains()
- //
- // Determines whether an element with a key comparing equal to the given `key`
- // exists within the `flat_hash_map`, returning `true` if so or `false`
- // otherwise.
- using Base::contains;
-
- // flat_hash_map::count(const Key& key) const
- //
- // Returns the number of elements with a key comparing equal to the given
- // `key` within the `flat_hash_map`. note that this function will return
- // either `1` or `0` since duplicate keys are not allowed within a
- // `flat_hash_map`.
- using Base::count;
-
- // flat_hash_map::equal_range()
- //
- // Returns a closed range [first, last], defined by a `std::pair` of two
- // iterators, containing all elements with the passed key in the
- // `flat_hash_map`.
- using Base::equal_range;
-
- // flat_hash_map::find()
- //
- // Finds an element with the passed `key` within the `flat_hash_map`.
- using Base::find;
-
- // flat_hash_map::operator[]()
- //
- // Returns a reference to the value mapped to the passed key within the
- // `flat_hash_map`, performing an `insert()` if the key does not already
- // exist.
- //
- // If an insertion occurs and results in a rehashing of the container, all
- // iterators are invalidated. Otherwise iterators are not affected and
- // references are not invalidated. Overloads are listed below.
- //
- // T& operator[](const Key& key):
- //
- // Inserts an init_type object constructed in-place if the element with the
- // given key does not exist.
- //
- // T& operator[](Key&& key):
- //
- // Inserts an init_type object constructed in-place provided that an element
- // with the given key does not exist.
- using Base::operator[];
-
- // flat_hash_map::bucket_count()
- //
- // Returns the number of "buckets" within the `flat_hash_map`. Note that
- // because a flat hash map contains all elements within its internal storage,
- // this value simply equals the current capacity of the `flat_hash_map`.
- using Base::bucket_count;
-
- // flat_hash_map::load_factor()
- //
- // Returns the current load factor of the `flat_hash_map` (the average number
- // of slots occupied with a value within the hash map).
- using Base::load_factor;
-
- // flat_hash_map::max_load_factor()
- //
- // Manages the maximum load factor of the `flat_hash_map`. Overloads are
- // listed below.
- //
- // float flat_hash_map::max_load_factor()
- //
- // Returns the current maximum load factor of the `flat_hash_map`.
- //
- // void flat_hash_map::max_load_factor(float ml)
- //
- // Sets the maximum load factor of the `flat_hash_map` to the passed value.
- //
- // NOTE: This overload is provided only for API compatibility with the STL;
- // `flat_hash_map` will ignore any set load factor and manage its rehashing
- // internally as an implementation detail.
- using Base::max_load_factor;
-
- // flat_hash_map::get_allocator()
- //
- // Returns the allocator function associated with this `flat_hash_map`.
- using Base::get_allocator;
-
- // flat_hash_map::hash_function()
- //
- // Returns the hashing function used to hash the keys within this
- // `flat_hash_map`.
- using Base::hash_function;
-
- // flat_hash_map::key_eq()
- //
- // Returns the function used for comparing keys equality.
- using Base::key_eq;
-};
-
-// erase_if(flat_hash_map<>, Pred)
-//
-// Erases all elements that satisfy the predicate `pred` from the container `c`.
-// Returns the number of erased elements.
-template <typename K, typename V, typename H, typename E, typename A,
- typename Predicate>
-typename flat_hash_map<K, V, H, E, A>::size_type erase_if(
- flat_hash_map<K, V, H, E, A>& c, Predicate pred) {
- return container_internal::EraseIf(pred, &c);
-}
-
-namespace container_internal {
-
-template <class K, class V>
-struct FlatHashMapPolicy {
- using slot_policy = container_internal::map_slot_policy<K, V>;
- using slot_type = typename slot_policy::slot_type;
- using key_type = K;
- using mapped_type = V;
- using init_type = std::pair</*non const*/ key_type, mapped_type>;
-
- template <class Allocator, class... Args>
- static void construct(Allocator* alloc, slot_type* slot, Args&&... args) {
- slot_policy::construct(alloc, slot, std::forward<Args>(args)...);
- }
-
- template <class Allocator>
- static void destroy(Allocator* alloc, slot_type* slot) {
- slot_policy::destroy(alloc, slot);
- }
-
- template <class Allocator>
- static void transfer(Allocator* alloc, slot_type* new_slot,
- slot_type* old_slot) {
- slot_policy::transfer(alloc, new_slot, old_slot);
- }
-
- template <class F, class... Args>
- static decltype(absl::container_internal::DecomposePair(
- std::declval<F>(), std::declval<Args>()...))
- apply(F&& f, Args&&... args) {
- return absl::container_internal::DecomposePair(std::forward<F>(f),
- std::forward<Args>(args)...);
- }
-
- static size_t space_used(const slot_type*) { return 0; }
-
- static std::pair<const K, V>& element(slot_type* slot) { return slot->value; }
-
- static V& value(std::pair<const K, V>* kv) { return kv->second; }
- static const V& value(const std::pair<const K, V>* kv) { return kv->second; }
-};
-
-} // namespace container_internal
-
-namespace container_algorithm_internal {
-
-// Specialization of trait in absl/algorithm/container.h
-template <class Key, class T, class Hash, class KeyEqual, class Allocator>
-struct IsUnorderedContainer<
- absl::flat_hash_map<Key, T, Hash, KeyEqual, Allocator>> : std::true_type {};
-
-} // namespace container_algorithm_internal
-
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_FLAT_HASH_MAP_H_
diff --git a/third_party/abseil-cpp/absl/container/flat_hash_map_test.cc b/third_party/abseil-cpp/absl/container/flat_hash_map_test.cc
deleted file mode 100644
index 263951f..0000000
--- a/third_party/abseil-cpp/absl/container/flat_hash_map_test.cc
+++ /dev/null
@@ -1,317 +0,0 @@
-// Copyright 2018 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/container/flat_hash_map.h"
-
-#include <memory>
-
-#include "absl/base/internal/raw_logging.h"
-#include "absl/container/internal/hash_generator_testing.h"
-#include "absl/container/internal/unordered_map_constructor_test.h"
-#include "absl/container/internal/unordered_map_lookup_test.h"
-#include "absl/container/internal/unordered_map_members_test.h"
-#include "absl/container/internal/unordered_map_modifiers_test.h"
-#include "absl/types/any.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-namespace {
-using ::absl::container_internal::hash_internal::Enum;
-using ::absl::container_internal::hash_internal::EnumClass;
-using ::testing::_;
-using ::testing::IsEmpty;
-using ::testing::Pair;
-using ::testing::UnorderedElementsAre;
-
-// Check that absl::flat_hash_map works in a global constructor.
-struct BeforeMain {
- BeforeMain() {
- absl::flat_hash_map<int, int> x;
- x.insert({1, 1});
- ABSL_RAW_CHECK(x.find(0) == x.end(), "x should not contain 0");
- auto it = x.find(1);
- ABSL_RAW_CHECK(it != x.end(), "x should contain 1");
- ABSL_RAW_CHECK(it->second, "1 should map to 1");
- }
-};
-const BeforeMain before_main;
-
-template <class K, class V>
-using Map = flat_hash_map<K, V, StatefulTestingHash, StatefulTestingEqual,
- Alloc<std::pair<const K, V>>>;
-
-static_assert(!std::is_standard_layout<NonStandardLayout>(), "");
-
-using MapTypes =
- ::testing::Types<Map<int, int>, Map<std::string, int>,
- Map<Enum, std::string>, Map<EnumClass, int>,
- Map<int, NonStandardLayout>, Map<NonStandardLayout, int>>;
-
-INSTANTIATE_TYPED_TEST_SUITE_P(FlatHashMap, ConstructorTest, MapTypes);
-INSTANTIATE_TYPED_TEST_SUITE_P(FlatHashMap, LookupTest, MapTypes);
-INSTANTIATE_TYPED_TEST_SUITE_P(FlatHashMap, MembersTest, MapTypes);
-INSTANTIATE_TYPED_TEST_SUITE_P(FlatHashMap, ModifiersTest, MapTypes);
-
-using UniquePtrMapTypes = ::testing::Types<Map<int, std::unique_ptr<int>>>;
-
-INSTANTIATE_TYPED_TEST_SUITE_P(FlatHashMap, UniquePtrModifiersTest,
- UniquePtrMapTypes);
-
-TEST(FlatHashMap, StandardLayout) {
- struct Int {
- explicit Int(size_t value) : value(value) {}
- Int() : value(0) { ADD_FAILURE(); }
- Int(const Int& other) : value(other.value) { ADD_FAILURE(); }
- Int(Int&&) = default;
- bool operator==(const Int& other) const { return value == other.value; }
- size_t value;
- };
- static_assert(std::is_standard_layout<Int>(), "");
-
- struct Hash {
- size_t operator()(const Int& obj) const { return obj.value; }
- };
-
- // Verify that neither the key nor the value get default-constructed or
- // copy-constructed.
- {
- flat_hash_map<Int, Int, Hash> m;
- m.try_emplace(Int(1), Int(2));
- m.try_emplace(Int(3), Int(4));
- m.erase(Int(1));
- m.rehash(2 * m.bucket_count());
- }
- {
- flat_hash_map<Int, Int, Hash> m;
- m.try_emplace(Int(1), Int(2));
- m.try_emplace(Int(3), Int(4));
- m.erase(Int(1));
- m.clear();
- }
-}
-
-// gcc becomes unhappy if this is inside the method, so pull it out here.
-struct balast {};
-
-TEST(FlatHashMap, IteratesMsan) {
- // Because SwissTable randomizes on pointer addresses, we keep old tables
- // around to ensure we don't reuse old memory.
- std::vector<absl::flat_hash_map<int, balast>> garbage;
- for (int i = 0; i < 100; ++i) {
- absl::flat_hash_map<int, balast> t;
- for (int j = 0; j < 100; ++j) {
- t[j];
- for (const auto& p : t) EXPECT_THAT(p, Pair(_, _));
- }
- garbage.push_back(std::move(t));
- }
-}
-
-// Demonstration of the "Lazy Key" pattern. This uses heterogeneous insert to
-// avoid creating expensive key elements when the item is already present in the
-// map.
-struct LazyInt {
- explicit LazyInt(size_t value, int* tracker)
- : value(value), tracker(tracker) {}
-
- explicit operator size_t() const {
- ++*tracker;
- return value;
- }
-
- size_t value;
- int* tracker;
-};
-
-struct Hash {
- using is_transparent = void;
- int* tracker;
- size_t operator()(size_t obj) const {
- ++*tracker;
- return obj;
- }
- size_t operator()(const LazyInt& obj) const {
- ++*tracker;
- return obj.value;
- }
-};
-
-struct Eq {
- using is_transparent = void;
- bool operator()(size_t lhs, size_t rhs) const {
- return lhs == rhs;
- }
- bool operator()(size_t lhs, const LazyInt& rhs) const {
- return lhs == rhs.value;
- }
-};
-
-TEST(FlatHashMap, LazyKeyPattern) {
- // hashes are only guaranteed in opt mode, we use assertions to track internal
- // state that can cause extra calls to hash.
- int conversions = 0;
- int hashes = 0;
- flat_hash_map<size_t, size_t, Hash, Eq> m(0, Hash{&hashes});
- m.reserve(3);
-
- m[LazyInt(1, &conversions)] = 1;
- EXPECT_THAT(m, UnorderedElementsAre(Pair(1, 1)));
- EXPECT_EQ(conversions, 1);
-#ifdef NDEBUG
- EXPECT_EQ(hashes, 1);
-#endif
-
- m[LazyInt(1, &conversions)] = 2;
- EXPECT_THAT(m, UnorderedElementsAre(Pair(1, 2)));
- EXPECT_EQ(conversions, 1);
-#ifdef NDEBUG
- EXPECT_EQ(hashes, 2);
-#endif
-
- m.try_emplace(LazyInt(2, &conversions), 3);
- EXPECT_THAT(m, UnorderedElementsAre(Pair(1, 2), Pair(2, 3)));
- EXPECT_EQ(conversions, 2);
-#ifdef NDEBUG
- EXPECT_EQ(hashes, 3);
-#endif
-
- m.try_emplace(LazyInt(2, &conversions), 4);
- EXPECT_THAT(m, UnorderedElementsAre(Pair(1, 2), Pair(2, 3)));
- EXPECT_EQ(conversions, 2);
-#ifdef NDEBUG
- EXPECT_EQ(hashes, 4);
-#endif
-}
-
-TEST(FlatHashMap, BitfieldArgument) {
- union {
- int n : 1;
- };
- n = 0;
- flat_hash_map<int, int> m;
- m.erase(n);
- m.count(n);
- m.prefetch(n);
- m.find(n);
- m.contains(n);
- m.equal_range(n);
- m.insert_or_assign(n, n);
- m.insert_or_assign(m.end(), n, n);
- m.try_emplace(n);
- m.try_emplace(m.end(), n);
- m.at(n);
- m[n];
-}
-
-TEST(FlatHashMap, MergeExtractInsert) {
- // We can't test mutable keys, or non-copyable keys with flat_hash_map.
- // Test that the nodes have the proper API.
- absl::flat_hash_map<int, int> m = {{1, 7}, {2, 9}};
- auto node = m.extract(1);
- EXPECT_TRUE(node);
- EXPECT_EQ(node.key(), 1);
- EXPECT_EQ(node.mapped(), 7);
- EXPECT_THAT(m, UnorderedElementsAre(Pair(2, 9)));
-
- node.mapped() = 17;
- m.insert(std::move(node));
- EXPECT_THAT(m, UnorderedElementsAre(Pair(1, 17), Pair(2, 9)));
-}
-
-bool FirstIsEven(std::pair<const int, int> p) { return p.first % 2 == 0; }
-
-TEST(FlatHashMap, EraseIf) {
- // Erase all elements.
- {
- flat_hash_map<int, int> s = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}};
- EXPECT_EQ(erase_if(s, [](std::pair<const int, int>) { return true; }), 5);
- EXPECT_THAT(s, IsEmpty());
- }
- // Erase no elements.
- {
- flat_hash_map<int, int> s = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}};
- EXPECT_EQ(erase_if(s, [](std::pair<const int, int>) { return false; }), 0);
- EXPECT_THAT(s, UnorderedElementsAre(Pair(1, 1), Pair(2, 2), Pair(3, 3),
- Pair(4, 4), Pair(5, 5)));
- }
- // Erase specific elements.
- {
- flat_hash_map<int, int> s = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}};
- EXPECT_EQ(erase_if(s,
- [](std::pair<const int, int> kvp) {
- return kvp.first % 2 == 1;
- }),
- 3);
- EXPECT_THAT(s, UnorderedElementsAre(Pair(2, 2), Pair(4, 4)));
- }
- // Predicate is function reference.
- {
- flat_hash_map<int, int> s = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}};
- EXPECT_EQ(erase_if(s, FirstIsEven), 2);
- EXPECT_THAT(s, UnorderedElementsAre(Pair(1, 1), Pair(3, 3), Pair(5, 5)));
- }
- // Predicate is function pointer.
- {
- flat_hash_map<int, int> s = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}};
- EXPECT_EQ(erase_if(s, &FirstIsEven), 2);
- EXPECT_THAT(s, UnorderedElementsAre(Pair(1, 1), Pair(3, 3), Pair(5, 5)));
- }
-}
-
-// This test requires std::launder for mutable key access in node handles.
-#if defined(__cpp_lib_launder) && __cpp_lib_launder >= 201606
-TEST(FlatHashMap, NodeHandleMutableKeyAccess) {
- flat_hash_map<std::string, std::string> map;
-
- map["key1"] = "mapped";
-
- auto nh = map.extract(map.begin());
- nh.key().resize(3);
- map.insert(std::move(nh));
-
- EXPECT_THAT(map, testing::ElementsAre(Pair("key", "mapped")));
-}
-#endif
-
-TEST(FlatHashMap, Reserve) {
- // Verify that if we reserve(size() + n) then we can perform n insertions
- // without a rehash, i.e., without invalidating any references.
- for (size_t trial = 0; trial < 20; ++trial) {
- for (size_t initial = 3; initial < 100; ++initial) {
- // Fill in `initial` entries, then erase 2 of them, then reserve space for
- // two inserts and check for reference stability while doing the inserts.
- flat_hash_map<size_t, size_t> map;
- for (size_t i = 0; i < initial; ++i) {
- map[i] = i;
- }
- map.erase(0);
- map.erase(1);
- map.reserve(map.size() + 2);
- size_t& a2 = map[2];
- // In the event of a failure, asan will complain in one of these two
- // assignments.
- map[initial] = a2;
- map[initial + 1] = a2;
- // Fail even when not under asan:
- size_t& a2new = map[2];
- EXPECT_EQ(&a2, &a2new);
- }
- }
-}
-
-} // namespace
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/container/flat_hash_set.h b/third_party/abseil-cpp/absl/container/flat_hash_set.h
deleted file mode 100644
index f5376f9..0000000
--- a/third_party/abseil-cpp/absl/container/flat_hash_set.h
+++ /dev/null
@@ -1,503 +0,0 @@
-// Copyright 2018 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.
-//
-// -----------------------------------------------------------------------------
-// File: flat_hash_set.h
-// -----------------------------------------------------------------------------
-//
-// An `absl::flat_hash_set<T>` is an unordered associative container designed to
-// be a more efficient replacement for `std::unordered_set`. Like
-// `unordered_set`, search, insertion, and deletion of set elements can be done
-// as an `O(1)` operation. However, `flat_hash_set` (and other unordered
-// associative containers known as the collection of Abseil "Swiss tables")
-// contain other optimizations that result in both memory and computation
-// advantages.
-//
-// In most cases, your default choice for a hash set should be a set of type
-// `flat_hash_set`.
-#ifndef ABSL_CONTAINER_FLAT_HASH_SET_H_
-#define ABSL_CONTAINER_FLAT_HASH_SET_H_
-
-#include <type_traits>
-#include <utility>
-
-#include "absl/algorithm/container.h"
-#include "absl/base/macros.h"
-#include "absl/container/internal/container_memory.h"
-#include "absl/container/internal/hash_function_defaults.h" // IWYU pragma: export
-#include "absl/container/internal/raw_hash_set.h" // IWYU pragma: export
-#include "absl/memory/memory.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-template <typename T>
-struct FlatHashSetPolicy;
-} // namespace container_internal
-
-// -----------------------------------------------------------------------------
-// absl::flat_hash_set
-// -----------------------------------------------------------------------------
-//
-// An `absl::flat_hash_set<T>` is an unordered associative container which has
-// been optimized for both speed and memory footprint in most common use cases.
-// Its interface is similar to that of `std::unordered_set<T>` with the
-// following notable differences:
-//
-// * Requires keys that are CopyConstructible
-// * Supports heterogeneous lookup, through `find()` and `insert()`, provided
-// that the set is provided a compatible heterogeneous hashing function and
-// equality operator.
-// * Invalidates any references and pointers to elements within the table after
-// `rehash()`.
-// * Contains a `capacity()` member function indicating the number of element
-// slots (open, deleted, and empty) within the hash set.
-// * Returns `void` from the `erase(iterator)` overload.
-//
-// By default, `flat_hash_set` uses the `absl::Hash` hashing framework. All
-// fundamental and Abseil types that support the `absl::Hash` framework have a
-// compatible equality operator for comparing insertions into `flat_hash_set`.
-// If your type is not yet supported by the `absl::Hash` framework, see
-// absl/hash/hash.h for information on extending Abseil hashing to user-defined
-// types.
-//
-// Using `absl::flat_hash_set` at interface boundaries in dynamically loaded
-// libraries (e.g. .dll, .so) is unsupported due to way `absl::Hash` values may
-// be randomized across dynamically loaded libraries.
-//
-// NOTE: A `flat_hash_set` stores its keys directly inside its implementation
-// array to avoid memory indirection. Because a `flat_hash_set` is designed to
-// move data when rehashed, set keys will not retain pointer stability. If you
-// require pointer stability, consider using
-// `absl::flat_hash_set<std::unique_ptr<T>>`. If your type is not moveable and
-// you require pointer stability, consider `absl::node_hash_set` instead.
-//
-// Example:
-//
-// // Create a flat hash set of three strings
-// absl::flat_hash_set<std::string> ducks =
-// {"huey", "dewey", "louie"};
-//
-// // Insert a new element into the flat hash set
-// ducks.insert("donald");
-//
-// // Force a rehash of the flat hash set
-// ducks.rehash(0);
-//
-// // See if "dewey" is present
-// if (ducks.contains("dewey")) {
-// std::cout << "We found dewey!" << std::endl;
-// }
-template <class T, class Hash = absl::container_internal::hash_default_hash<T>,
- class Eq = absl::container_internal::hash_default_eq<T>,
- class Allocator = std::allocator<T>>
-class flat_hash_set
- : public absl::container_internal::raw_hash_set<
- absl::container_internal::FlatHashSetPolicy<T>, Hash, Eq, Allocator> {
- using Base = typename flat_hash_set::raw_hash_set;
-
- public:
- // Constructors and Assignment Operators
- //
- // A flat_hash_set supports the same overload set as `std::unordered_set`
- // for construction and assignment:
- //
- // * Default constructor
- //
- // // No allocation for the table's elements is made.
- // absl::flat_hash_set<std::string> set1;
- //
- // * Initializer List constructor
- //
- // absl::flat_hash_set<std::string> set2 =
- // {{"huey"}, {"dewey"}, {"louie"},};
- //
- // * Copy constructor
- //
- // absl::flat_hash_set<std::string> set3(set2);
- //
- // * Copy assignment operator
- //
- // // Hash functor and Comparator are copied as well
- // absl::flat_hash_set<std::string> set4;
- // set4 = set3;
- //
- // * Move constructor
- //
- // // Move is guaranteed efficient
- // absl::flat_hash_set<std::string> set5(std::move(set4));
- //
- // * Move assignment operator
- //
- // // May be efficient if allocators are compatible
- // absl::flat_hash_set<std::string> set6;
- // set6 = std::move(set5);
- //
- // * Range constructor
- //
- // std::vector<std::string> v = {"a", "b"};
- // absl::flat_hash_set<std::string> set7(v.begin(), v.end());
- flat_hash_set() {}
- using Base::Base;
-
- // flat_hash_set::begin()
- //
- // Returns an iterator to the beginning of the `flat_hash_set`.
- using Base::begin;
-
- // flat_hash_set::cbegin()
- //
- // Returns a const iterator to the beginning of the `flat_hash_set`.
- using Base::cbegin;
-
- // flat_hash_set::cend()
- //
- // Returns a const iterator to the end of the `flat_hash_set`.
- using Base::cend;
-
- // flat_hash_set::end()
- //
- // Returns an iterator to the end of the `flat_hash_set`.
- using Base::end;
-
- // flat_hash_set::capacity()
- //
- // Returns the number of element slots (assigned, deleted, and empty)
- // available within the `flat_hash_set`.
- //
- // NOTE: this member function is particular to `absl::flat_hash_set` and is
- // not provided in the `std::unordered_set` API.
- using Base::capacity;
-
- // flat_hash_set::empty()
- //
- // Returns whether or not the `flat_hash_set` is empty.
- using Base::empty;
-
- // flat_hash_set::max_size()
- //
- // Returns the largest theoretical possible number of elements within a
- // `flat_hash_set` under current memory constraints. This value can be thought
- // of the largest value of `std::distance(begin(), end())` for a
- // `flat_hash_set<T>`.
- using Base::max_size;
-
- // flat_hash_set::size()
- //
- // Returns the number of elements currently within the `flat_hash_set`.
- using Base::size;
-
- // flat_hash_set::clear()
- //
- // Removes all elements from the `flat_hash_set`. Invalidates any references,
- // pointers, or iterators referring to contained elements.
- //
- // NOTE: this operation may shrink the underlying buffer. To avoid shrinking
- // the underlying buffer call `erase(begin(), end())`.
- using Base::clear;
-
- // flat_hash_set::erase()
- //
- // Erases elements within the `flat_hash_set`. Erasing does not trigger a
- // rehash. Overloads are listed below.
- //
- // void erase(const_iterator pos):
- //
- // Erases the element at `position` of the `flat_hash_set`, returning
- // `void`.
- //
- // NOTE: returning `void` in this case is different than that of STL
- // containers in general and `std::unordered_set` in particular (which
- // return an iterator to the element following the erased element). If that
- // iterator is needed, simply post increment the iterator:
- //
- // set.erase(it++);
- //
- // iterator erase(const_iterator first, const_iterator last):
- //
- // Erases the elements in the open interval [`first`, `last`), returning an
- // iterator pointing to `last`.
- //
- // size_type erase(const key_type& key):
- //
- // Erases the element with the matching key, if it exists, returning the
- // number of elements erased (0 or 1).
- using Base::erase;
-
- // flat_hash_set::insert()
- //
- // Inserts an element of the specified value into the `flat_hash_set`,
- // returning an iterator pointing to the newly inserted element, provided that
- // an element with the given key does not already exist. If rehashing occurs
- // due to the insertion, all iterators are invalidated. Overloads are listed
- // below.
- //
- // std::pair<iterator,bool> insert(const T& value):
- //
- // Inserts a value into the `flat_hash_set`. Returns a pair consisting of an
- // iterator to the inserted element (or to the element that prevented the
- // insertion) and a bool denoting whether the insertion took place.
- //
- // std::pair<iterator,bool> insert(T&& value):
- //
- // Inserts a moveable value into the `flat_hash_set`. Returns a pair
- // consisting of an iterator to the inserted element (or to the element that
- // prevented the insertion) and a bool denoting whether the insertion took
- // place.
- //
- // iterator insert(const_iterator hint, const T& value):
- // iterator insert(const_iterator hint, T&& value):
- //
- // Inserts a value, using the position of `hint` as a non-binding suggestion
- // for where to begin the insertion search. Returns an iterator to the
- // inserted element, or to the existing element that prevented the
- // insertion.
- //
- // void insert(InputIterator first, InputIterator last):
- //
- // Inserts a range of values [`first`, `last`).
- //
- // NOTE: Although the STL does not specify which element may be inserted if
- // multiple keys compare equivalently, for `flat_hash_set` we guarantee the
- // first match is inserted.
- //
- // void insert(std::initializer_list<T> ilist):
- //
- // Inserts the elements within the initializer list `ilist`.
- //
- // NOTE: Although the STL does not specify which element may be inserted if
- // multiple keys compare equivalently within the initializer list, for
- // `flat_hash_set` we guarantee the first match is inserted.
- using Base::insert;
-
- // flat_hash_set::emplace()
- //
- // Inserts an element of the specified value by constructing it in-place
- // within the `flat_hash_set`, provided that no element with the given key
- // already exists.
- //
- // The element may be constructed even if there already is an element with the
- // key in the container, in which case the newly constructed element will be
- // destroyed immediately.
- //
- // If rehashing occurs due to the insertion, all iterators are invalidated.
- using Base::emplace;
-
- // flat_hash_set::emplace_hint()
- //
- // Inserts an element of the specified value by constructing it in-place
- // within the `flat_hash_set`, using the position of `hint` as a non-binding
- // suggestion for where to begin the insertion search, and only inserts
- // provided that no element with the given key already exists.
- //
- // The element may be constructed even if there already is an element with the
- // key in the container, in which case the newly constructed element will be
- // destroyed immediately.
- //
- // If rehashing occurs due to the insertion, all iterators are invalidated.
- using Base::emplace_hint;
-
- // flat_hash_set::extract()
- //
- // Extracts the indicated element, erasing it in the process, and returns it
- // as a C++17-compatible node handle. Overloads are listed below.
- //
- // node_type extract(const_iterator position):
- //
- // Extracts the element at the indicated position and returns a node handle
- // owning that extracted data.
- //
- // node_type extract(const key_type& x):
- //
- // Extracts the element with the key matching the passed key value and
- // returns a node handle owning that extracted data. If the `flat_hash_set`
- // does not contain an element with a matching key, this function returns an
- // empty node handle.
- using Base::extract;
-
- // flat_hash_set::merge()
- //
- // Extracts elements from a given `source` flat hash set into this
- // `flat_hash_set`. If the destination `flat_hash_set` already contains an
- // element with an equivalent key, that element is not extracted.
- using Base::merge;
-
- // flat_hash_set::swap(flat_hash_set& other)
- //
- // Exchanges the contents of this `flat_hash_set` with those of the `other`
- // flat hash set, avoiding invocation of any move, copy, or swap operations on
- // individual elements.
- //
- // All iterators and references on the `flat_hash_set` remain valid, excepting
- // for the past-the-end iterator, which is invalidated.
- //
- // `swap()` requires that the flat hash set's hashing and key equivalence
- // functions be Swappable, and are exchaged using unqualified calls to
- // non-member `swap()`. If the set's allocator has
- // `std::allocator_traits<allocator_type>::propagate_on_container_swap::value`
- // set to `true`, the allocators are also exchanged using an unqualified call
- // to non-member `swap()`; otherwise, the allocators are not swapped.
- using Base::swap;
-
- // flat_hash_set::rehash(count)
- //
- // Rehashes the `flat_hash_set`, setting the number of slots to be at least
- // the passed value. If the new number of slots increases the load factor more
- // than the current maximum load factor
- // (`count` < `size()` / `max_load_factor()`), then the new number of slots
- // will be at least `size()` / `max_load_factor()`.
- //
- // To force a rehash, pass rehash(0).
- //
- // NOTE: unlike behavior in `std::unordered_set`, references are also
- // invalidated upon a `rehash()`.
- using Base::rehash;
-
- // flat_hash_set::reserve(count)
- //
- // Sets the number of slots in the `flat_hash_set` to the number needed to
- // accommodate at least `count` total elements without exceeding the current
- // maximum load factor, and may rehash the container if needed.
- using Base::reserve;
-
- // flat_hash_set::contains()
- //
- // Determines whether an element comparing equal to the given `key` exists
- // within the `flat_hash_set`, returning `true` if so or `false` otherwise.
- using Base::contains;
-
- // flat_hash_set::count(const Key& key) const
- //
- // Returns the number of elements comparing equal to the given `key` within
- // the `flat_hash_set`. note that this function will return either `1` or `0`
- // since duplicate elements are not allowed within a `flat_hash_set`.
- using Base::count;
-
- // flat_hash_set::equal_range()
- //
- // Returns a closed range [first, last], defined by a `std::pair` of two
- // iterators, containing all elements with the passed key in the
- // `flat_hash_set`.
- using Base::equal_range;
-
- // flat_hash_set::find()
- //
- // Finds an element with the passed `key` within the `flat_hash_set`.
- using Base::find;
-
- // flat_hash_set::bucket_count()
- //
- // Returns the number of "buckets" within the `flat_hash_set`. Note that
- // because a flat hash set contains all elements within its internal storage,
- // this value simply equals the current capacity of the `flat_hash_set`.
- using Base::bucket_count;
-
- // flat_hash_set::load_factor()
- //
- // Returns the current load factor of the `flat_hash_set` (the average number
- // of slots occupied with a value within the hash set).
- using Base::load_factor;
-
- // flat_hash_set::max_load_factor()
- //
- // Manages the maximum load factor of the `flat_hash_set`. Overloads are
- // listed below.
- //
- // float flat_hash_set::max_load_factor()
- //
- // Returns the current maximum load factor of the `flat_hash_set`.
- //
- // void flat_hash_set::max_load_factor(float ml)
- //
- // Sets the maximum load factor of the `flat_hash_set` to the passed value.
- //
- // NOTE: This overload is provided only for API compatibility with the STL;
- // `flat_hash_set` will ignore any set load factor and manage its rehashing
- // internally as an implementation detail.
- using Base::max_load_factor;
-
- // flat_hash_set::get_allocator()
- //
- // Returns the allocator function associated with this `flat_hash_set`.
- using Base::get_allocator;
-
- // flat_hash_set::hash_function()
- //
- // Returns the hashing function used to hash the keys within this
- // `flat_hash_set`.
- using Base::hash_function;
-
- // flat_hash_set::key_eq()
- //
- // Returns the function used for comparing keys equality.
- using Base::key_eq;
-};
-
-// erase_if(flat_hash_set<>, Pred)
-//
-// Erases all elements that satisfy the predicate `pred` from the container `c`.
-// Returns the number of erased elements.
-template <typename T, typename H, typename E, typename A, typename Predicate>
-typename flat_hash_set<T, H, E, A>::size_type erase_if(
- flat_hash_set<T, H, E, A>& c, Predicate pred) {
- return container_internal::EraseIf(pred, &c);
-}
-
-namespace container_internal {
-
-template <class T>
-struct FlatHashSetPolicy {
- using slot_type = T;
- using key_type = T;
- using init_type = T;
- using constant_iterators = std::true_type;
-
- template <class Allocator, class... Args>
- static void construct(Allocator* alloc, slot_type* slot, Args&&... args) {
- absl::allocator_traits<Allocator>::construct(*alloc, slot,
- std::forward<Args>(args)...);
- }
-
- template <class Allocator>
- static void destroy(Allocator* alloc, slot_type* slot) {
- absl::allocator_traits<Allocator>::destroy(*alloc, slot);
- }
-
- static T& element(slot_type* slot) { return *slot; }
-
- template <class F, class... Args>
- static decltype(absl::container_internal::DecomposeValue(
- std::declval<F>(), std::declval<Args>()...))
- apply(F&& f, Args&&... args) {
- return absl::container_internal::DecomposeValue(
- std::forward<F>(f), std::forward<Args>(args)...);
- }
-
- static size_t space_used(const T*) { return 0; }
-};
-} // namespace container_internal
-
-namespace container_algorithm_internal {
-
-// Specialization of trait in absl/algorithm/container.h
-template <class Key, class Hash, class KeyEqual, class Allocator>
-struct IsUnorderedContainer<absl::flat_hash_set<Key, Hash, KeyEqual, Allocator>>
- : std::true_type {};
-
-} // namespace container_algorithm_internal
-
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_FLAT_HASH_SET_H_
diff --git a/third_party/abseil-cpp/absl/container/flat_hash_set_test.cc b/third_party/abseil-cpp/absl/container/flat_hash_set_test.cc
deleted file mode 100644
index b6a72a2..0000000
--- a/third_party/abseil-cpp/absl/container/flat_hash_set_test.cc
+++ /dev/null
@@ -1,178 +0,0 @@
-// Copyright 2018 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/container/flat_hash_set.h"
-
-#include <vector>
-
-#include "absl/base/internal/raw_logging.h"
-#include "absl/container/internal/hash_generator_testing.h"
-#include "absl/container/internal/unordered_set_constructor_test.h"
-#include "absl/container/internal/unordered_set_lookup_test.h"
-#include "absl/container/internal/unordered_set_members_test.h"
-#include "absl/container/internal/unordered_set_modifiers_test.h"
-#include "absl/memory/memory.h"
-#include "absl/strings/string_view.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-namespace {
-
-using ::absl::container_internal::hash_internal::Enum;
-using ::absl::container_internal::hash_internal::EnumClass;
-using ::testing::IsEmpty;
-using ::testing::Pointee;
-using ::testing::UnorderedElementsAre;
-using ::testing::UnorderedElementsAreArray;
-
-// Check that absl::flat_hash_set works in a global constructor.
-struct BeforeMain {
- BeforeMain() {
- absl::flat_hash_set<int> x;
- x.insert(1);
- ABSL_RAW_CHECK(!x.contains(0), "x should not contain 0");
- ABSL_RAW_CHECK(x.contains(1), "x should contain 1");
- }
-};
-const BeforeMain before_main;
-
-template <class T>
-using Set =
- absl::flat_hash_set<T, StatefulTestingHash, StatefulTestingEqual, Alloc<T>>;
-
-using SetTypes =
- ::testing::Types<Set<int>, Set<std::string>, Set<Enum>, Set<EnumClass>>;
-
-INSTANTIATE_TYPED_TEST_SUITE_P(FlatHashSet, ConstructorTest, SetTypes);
-INSTANTIATE_TYPED_TEST_SUITE_P(FlatHashSet, LookupTest, SetTypes);
-INSTANTIATE_TYPED_TEST_SUITE_P(FlatHashSet, MembersTest, SetTypes);
-INSTANTIATE_TYPED_TEST_SUITE_P(FlatHashSet, ModifiersTest, SetTypes);
-
-TEST(FlatHashSet, EmplaceString) {
- std::vector<std::string> v = {"a", "b"};
- absl::flat_hash_set<absl::string_view> hs(v.begin(), v.end());
- EXPECT_THAT(hs, UnorderedElementsAreArray(v));
-}
-
-TEST(FlatHashSet, BitfieldArgument) {
- union {
- int n : 1;
- };
- n = 0;
- absl::flat_hash_set<int> s = {n};
- s.insert(n);
- s.insert(s.end(), n);
- s.insert({n});
- s.erase(n);
- s.count(n);
- s.prefetch(n);
- s.find(n);
- s.contains(n);
- s.equal_range(n);
-}
-
-TEST(FlatHashSet, MergeExtractInsert) {
- struct Hash {
- size_t operator()(const std::unique_ptr<int>& p) const { return *p; }
- };
- struct Eq {
- bool operator()(const std::unique_ptr<int>& a,
- const std::unique_ptr<int>& b) const {
- return *a == *b;
- }
- };
- absl::flat_hash_set<std::unique_ptr<int>, Hash, Eq> set1, set2;
- set1.insert(absl::make_unique<int>(7));
- set1.insert(absl::make_unique<int>(17));
-
- set2.insert(absl::make_unique<int>(7));
- set2.insert(absl::make_unique<int>(19));
-
- EXPECT_THAT(set1, UnorderedElementsAre(Pointee(7), Pointee(17)));
- EXPECT_THAT(set2, UnorderedElementsAre(Pointee(7), Pointee(19)));
-
- set1.merge(set2);
-
- EXPECT_THAT(set1, UnorderedElementsAre(Pointee(7), Pointee(17), Pointee(19)));
- EXPECT_THAT(set2, UnorderedElementsAre(Pointee(7)));
-
- auto node = set1.extract(absl::make_unique<int>(7));
- EXPECT_TRUE(node);
- EXPECT_THAT(node.value(), Pointee(7));
- EXPECT_THAT(set1, UnorderedElementsAre(Pointee(17), Pointee(19)));
-
- auto insert_result = set2.insert(std::move(node));
- EXPECT_FALSE(node);
- EXPECT_FALSE(insert_result.inserted);
- EXPECT_TRUE(insert_result.node);
- EXPECT_THAT(insert_result.node.value(), Pointee(7));
- EXPECT_EQ(**insert_result.position, 7);
- EXPECT_NE(insert_result.position->get(), insert_result.node.value().get());
- EXPECT_THAT(set2, UnorderedElementsAre(Pointee(7)));
-
- node = set1.extract(absl::make_unique<int>(17));
- EXPECT_TRUE(node);
- EXPECT_THAT(node.value(), Pointee(17));
- EXPECT_THAT(set1, UnorderedElementsAre(Pointee(19)));
-
- node.value() = absl::make_unique<int>(23);
-
- insert_result = set2.insert(std::move(node));
- EXPECT_FALSE(node);
- EXPECT_TRUE(insert_result.inserted);
- EXPECT_FALSE(insert_result.node);
- EXPECT_EQ(**insert_result.position, 23);
- EXPECT_THAT(set2, UnorderedElementsAre(Pointee(7), Pointee(23)));
-}
-
-bool IsEven(int k) { return k % 2 == 0; }
-
-TEST(FlatHashSet, EraseIf) {
- // Erase all elements.
- {
- flat_hash_set<int> s = {1, 2, 3, 4, 5};
- EXPECT_EQ(erase_if(s, [](int) { return true; }), 5);
- EXPECT_THAT(s, IsEmpty());
- }
- // Erase no elements.
- {
- flat_hash_set<int> s = {1, 2, 3, 4, 5};
- EXPECT_EQ(erase_if(s, [](int) { return false; }), 0);
- EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
- }
- // Erase specific elements.
- {
- flat_hash_set<int> s = {1, 2, 3, 4, 5};
- EXPECT_EQ(erase_if(s, [](int k) { return k % 2 == 1; }), 3);
- EXPECT_THAT(s, UnorderedElementsAre(2, 4));
- }
- // Predicate is function reference.
- {
- flat_hash_set<int> s = {1, 2, 3, 4, 5};
- EXPECT_EQ(erase_if(s, IsEven), 2);
- EXPECT_THAT(s, UnorderedElementsAre(1, 3, 5));
- }
- // Predicate is function pointer.
- {
- flat_hash_set<int> s = {1, 2, 3, 4, 5};
- EXPECT_EQ(erase_if(s, &IsEven), 2);
- EXPECT_THAT(s, UnorderedElementsAre(1, 3, 5));
- }
-}
-
-} // namespace
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/container/inlined_vector.h b/third_party/abseil-cpp/absl/container/inlined_vector.h
deleted file mode 100644
index 1561600..0000000
--- a/third_party/abseil-cpp/absl/container/inlined_vector.h
+++ /dev/null
@@ -1,902 +0,0 @@
-// Copyright 2019 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.
-//
-// -----------------------------------------------------------------------------
-// File: inlined_vector.h
-// -----------------------------------------------------------------------------
-//
-// This header file contains the declaration and definition of an "inlined
-// vector" which behaves in an equivalent fashion to a `std::vector`, except
-// that storage for small sequences of the vector are provided inline without
-// requiring any heap allocation.
-//
-// An `absl::InlinedVector<T, N>` specifies the default capacity `N` as one of
-// its template parameters. Instances where `size() <= N` hold contained
-// elements in inline space. Typically `N` is very small so that sequences that
-// are expected to be short do not require allocations.
-//
-// An `absl::InlinedVector` does not usually require a specific allocator. If
-// the inlined vector grows beyond its initial constraints, it will need to
-// allocate (as any normal `std::vector` would). This is usually performed with
-// the default allocator (defined as `std::allocator<T>`). Optionally, a custom
-// allocator type may be specified as `A` in `absl::InlinedVector<T, N, A>`.
-
-#ifndef ABSL_CONTAINER_INLINED_VECTOR_H_
-#define ABSL_CONTAINER_INLINED_VECTOR_H_
-
-#include <algorithm>
-#include <cstddef>
-#include <cstdlib>
-#include <cstring>
-#include <initializer_list>
-#include <iterator>
-#include <memory>
-#include <type_traits>
-#include <utility>
-
-#include "absl/algorithm/algorithm.h"
-#include "absl/base/internal/throw_delegate.h"
-#include "absl/base/macros.h"
-#include "absl/base/optimization.h"
-#include "absl/base/port.h"
-#include "absl/container/internal/inlined_vector.h"
-#include "absl/memory/memory.h"
-#include "absl/meta/type_traits.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-// -----------------------------------------------------------------------------
-// InlinedVector
-// -----------------------------------------------------------------------------
-//
-// An `absl::InlinedVector` is designed to be a drop-in replacement for
-// `std::vector` for use cases where the vector's size is sufficiently small
-// that it can be inlined. If the inlined vector does grow beyond its estimated
-// capacity, it will trigger an initial allocation on the heap, and will behave
-// as a `std::vector`. The API of the `absl::InlinedVector` within this file is
-// designed to cover the same API footprint as covered by `std::vector`.
-template <typename T, size_t N, typename A = std::allocator<T>>
-class InlinedVector {
- static_assert(N > 0, "`absl::InlinedVector` requires an inlined capacity.");
-
- using Storage = inlined_vector_internal::Storage<T, N, A>;
-
- template <typename TheA>
- using AllocatorTraits = inlined_vector_internal::AllocatorTraits<TheA>;
- template <typename TheA>
- using MoveIterator = inlined_vector_internal::MoveIterator<TheA>;
- template <typename TheA>
- using IsMemcpyOk = inlined_vector_internal::IsMemcpyOk<TheA>;
- template <typename TheA>
- using IsMoveAssignOk = inlined_vector_internal::IsMoveAssignOk<TheA>;
-
- template <typename TheA, typename Iterator>
- using IteratorValueAdapter =
- inlined_vector_internal::IteratorValueAdapter<TheA, Iterator>;
- template <typename TheA>
- using CopyValueAdapter = inlined_vector_internal::CopyValueAdapter<TheA>;
- template <typename TheA>
- using DefaultValueAdapter =
- inlined_vector_internal::DefaultValueAdapter<TheA>;
-
- template <typename Iterator>
- using EnableIfAtLeastForwardIterator = absl::enable_if_t<
- inlined_vector_internal::IsAtLeastForwardIterator<Iterator>::value, int>;
- template <typename Iterator>
- using DisableIfAtLeastForwardIterator = absl::enable_if_t<
- !inlined_vector_internal::IsAtLeastForwardIterator<Iterator>::value, int>;
-
- using MemcpyPolicy = typename Storage::MemcpyPolicy;
- using ElementwiseAssignPolicy = typename Storage::ElementwiseAssignPolicy;
- using ElementwiseConstructPolicy =
- typename Storage::ElementwiseConstructPolicy;
- using MoveAssignmentPolicy = typename Storage::MoveAssignmentPolicy;
-
- public:
- using allocator_type = A;
- using value_type = inlined_vector_internal::ValueType<A>;
- using pointer = inlined_vector_internal::Pointer<A>;
- using const_pointer = inlined_vector_internal::ConstPointer<A>;
- using size_type = inlined_vector_internal::SizeType<A>;
- using difference_type = inlined_vector_internal::DifferenceType<A>;
- using reference = inlined_vector_internal::Reference<A>;
- using const_reference = inlined_vector_internal::ConstReference<A>;
- using iterator = inlined_vector_internal::Iterator<A>;
- using const_iterator = inlined_vector_internal::ConstIterator<A>;
- using reverse_iterator = inlined_vector_internal::ReverseIterator<A>;
- using const_reverse_iterator =
- inlined_vector_internal::ConstReverseIterator<A>;
-
- // ---------------------------------------------------------------------------
- // InlinedVector Constructors and Destructor
- // ---------------------------------------------------------------------------
-
- // Creates an empty inlined vector with a value-initialized allocator.
- InlinedVector() noexcept(noexcept(allocator_type())) : storage_() {}
-
- // Creates an empty inlined vector with a copy of `allocator`.
- explicit InlinedVector(const allocator_type& allocator) noexcept
- : storage_(allocator) {}
-
- // Creates an inlined vector with `n` copies of `value_type()`.
- explicit InlinedVector(size_type n,
- const allocator_type& allocator = allocator_type())
- : storage_(allocator) {
- storage_.Initialize(DefaultValueAdapter<A>(), n);
- }
-
- // Creates an inlined vector with `n` copies of `v`.
- InlinedVector(size_type n, const_reference v,
- const allocator_type& allocator = allocator_type())
- : storage_(allocator) {
- storage_.Initialize(CopyValueAdapter<A>(std::addressof(v)), n);
- }
-
- // Creates an inlined vector with copies of the elements of `list`.
- InlinedVector(std::initializer_list<value_type> list,
- const allocator_type& allocator = allocator_type())
- : InlinedVector(list.begin(), list.end(), allocator) {}
-
- // Creates an inlined vector with elements constructed from the provided
- // forward iterator range [`first`, `last`).
- //
- // NOTE: the `enable_if` prevents ambiguous interpretation between a call to
- // this constructor with two integral arguments and a call to the above
- // `InlinedVector(size_type, const_reference)` constructor.
- template <typename ForwardIterator,
- EnableIfAtLeastForwardIterator<ForwardIterator> = 0>
- InlinedVector(ForwardIterator first, ForwardIterator last,
- const allocator_type& allocator = allocator_type())
- : storage_(allocator) {
- storage_.Initialize(IteratorValueAdapter<A, ForwardIterator>(first),
- static_cast<size_t>(std::distance(first, last)));
- }
-
- // Creates an inlined vector with elements constructed from the provided input
- // iterator range [`first`, `last`).
- template <typename InputIterator,
- DisableIfAtLeastForwardIterator<InputIterator> = 0>
- InlinedVector(InputIterator first, InputIterator last,
- const allocator_type& allocator = allocator_type())
- : storage_(allocator) {
- std::copy(first, last, std::back_inserter(*this));
- }
-
- // Creates an inlined vector by copying the contents of `other` using
- // `other`'s allocator.
- InlinedVector(const InlinedVector& other)
- : InlinedVector(other, other.storage_.GetAllocator()) {}
-
- // Creates an inlined vector by copying the contents of `other` using the
- // provided `allocator`.
- InlinedVector(const InlinedVector& other, const allocator_type& allocator)
- : storage_(allocator) {
- if (other.empty()) {
- // Empty; nothing to do.
- } else if (IsMemcpyOk<A>::value && !other.storage_.GetIsAllocated()) {
- // Memcpy-able and do not need allocation.
- storage_.MemcpyFrom(other.storage_);
- } else {
- storage_.InitFrom(other.storage_);
- }
- }
-
- // Creates an inlined vector by moving in the contents of `other` without
- // allocating. If `other` contains allocated memory, the newly-created inlined
- // vector will take ownership of that memory. However, if `other` does not
- // contain allocated memory, the newly-created inlined vector will perform
- // element-wise move construction of the contents of `other`.
- //
- // NOTE: since no allocation is performed for the inlined vector in either
- // case, the `noexcept(...)` specification depends on whether moving the
- // underlying objects can throw. It is assumed assumed that...
- // a) move constructors should only throw due to allocation failure.
- // b) if `value_type`'s move constructor allocates, it uses the same
- // allocation function as the inlined vector's allocator.
- // Thus, the move constructor is non-throwing if the allocator is non-throwing
- // or `value_type`'s move constructor is specified as `noexcept`.
- InlinedVector(InlinedVector&& other) noexcept(
- absl::allocator_is_nothrow<allocator_type>::value ||
- std::is_nothrow_move_constructible<value_type>::value)
- : storage_(other.storage_.GetAllocator()) {
- if (IsMemcpyOk<A>::value) {
- storage_.MemcpyFrom(other.storage_);
-
- other.storage_.SetInlinedSize(0);
- } else if (other.storage_.GetIsAllocated()) {
- storage_.SetAllocation({other.storage_.GetAllocatedData(),
- other.storage_.GetAllocatedCapacity()});
- storage_.SetAllocatedSize(other.storage_.GetSize());
-
- other.storage_.SetInlinedSize(0);
- } else {
- IteratorValueAdapter<A, MoveIterator<A>> other_values(
- MoveIterator<A>(other.storage_.GetInlinedData()));
-
- inlined_vector_internal::ConstructElements<A>(
- storage_.GetAllocator(), storage_.GetInlinedData(), other_values,
- other.storage_.GetSize());
-
- storage_.SetInlinedSize(other.storage_.GetSize());
- }
- }
-
- // Creates an inlined vector by moving in the contents of `other` with a copy
- // of `allocator`.
- //
- // NOTE: if `other`'s allocator is not equal to `allocator`, even if `other`
- // contains allocated memory, this move constructor will still allocate. Since
- // allocation is performed, this constructor can only be `noexcept` if the
- // specified allocator is also `noexcept`.
- InlinedVector(
- InlinedVector&& other,
- const allocator_type&
- allocator) noexcept(absl::allocator_is_nothrow<allocator_type>::value)
- : storage_(allocator) {
- if (IsMemcpyOk<A>::value) {
- storage_.MemcpyFrom(other.storage_);
-
- other.storage_.SetInlinedSize(0);
- } else if ((storage_.GetAllocator() == other.storage_.GetAllocator()) &&
- other.storage_.GetIsAllocated()) {
- storage_.SetAllocation({other.storage_.GetAllocatedData(),
- other.storage_.GetAllocatedCapacity()});
- storage_.SetAllocatedSize(other.storage_.GetSize());
-
- other.storage_.SetInlinedSize(0);
- } else {
- storage_.Initialize(IteratorValueAdapter<A, MoveIterator<A>>(
- MoveIterator<A>(other.data())),
- other.size());
- }
- }
-
- ~InlinedVector() {}
-
- // ---------------------------------------------------------------------------
- // InlinedVector Member Accessors
- // ---------------------------------------------------------------------------
-
- // `InlinedVector::empty()`
- //
- // Returns whether the inlined vector contains no elements.
- bool empty() const noexcept { return !size(); }
-
- // `InlinedVector::size()`
- //
- // Returns the number of elements in the inlined vector.
- size_type size() const noexcept { return storage_.GetSize(); }
-
- // `InlinedVector::max_size()`
- //
- // Returns the maximum number of elements the inlined vector can hold.
- size_type max_size() const noexcept {
- // One bit of the size storage is used to indicate whether the inlined
- // vector contains allocated memory. As a result, the maximum size that the
- // inlined vector can express is the minimum of the limit of how many
- // objects we can allocate and std::numeric_limits<size_type>::max() / 2.
- return (std::min)(AllocatorTraits<A>::max_size(storage_.GetAllocator()),
- (std::numeric_limits<size_type>::max)() / 2);
- }
-
- // `InlinedVector::capacity()`
- //
- // Returns the number of elements that could be stored in the inlined vector
- // without requiring a reallocation.
- //
- // NOTE: for most inlined vectors, `capacity()` should be equal to the
- // template parameter `N`. For inlined vectors which exceed this capacity,
- // they will no longer be inlined and `capacity()` will equal the capactity of
- // the allocated memory.
- size_type capacity() const noexcept {
- return storage_.GetIsAllocated() ? storage_.GetAllocatedCapacity()
- : storage_.GetInlinedCapacity();
- }
-
- // `InlinedVector::data()`
- //
- // Returns a `pointer` to the elements of the inlined vector. This pointer
- // can be used to access and modify the contained elements.
- //
- // NOTE: only elements within [`data()`, `data() + size()`) are valid.
- pointer data() noexcept {
- return storage_.GetIsAllocated() ? storage_.GetAllocatedData()
- : storage_.GetInlinedData();
- }
-
- // Overload of `InlinedVector::data()` that returns a `const_pointer` to the
- // elements of the inlined vector. This pointer can be used to access but not
- // modify the contained elements.
- //
- // NOTE: only elements within [`data()`, `data() + size()`) are valid.
- const_pointer data() const noexcept {
- return storage_.GetIsAllocated() ? storage_.GetAllocatedData()
- : storage_.GetInlinedData();
- }
-
- // `InlinedVector::operator[](...)`
- //
- // Returns a `reference` to the `i`th element of the inlined vector.
- reference operator[](size_type i) {
- ABSL_HARDENING_ASSERT(i < size());
- return data()[i];
- }
-
- // Overload of `InlinedVector::operator[](...)` that returns a
- // `const_reference` to the `i`th element of the inlined vector.
- const_reference operator[](size_type i) const {
- ABSL_HARDENING_ASSERT(i < size());
- return data()[i];
- }
-
- // `InlinedVector::at(...)`
- //
- // Returns a `reference` to the `i`th element of the inlined vector.
- //
- // NOTE: if `i` is not within the required range of `InlinedVector::at(...)`,
- // in both debug and non-debug builds, `std::out_of_range` will be thrown.
- reference at(size_type i) {
- if (ABSL_PREDICT_FALSE(i >= size())) {
- base_internal::ThrowStdOutOfRange(
- "`InlinedVector::at(size_type)` failed bounds check");
- }
- return data()[i];
- }
-
- // Overload of `InlinedVector::at(...)` that returns a `const_reference` to
- // the `i`th element of the inlined vector.
- //
- // NOTE: if `i` is not within the required range of `InlinedVector::at(...)`,
- // in both debug and non-debug builds, `std::out_of_range` will be thrown.
- const_reference at(size_type i) const {
- if (ABSL_PREDICT_FALSE(i >= size())) {
- base_internal::ThrowStdOutOfRange(
- "`InlinedVector::at(size_type) const` failed bounds check");
- }
- return data()[i];
- }
-
- // `InlinedVector::front()`
- //
- // Returns a `reference` to the first element of the inlined vector.
- reference front() {
- ABSL_HARDENING_ASSERT(!empty());
- return data()[0];
- }
-
- // Overload of `InlinedVector::front()` that returns a `const_reference` to
- // the first element of the inlined vector.
- const_reference front() const {
- ABSL_HARDENING_ASSERT(!empty());
- return data()[0];
- }
-
- // `InlinedVector::back()`
- //
- // Returns a `reference` to the last element of the inlined vector.
- reference back() {
- ABSL_HARDENING_ASSERT(!empty());
- return data()[size() - 1];
- }
-
- // Overload of `InlinedVector::back()` that returns a `const_reference` to the
- // last element of the inlined vector.
- const_reference back() const {
- ABSL_HARDENING_ASSERT(!empty());
- return data()[size() - 1];
- }
-
- // `InlinedVector::begin()`
- //
- // Returns an `iterator` to the beginning of the inlined vector.
- iterator begin() noexcept { return data(); }
-
- // Overload of `InlinedVector::begin()` that returns a `const_iterator` to
- // the beginning of the inlined vector.
- const_iterator begin() const noexcept { return data(); }
-
- // `InlinedVector::end()`
- //
- // Returns an `iterator` to the end of the inlined vector.
- iterator end() noexcept { return data() + size(); }
-
- // Overload of `InlinedVector::end()` that returns a `const_iterator` to the
- // end of the inlined vector.
- const_iterator end() const noexcept { return data() + size(); }
-
- // `InlinedVector::cbegin()`
- //
- // Returns a `const_iterator` to the beginning of the inlined vector.
- const_iterator cbegin() const noexcept { return begin(); }
-
- // `InlinedVector::cend()`
- //
- // Returns a `const_iterator` to the end of the inlined vector.
- const_iterator cend() const noexcept { return end(); }
-
- // `InlinedVector::rbegin()`
- //
- // Returns a `reverse_iterator` from the end of the inlined vector.
- reverse_iterator rbegin() noexcept { return reverse_iterator(end()); }
-
- // Overload of `InlinedVector::rbegin()` that returns a
- // `const_reverse_iterator` from the end of the inlined vector.
- const_reverse_iterator rbegin() const noexcept {
- return const_reverse_iterator(end());
- }
-
- // `InlinedVector::rend()`
- //
- // Returns a `reverse_iterator` from the beginning of the inlined vector.
- reverse_iterator rend() noexcept { return reverse_iterator(begin()); }
-
- // Overload of `InlinedVector::rend()` that returns a `const_reverse_iterator`
- // from the beginning of the inlined vector.
- const_reverse_iterator rend() const noexcept {
- return const_reverse_iterator(begin());
- }
-
- // `InlinedVector::crbegin()`
- //
- // Returns a `const_reverse_iterator` from the end of the inlined vector.
- const_reverse_iterator crbegin() const noexcept { return rbegin(); }
-
- // `InlinedVector::crend()`
- //
- // Returns a `const_reverse_iterator` from the beginning of the inlined
- // vector.
- const_reverse_iterator crend() const noexcept { return rend(); }
-
- // `InlinedVector::get_allocator()`
- //
- // Returns a copy of the inlined vector's allocator.
- allocator_type get_allocator() const { return storage_.GetAllocator(); }
-
- // ---------------------------------------------------------------------------
- // InlinedVector Member Mutators
- // ---------------------------------------------------------------------------
-
- // `InlinedVector::operator=(...)`
- //
- // Replaces the elements of the inlined vector with copies of the elements of
- // `list`.
- InlinedVector& operator=(std::initializer_list<value_type> list) {
- assign(list.begin(), list.end());
-
- return *this;
- }
-
- // Overload of `InlinedVector::operator=(...)` that replaces the elements of
- // the inlined vector with copies of the elements of `other`.
- InlinedVector& operator=(const InlinedVector& other) {
- if (ABSL_PREDICT_TRUE(this != std::addressof(other))) {
- const_pointer other_data = other.data();
- assign(other_data, other_data + other.size());
- }
-
- return *this;
- }
-
- // Overload of `InlinedVector::operator=(...)` that moves the elements of
- // `other` into the inlined vector.
- //
- // NOTE: as a result of calling this overload, `other` is left in a valid but
- // unspecified state.
- InlinedVector& operator=(InlinedVector&& other) {
- if (ABSL_PREDICT_TRUE(this != std::addressof(other))) {
- MoveAssignment(MoveAssignmentPolicy{}, std::move(other));
- }
-
- return *this;
- }
-
- // `InlinedVector::assign(...)`
- //
- // Replaces the contents of the inlined vector with `n` copies of `v`.
- void assign(size_type n, const_reference v) {
- storage_.Assign(CopyValueAdapter<A>(std::addressof(v)), n);
- }
-
- // Overload of `InlinedVector::assign(...)` that replaces the contents of the
- // inlined vector with copies of the elements of `list`.
- void assign(std::initializer_list<value_type> list) {
- assign(list.begin(), list.end());
- }
-
- // Overload of `InlinedVector::assign(...)` to replace the contents of the
- // inlined vector with the range [`first`, `last`).
- //
- // NOTE: this overload is for iterators that are "forward" category or better.
- template <typename ForwardIterator,
- EnableIfAtLeastForwardIterator<ForwardIterator> = 0>
- void assign(ForwardIterator first, ForwardIterator last) {
- storage_.Assign(IteratorValueAdapter<A, ForwardIterator>(first),
- static_cast<size_t>(std::distance(first, last)));
- }
-
- // Overload of `InlinedVector::assign(...)` to replace the contents of the
- // inlined vector with the range [`first`, `last`).
- //
- // NOTE: this overload is for iterators that are "input" category.
- template <typename InputIterator,
- DisableIfAtLeastForwardIterator<InputIterator> = 0>
- void assign(InputIterator first, InputIterator last) {
- size_type i = 0;
- for (; i < size() && first != last; ++i, static_cast<void>(++first)) {
- data()[i] = *first;
- }
-
- erase(data() + i, data() + size());
- std::copy(first, last, std::back_inserter(*this));
- }
-
- // `InlinedVector::resize(...)`
- //
- // Resizes the inlined vector to contain `n` elements.
- //
- // NOTE: If `n` is smaller than `size()`, extra elements are destroyed. If `n`
- // is larger than `size()`, new elements are value-initialized.
- void resize(size_type n) {
- ABSL_HARDENING_ASSERT(n <= max_size());
- storage_.Resize(DefaultValueAdapter<A>(), n);
- }
-
- // Overload of `InlinedVector::resize(...)` that resizes the inlined vector to
- // contain `n` elements.
- //
- // NOTE: if `n` is smaller than `size()`, extra elements are destroyed. If `n`
- // is larger than `size()`, new elements are copied-constructed from `v`.
- void resize(size_type n, const_reference v) {
- ABSL_HARDENING_ASSERT(n <= max_size());
- storage_.Resize(CopyValueAdapter<A>(std::addressof(v)), n);
- }
-
- // `InlinedVector::insert(...)`
- //
- // Inserts a copy of `v` at `pos`, returning an `iterator` to the newly
- // inserted element.
- iterator insert(const_iterator pos, const_reference v) {
- return emplace(pos, v);
- }
-
- // Overload of `InlinedVector::insert(...)` that inserts `v` at `pos` using
- // move semantics, returning an `iterator` to the newly inserted element.
- iterator insert(const_iterator pos, value_type&& v) {
- return emplace(pos, std::move(v));
- }
-
- // Overload of `InlinedVector::insert(...)` that inserts `n` contiguous copies
- // of `v` starting at `pos`, returning an `iterator` pointing to the first of
- // the newly inserted elements.
- iterator insert(const_iterator pos, size_type n, const_reference v) {
- ABSL_HARDENING_ASSERT(pos >= begin());
- ABSL_HARDENING_ASSERT(pos <= end());
-
- if (ABSL_PREDICT_TRUE(n != 0)) {
- value_type dealias = v;
- // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=102329#c2
- // It appears that GCC thinks that since `pos` is a const pointer and may
- // point to uninitialized memory at this point, a warning should be
- // issued. But `pos` is actually only used to compute an array index to
- // write to.
-#if !defined(__clang__) && defined(__GNUC__)
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
-#endif
- return storage_.Insert(pos, CopyValueAdapter<A>(std::addressof(dealias)),
- n);
-#if !defined(__clang__) && defined(__GNUC__)
-#pragma GCC diagnostic pop
-#endif
- } else {
- return const_cast<iterator>(pos);
- }
- }
-
- // Overload of `InlinedVector::insert(...)` that inserts copies of the
- // elements of `list` starting at `pos`, returning an `iterator` pointing to
- // the first of the newly inserted elements.
- iterator insert(const_iterator pos, std::initializer_list<value_type> list) {
- return insert(pos, list.begin(), list.end());
- }
-
- // Overload of `InlinedVector::insert(...)` that inserts the range [`first`,
- // `last`) starting at `pos`, returning an `iterator` pointing to the first
- // of the newly inserted elements.
- //
- // NOTE: this overload is for iterators that are "forward" category or better.
- template <typename ForwardIterator,
- EnableIfAtLeastForwardIterator<ForwardIterator> = 0>
- iterator insert(const_iterator pos, ForwardIterator first,
- ForwardIterator last) {
- ABSL_HARDENING_ASSERT(pos >= begin());
- ABSL_HARDENING_ASSERT(pos <= end());
-
- if (ABSL_PREDICT_TRUE(first != last)) {
- return storage_.Insert(
- pos, IteratorValueAdapter<A, ForwardIterator>(first),
- static_cast<size_type>(std::distance(first, last)));
- } else {
- return const_cast<iterator>(pos);
- }
- }
-
- // Overload of `InlinedVector::insert(...)` that inserts the range [`first`,
- // `last`) starting at `pos`, returning an `iterator` pointing to the first
- // of the newly inserted elements.
- //
- // NOTE: this overload is for iterators that are "input" category.
- template <typename InputIterator,
- DisableIfAtLeastForwardIterator<InputIterator> = 0>
- iterator insert(const_iterator pos, InputIterator first, InputIterator last) {
- ABSL_HARDENING_ASSERT(pos >= begin());
- ABSL_HARDENING_ASSERT(pos <= end());
-
- size_type index = static_cast<size_type>(std::distance(cbegin(), pos));
- for (size_type i = index; first != last; ++i, static_cast<void>(++first)) {
- insert(data() + i, *first);
- }
-
- return iterator(data() + index);
- }
-
- // `InlinedVector::emplace(...)`
- //
- // Constructs and inserts an element using `args...` in the inlined vector at
- // `pos`, returning an `iterator` pointing to the newly emplaced element.
- template <typename... Args>
- iterator emplace(const_iterator pos, Args&&... args) {
- ABSL_HARDENING_ASSERT(pos >= begin());
- ABSL_HARDENING_ASSERT(pos <= end());
-
- value_type dealias(std::forward<Args>(args)...);
- return storage_.Insert(pos,
- IteratorValueAdapter<A, MoveIterator<A>>(
- MoveIterator<A>(std::addressof(dealias))),
- 1);
- }
-
- // `InlinedVector::emplace_back(...)`
- //
- // Constructs and inserts an element using `args...` in the inlined vector at
- // `end()`, returning a `reference` to the newly emplaced element.
- template <typename... Args>
- reference emplace_back(Args&&... args) {
- return storage_.EmplaceBack(std::forward<Args>(args)...);
- }
-
- // `InlinedVector::push_back(...)`
- //
- // Inserts a copy of `v` in the inlined vector at `end()`.
- void push_back(const_reference v) { static_cast<void>(emplace_back(v)); }
-
- // Overload of `InlinedVector::push_back(...)` for inserting `v` at `end()`
- // using move semantics.
- void push_back(value_type&& v) {
- static_cast<void>(emplace_back(std::move(v)));
- }
-
- // `InlinedVector::pop_back()`
- //
- // Destroys the element at `back()`, reducing the size by `1`.
- void pop_back() noexcept {
- ABSL_HARDENING_ASSERT(!empty());
-
- AllocatorTraits<A>::destroy(storage_.GetAllocator(), data() + (size() - 1));
- storage_.SubtractSize(1);
- }
-
- // `InlinedVector::erase(...)`
- //
- // Erases the element at `pos`, returning an `iterator` pointing to where the
- // erased element was located.
- //
- // NOTE: may return `end()`, which is not dereferencable.
- iterator erase(const_iterator pos) {
- ABSL_HARDENING_ASSERT(pos >= begin());
- ABSL_HARDENING_ASSERT(pos < end());
-
- return storage_.Erase(pos, pos + 1);
- }
-
- // Overload of `InlinedVector::erase(...)` that erases every element in the
- // range [`from`, `to`), returning an `iterator` pointing to where the first
- // erased element was located.
- //
- // NOTE: may return `end()`, which is not dereferencable.
- iterator erase(const_iterator from, const_iterator to) {
- ABSL_HARDENING_ASSERT(from >= begin());
- ABSL_HARDENING_ASSERT(from <= to);
- ABSL_HARDENING_ASSERT(to <= end());
-
- if (ABSL_PREDICT_TRUE(from != to)) {
- return storage_.Erase(from, to);
- } else {
- return const_cast<iterator>(from);
- }
- }
-
- // `InlinedVector::clear()`
- //
- // Destroys all elements in the inlined vector, setting the size to `0` and
- // deallocating any held memory.
- void clear() noexcept {
- inlined_vector_internal::DestroyAdapter<A>::DestroyElements(
- storage_.GetAllocator(), data(), size());
- storage_.DeallocateIfAllocated();
-
- storage_.SetInlinedSize(0);
- }
-
- // `InlinedVector::reserve(...)`
- //
- // Ensures that there is enough room for at least `n` elements.
- void reserve(size_type n) { storage_.Reserve(n); }
-
- // `InlinedVector::shrink_to_fit()`
- //
- // Attempts to reduce memory usage by moving elements to (or keeping elements
- // in) the smallest available buffer sufficient for containing `size()`
- // elements.
- //
- // If `size()` is sufficiently small, the elements will be moved into (or kept
- // in) the inlined space.
- void shrink_to_fit() {
- if (storage_.GetIsAllocated()) {
- storage_.ShrinkToFit();
- }
- }
-
- // `InlinedVector::swap(...)`
- //
- // Swaps the contents of the inlined vector with `other`.
- void swap(InlinedVector& other) {
- if (ABSL_PREDICT_TRUE(this != std::addressof(other))) {
- storage_.Swap(std::addressof(other.storage_));
- }
- }
-
- private:
- template <typename H, typename TheT, size_t TheN, typename TheA>
- friend H AbslHashValue(H h, const absl::InlinedVector<TheT, TheN, TheA>& a);
-
- void MoveAssignment(MemcpyPolicy, InlinedVector&& other) {
- inlined_vector_internal::DestroyAdapter<A>::DestroyElements(
- storage_.GetAllocator(), data(), size());
- storage_.DeallocateIfAllocated();
- storage_.MemcpyFrom(other.storage_);
-
- other.storage_.SetInlinedSize(0);
- }
-
- void MoveAssignment(ElementwiseAssignPolicy, InlinedVector&& other) {
- if (other.storage_.GetIsAllocated()) {
- MoveAssignment(MemcpyPolicy{}, std::move(other));
- } else {
- storage_.Assign(IteratorValueAdapter<A, MoveIterator<A>>(
- MoveIterator<A>(other.storage_.GetInlinedData())),
- other.size());
- }
- }
-
- void MoveAssignment(ElementwiseConstructPolicy, InlinedVector&& other) {
- if (other.storage_.GetIsAllocated()) {
- MoveAssignment(MemcpyPolicy{}, std::move(other));
- } else {
- inlined_vector_internal::DestroyAdapter<A>::DestroyElements(
- storage_.GetAllocator(), data(), size());
- storage_.DeallocateIfAllocated();
-
- IteratorValueAdapter<A, MoveIterator<A>> other_values(
- MoveIterator<A>(other.storage_.GetInlinedData()));
- inlined_vector_internal::ConstructElements<A>(
- storage_.GetAllocator(), storage_.GetInlinedData(), other_values,
- other.storage_.GetSize());
- storage_.SetInlinedSize(other.storage_.GetSize());
- }
- }
-
- Storage storage_;
-};
-
-// -----------------------------------------------------------------------------
-// InlinedVector Non-Member Functions
-// -----------------------------------------------------------------------------
-
-// `swap(...)`
-//
-// Swaps the contents of two inlined vectors.
-template <typename T, size_t N, typename A>
-void swap(absl::InlinedVector<T, N, A>& a,
- absl::InlinedVector<T, N, A>& b) noexcept(noexcept(a.swap(b))) {
- a.swap(b);
-}
-
-// `operator==(...)`
-//
-// Tests for value-equality of two inlined vectors.
-template <typename T, size_t N, typename A>
-bool operator==(const absl::InlinedVector<T, N, A>& a,
- const absl::InlinedVector<T, N, A>& b) {
- auto a_data = a.data();
- auto b_data = b.data();
- return absl::equal(a_data, a_data + a.size(), b_data, b_data + b.size());
-}
-
-// `operator!=(...)`
-//
-// Tests for value-inequality of two inlined vectors.
-template <typename T, size_t N, typename A>
-bool operator!=(const absl::InlinedVector<T, N, A>& a,
- const absl::InlinedVector<T, N, A>& b) {
- return !(a == b);
-}
-
-// `operator<(...)`
-//
-// Tests whether the value of an inlined vector is less than the value of
-// another inlined vector using a lexicographical comparison algorithm.
-template <typename T, size_t N, typename A>
-bool operator<(const absl::InlinedVector<T, N, A>& a,
- const absl::InlinedVector<T, N, A>& b) {
- auto a_data = a.data();
- auto b_data = b.data();
- return std::lexicographical_compare(a_data, a_data + a.size(), b_data,
- b_data + b.size());
-}
-
-// `operator>(...)`
-//
-// Tests whether the value of an inlined vector is greater than the value of
-// another inlined vector using a lexicographical comparison algorithm.
-template <typename T, size_t N, typename A>
-bool operator>(const absl::InlinedVector<T, N, A>& a,
- const absl::InlinedVector<T, N, A>& b) {
- return b < a;
-}
-
-// `operator<=(...)`
-//
-// Tests whether the value of an inlined vector is less than or equal to the
-// value of another inlined vector using a lexicographical comparison algorithm.
-template <typename T, size_t N, typename A>
-bool operator<=(const absl::InlinedVector<T, N, A>& a,
- const absl::InlinedVector<T, N, A>& b) {
- return !(b < a);
-}
-
-// `operator>=(...)`
-//
-// Tests whether the value of an inlined vector is greater than or equal to the
-// value of another inlined vector using a lexicographical comparison algorithm.
-template <typename T, size_t N, typename A>
-bool operator>=(const absl::InlinedVector<T, N, A>& a,
- const absl::InlinedVector<T, N, A>& b) {
- return !(a < b);
-}
-
-// `AbslHashValue(...)`
-//
-// Provides `absl::Hash` support for `absl::InlinedVector`. It is uncommon to
-// call this directly.
-template <typename H, typename T, size_t N, typename A>
-H AbslHashValue(H h, const absl::InlinedVector<T, N, A>& a) {
- auto size = a.size();
- return H::combine(H::combine_contiguous(std::move(h), a.data(), size), size);
-}
-
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_INLINED_VECTOR_H_
diff --git a/third_party/abseil-cpp/absl/container/inlined_vector_benchmark.cc b/third_party/abseil-cpp/absl/container/inlined_vector_benchmark.cc
deleted file mode 100644
index 56a6bfd..0000000
--- a/third_party/abseil-cpp/absl/container/inlined_vector_benchmark.cc
+++ /dev/null
@@ -1,829 +0,0 @@
-// Copyright 2019 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 <array>
-#include <string>
-#include <vector>
-
-#include "absl/base/internal/raw_logging.h"
-#include "absl/base/macros.h"
-#include "absl/container/inlined_vector.h"
-#include "absl/strings/str_cat.h"
-#include "benchmark/benchmark.h"
-
-namespace {
-
-void BM_InlinedVectorFill(benchmark::State& state) {
- const int len = state.range(0);
- absl::InlinedVector<int, 8> v;
- v.reserve(len);
- for (auto _ : state) {
- v.resize(0); // Use resize(0) as InlinedVector releases storage on clear().
- for (int i = 0; i < len; ++i) {
- v.push_back(i);
- }
- benchmark::DoNotOptimize(v);
- }
-}
-BENCHMARK(BM_InlinedVectorFill)->Range(1, 256);
-
-void BM_InlinedVectorFillRange(benchmark::State& state) {
- const int len = state.range(0);
- const std::vector<int> src(len, len);
- absl::InlinedVector<int, 8> v;
- v.reserve(len);
- for (auto _ : state) {
- benchmark::DoNotOptimize(src);
- v.assign(src.begin(), src.end());
- benchmark::DoNotOptimize(v);
- }
-}
-BENCHMARK(BM_InlinedVectorFillRange)->Range(1, 256);
-
-void BM_StdVectorFill(benchmark::State& state) {
- const int len = state.range(0);
- std::vector<int> v;
- v.reserve(len);
- for (auto _ : state) {
- v.clear();
- for (int i = 0; i < len; ++i) {
- v.push_back(i);
- }
- benchmark::DoNotOptimize(v);
- }
-}
-BENCHMARK(BM_StdVectorFill)->Range(1, 256);
-
-// The purpose of the next two benchmarks is to verify that
-// absl::InlinedVector is efficient when moving is more efficent than
-// copying. To do so, we use strings that are larger than the short
-// string optimization.
-bool StringRepresentedInline(std::string s) {
- const char* chars = s.data();
- std::string s1 = std::move(s);
- return s1.data() != chars;
-}
-
-int GetNonShortStringOptimizationSize() {
- for (int i = 24; i <= 192; i *= 2) {
- if (!StringRepresentedInline(std::string(i, 'A'))) {
- return i;
- }
- }
- ABSL_RAW_LOG(
- FATAL,
- "Failed to find a string larger than the short string optimization");
- return -1;
-}
-
-void BM_InlinedVectorFillString(benchmark::State& state) {
- const int len = state.range(0);
- const int no_sso = GetNonShortStringOptimizationSize();
- std::string strings[4] = {std::string(no_sso, 'A'), std::string(no_sso, 'B'),
- std::string(no_sso, 'C'), std::string(no_sso, 'D')};
-
- for (auto _ : state) {
- absl::InlinedVector<std::string, 8> v;
- for (int i = 0; i < len; i++) {
- v.push_back(strings[i & 3]);
- }
- }
- state.SetItemsProcessed(static_cast<int64_t>(state.iterations()) * len);
-}
-BENCHMARK(BM_InlinedVectorFillString)->Range(0, 1024);
-
-void BM_StdVectorFillString(benchmark::State& state) {
- const int len = state.range(0);
- const int no_sso = GetNonShortStringOptimizationSize();
- std::string strings[4] = {std::string(no_sso, 'A'), std::string(no_sso, 'B'),
- std::string(no_sso, 'C'), std::string(no_sso, 'D')};
-
- for (auto _ : state) {
- std::vector<std::string> v;
- for (int i = 0; i < len; i++) {
- v.push_back(strings[i & 3]);
- }
- }
- state.SetItemsProcessed(static_cast<int64_t>(state.iterations()) * len);
-}
-BENCHMARK(BM_StdVectorFillString)->Range(0, 1024);
-
-struct Buffer { // some arbitrary structure for benchmarking.
- char* base;
- int length;
- int capacity;
- void* user_data;
-};
-
-void BM_InlinedVectorAssignments(benchmark::State& state) {
- const int len = state.range(0);
- using BufferVec = absl::InlinedVector<Buffer, 2>;
-
- BufferVec src;
- src.resize(len);
-
- BufferVec dst;
- for (auto _ : state) {
- benchmark::DoNotOptimize(dst);
- benchmark::DoNotOptimize(src);
- dst = src;
- }
-}
-BENCHMARK(BM_InlinedVectorAssignments)
- ->Arg(0)
- ->Arg(1)
- ->Arg(2)
- ->Arg(3)
- ->Arg(4)
- ->Arg(20);
-
-void BM_CreateFromContainer(benchmark::State& state) {
- for (auto _ : state) {
- absl::InlinedVector<int, 4> src{1, 2, 3};
- benchmark::DoNotOptimize(src);
- absl::InlinedVector<int, 4> dst(std::move(src));
- benchmark::DoNotOptimize(dst);
- }
-}
-BENCHMARK(BM_CreateFromContainer);
-
-struct LargeCopyableOnly {
- LargeCopyableOnly() : d(1024, 17) {}
- LargeCopyableOnly(const LargeCopyableOnly& o) = default;
- LargeCopyableOnly& operator=(const LargeCopyableOnly& o) = default;
-
- std::vector<int> d;
-};
-
-struct LargeCopyableSwappable {
- LargeCopyableSwappable() : d(1024, 17) {}
-
- LargeCopyableSwappable(const LargeCopyableSwappable& o) = default;
-
- LargeCopyableSwappable& operator=(LargeCopyableSwappable o) {
- using std::swap;
- swap(*this, o);
- return *this;
- }
-
- friend void swap(LargeCopyableSwappable& a, LargeCopyableSwappable& b) {
- using std::swap;
- swap(a.d, b.d);
- }
-
- std::vector<int> d;
-};
-
-struct LargeCopyableMovable {
- LargeCopyableMovable() : d(1024, 17) {}
- // Use implicitly defined copy and move.
-
- std::vector<int> d;
-};
-
-struct LargeCopyableMovableSwappable {
- LargeCopyableMovableSwappable() : d(1024, 17) {}
- LargeCopyableMovableSwappable(const LargeCopyableMovableSwappable& o) =
- default;
- LargeCopyableMovableSwappable(LargeCopyableMovableSwappable&& o) = default;
-
- LargeCopyableMovableSwappable& operator=(LargeCopyableMovableSwappable o) {
- using std::swap;
- swap(*this, o);
- return *this;
- }
- LargeCopyableMovableSwappable& operator=(LargeCopyableMovableSwappable&& o) =
- default;
-
- friend void swap(LargeCopyableMovableSwappable& a,
- LargeCopyableMovableSwappable& b) {
- using std::swap;
- swap(a.d, b.d);
- }
-
- std::vector<int> d;
-};
-
-template <typename ElementType>
-void BM_SwapElements(benchmark::State& state) {
- const int len = state.range(0);
- using Vec = absl::InlinedVector<ElementType, 32>;
- Vec a(len);
- Vec b;
- for (auto _ : state) {
- using std::swap;
- benchmark::DoNotOptimize(a);
- benchmark::DoNotOptimize(b);
- swap(a, b);
- }
-}
-BENCHMARK_TEMPLATE(BM_SwapElements, LargeCopyableOnly)->Range(0, 1024);
-BENCHMARK_TEMPLATE(BM_SwapElements, LargeCopyableSwappable)->Range(0, 1024);
-BENCHMARK_TEMPLATE(BM_SwapElements, LargeCopyableMovable)->Range(0, 1024);
-BENCHMARK_TEMPLATE(BM_SwapElements, LargeCopyableMovableSwappable)
- ->Range(0, 1024);
-
-// The following benchmark is meant to track the efficiency of the vector size
-// as a function of stored type via the benchmark label. It is not meant to
-// output useful sizeof operator performance. The loop is a dummy operation
-// to fulfill the requirement of running the benchmark.
-template <typename VecType>
-void BM_Sizeof(benchmark::State& state) {
- int size = 0;
- for (auto _ : state) {
- VecType vec;
- size = sizeof(vec);
- }
- state.SetLabel(absl::StrCat("sz=", size));
-}
-BENCHMARK_TEMPLATE(BM_Sizeof, absl::InlinedVector<char, 1>);
-BENCHMARK_TEMPLATE(BM_Sizeof, absl::InlinedVector<char, 4>);
-BENCHMARK_TEMPLATE(BM_Sizeof, absl::InlinedVector<char, 7>);
-BENCHMARK_TEMPLATE(BM_Sizeof, absl::InlinedVector<char, 8>);
-
-BENCHMARK_TEMPLATE(BM_Sizeof, absl::InlinedVector<int, 1>);
-BENCHMARK_TEMPLATE(BM_Sizeof, absl::InlinedVector<int, 4>);
-BENCHMARK_TEMPLATE(BM_Sizeof, absl::InlinedVector<int, 7>);
-BENCHMARK_TEMPLATE(BM_Sizeof, absl::InlinedVector<int, 8>);
-
-BENCHMARK_TEMPLATE(BM_Sizeof, absl::InlinedVector<void*, 1>);
-BENCHMARK_TEMPLATE(BM_Sizeof, absl::InlinedVector<void*, 4>);
-BENCHMARK_TEMPLATE(BM_Sizeof, absl::InlinedVector<void*, 7>);
-BENCHMARK_TEMPLATE(BM_Sizeof, absl::InlinedVector<void*, 8>);
-
-BENCHMARK_TEMPLATE(BM_Sizeof, absl::InlinedVector<std::string, 1>);
-BENCHMARK_TEMPLATE(BM_Sizeof, absl::InlinedVector<std::string, 4>);
-BENCHMARK_TEMPLATE(BM_Sizeof, absl::InlinedVector<std::string, 7>);
-BENCHMARK_TEMPLATE(BM_Sizeof, absl::InlinedVector<std::string, 8>);
-
-void BM_InlinedVectorIndexInlined(benchmark::State& state) {
- absl::InlinedVector<int, 8> v = {1, 2, 3, 4, 5, 6, 7};
- for (auto _ : state) {
- benchmark::DoNotOptimize(v);
- benchmark::DoNotOptimize(v[4]);
- }
-}
-BENCHMARK(BM_InlinedVectorIndexInlined);
-
-void BM_InlinedVectorIndexExternal(benchmark::State& state) {
- absl::InlinedVector<int, 8> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
- for (auto _ : state) {
- benchmark::DoNotOptimize(v);
- benchmark::DoNotOptimize(v[4]);
- }
-}
-BENCHMARK(BM_InlinedVectorIndexExternal);
-
-void BM_StdVectorIndex(benchmark::State& state) {
- std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
- for (auto _ : state) {
- benchmark::DoNotOptimize(v);
- benchmark::DoNotOptimize(v[4]);
- }
-}
-BENCHMARK(BM_StdVectorIndex);
-
-void BM_InlinedVectorDataInlined(benchmark::State& state) {
- absl::InlinedVector<int, 8> v = {1, 2, 3, 4, 5, 6, 7};
- for (auto _ : state) {
- benchmark::DoNotOptimize(v);
- benchmark::DoNotOptimize(v.data());
- }
-}
-BENCHMARK(BM_InlinedVectorDataInlined);
-
-void BM_InlinedVectorDataExternal(benchmark::State& state) {
- absl::InlinedVector<int, 8> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
- for (auto _ : state) {
- benchmark::DoNotOptimize(v);
- benchmark::DoNotOptimize(v.data());
- }
- state.SetItemsProcessed(16 * static_cast<int64_t>(state.iterations()));
-}
-BENCHMARK(BM_InlinedVectorDataExternal);
-
-void BM_StdVectorData(benchmark::State& state) {
- std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
- for (auto _ : state) {
- benchmark::DoNotOptimize(v);
- benchmark::DoNotOptimize(v.data());
- }
- state.SetItemsProcessed(16 * static_cast<int64_t>(state.iterations()));
-}
-BENCHMARK(BM_StdVectorData);
-
-void BM_InlinedVectorSizeInlined(benchmark::State& state) {
- absl::InlinedVector<int, 8> v = {1, 2, 3, 4, 5, 6, 7};
- for (auto _ : state) {
- benchmark::DoNotOptimize(v);
- benchmark::DoNotOptimize(v.size());
- }
-}
-BENCHMARK(BM_InlinedVectorSizeInlined);
-
-void BM_InlinedVectorSizeExternal(benchmark::State& state) {
- absl::InlinedVector<int, 8> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
- for (auto _ : state) {
- benchmark::DoNotOptimize(v);
- benchmark::DoNotOptimize(v.size());
- }
-}
-BENCHMARK(BM_InlinedVectorSizeExternal);
-
-void BM_StdVectorSize(benchmark::State& state) {
- std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
- for (auto _ : state) {
- benchmark::DoNotOptimize(v);
- benchmark::DoNotOptimize(v.size());
- }
-}
-BENCHMARK(BM_StdVectorSize);
-
-void BM_InlinedVectorEmptyInlined(benchmark::State& state) {
- absl::InlinedVector<int, 8> v = {1, 2, 3, 4, 5, 6, 7};
- for (auto _ : state) {
- benchmark::DoNotOptimize(v);
- benchmark::DoNotOptimize(v.empty());
- }
-}
-BENCHMARK(BM_InlinedVectorEmptyInlined);
-
-void BM_InlinedVectorEmptyExternal(benchmark::State& state) {
- absl::InlinedVector<int, 8> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
- for (auto _ : state) {
- benchmark::DoNotOptimize(v);
- benchmark::DoNotOptimize(v.empty());
- }
-}
-BENCHMARK(BM_InlinedVectorEmptyExternal);
-
-void BM_StdVectorEmpty(benchmark::State& state) {
- std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
- for (auto _ : state) {
- benchmark::DoNotOptimize(v);
- benchmark::DoNotOptimize(v.empty());
- }
-}
-BENCHMARK(BM_StdVectorEmpty);
-
-constexpr size_t kInlinedCapacity = 4;
-constexpr size_t kLargeSize = kInlinedCapacity * 2;
-constexpr size_t kSmallSize = kInlinedCapacity / 2;
-constexpr size_t kBatchSize = 100;
-
-#define ABSL_INTERNAL_BENCHMARK_ONE_SIZE(BM_FunctionTemplate, T) \
- BENCHMARK_TEMPLATE(BM_FunctionTemplate, T, kLargeSize); \
- BENCHMARK_TEMPLATE(BM_FunctionTemplate, T, kSmallSize)
-
-#define ABSL_INTERNAL_BENCHMARK_TWO_SIZE(BM_FunctionTemplate, T) \
- BENCHMARK_TEMPLATE(BM_FunctionTemplate, T, kLargeSize, kLargeSize); \
- BENCHMARK_TEMPLATE(BM_FunctionTemplate, T, kLargeSize, kSmallSize); \
- BENCHMARK_TEMPLATE(BM_FunctionTemplate, T, kSmallSize, kLargeSize); \
- BENCHMARK_TEMPLATE(BM_FunctionTemplate, T, kSmallSize, kSmallSize)
-
-template <typename T>
-using InlVec = absl::InlinedVector<T, kInlinedCapacity>;
-
-struct TrivialType {
- size_t val;
-};
-
-class NontrivialType {
- public:
- ABSL_ATTRIBUTE_NOINLINE NontrivialType() : val_() {
- benchmark::DoNotOptimize(*this);
- }
-
- ABSL_ATTRIBUTE_NOINLINE NontrivialType(const NontrivialType& other)
- : val_(other.val_) {
- benchmark::DoNotOptimize(*this);
- }
-
- ABSL_ATTRIBUTE_NOINLINE NontrivialType& operator=(
- const NontrivialType& other) {
- val_ = other.val_;
- benchmark::DoNotOptimize(*this);
- return *this;
- }
-
- ABSL_ATTRIBUTE_NOINLINE ~NontrivialType() noexcept {
- benchmark::DoNotOptimize(*this);
- }
-
- private:
- size_t val_;
-};
-
-template <typename T, typename PrepareVecFn, typename TestVecFn>
-void BatchedBenchmark(benchmark::State& state, PrepareVecFn prepare_vec,
- TestVecFn test_vec) {
- std::array<InlVec<T>, kBatchSize> vector_batch{};
-
- while (state.KeepRunningBatch(kBatchSize)) {
- // Prepare batch
- state.PauseTiming();
- for (size_t i = 0; i < kBatchSize; ++i) {
- prepare_vec(vector_batch.data() + i, i);
- }
- benchmark::DoNotOptimize(vector_batch);
- state.ResumeTiming();
-
- // Test batch
- for (size_t i = 0; i < kBatchSize; ++i) {
- test_vec(vector_batch.data() + i, i);
- }
- }
-}
-
-template <typename T, size_t ToSize>
-void BM_ConstructFromSize(benchmark::State& state) {
- using VecT = InlVec<T>;
- auto size = ToSize;
- BatchedBenchmark<T>(
- state,
- /* prepare_vec = */ [](InlVec<T>* vec, size_t) { vec->~VecT(); },
- /* test_vec = */
- [&](void* ptr, size_t) {
- benchmark::DoNotOptimize(size);
- ::new (ptr) VecT(size);
- });
-}
-ABSL_INTERNAL_BENCHMARK_ONE_SIZE(BM_ConstructFromSize, TrivialType);
-ABSL_INTERNAL_BENCHMARK_ONE_SIZE(BM_ConstructFromSize, NontrivialType);
-
-template <typename T, size_t ToSize>
-void BM_ConstructFromSizeRef(benchmark::State& state) {
- using VecT = InlVec<T>;
- auto size = ToSize;
- auto ref = T();
- BatchedBenchmark<T>(
- state,
- /* prepare_vec = */ [](InlVec<T>* vec, size_t) { vec->~VecT(); },
- /* test_vec = */
- [&](void* ptr, size_t) {
- benchmark::DoNotOptimize(size);
- benchmark::DoNotOptimize(ref);
- ::new (ptr) VecT(size, ref);
- });
-}
-ABSL_INTERNAL_BENCHMARK_ONE_SIZE(BM_ConstructFromSizeRef, TrivialType);
-ABSL_INTERNAL_BENCHMARK_ONE_SIZE(BM_ConstructFromSizeRef, NontrivialType);
-
-template <typename T, size_t ToSize>
-void BM_ConstructFromRange(benchmark::State& state) {
- using VecT = InlVec<T>;
- std::array<T, ToSize> arr{};
- BatchedBenchmark<T>(
- state,
- /* prepare_vec = */ [](InlVec<T>* vec, size_t) { vec->~VecT(); },
- /* test_vec = */
- [&](void* ptr, size_t) {
- benchmark::DoNotOptimize(arr);
- ::new (ptr) VecT(arr.begin(), arr.end());
- });
-}
-ABSL_INTERNAL_BENCHMARK_ONE_SIZE(BM_ConstructFromRange, TrivialType);
-ABSL_INTERNAL_BENCHMARK_ONE_SIZE(BM_ConstructFromRange, NontrivialType);
-
-template <typename T, size_t ToSize>
-void BM_ConstructFromCopy(benchmark::State& state) {
- using VecT = InlVec<T>;
- VecT other_vec(ToSize);
- BatchedBenchmark<T>(
- state,
- /* prepare_vec = */
- [](InlVec<T>* vec, size_t) { vec->~VecT(); },
- /* test_vec = */
- [&](void* ptr, size_t) {
- benchmark::DoNotOptimize(other_vec);
- ::new (ptr) VecT(other_vec);
- });
-}
-ABSL_INTERNAL_BENCHMARK_ONE_SIZE(BM_ConstructFromCopy, TrivialType);
-ABSL_INTERNAL_BENCHMARK_ONE_SIZE(BM_ConstructFromCopy, NontrivialType);
-
-template <typename T, size_t ToSize>
-void BM_ConstructFromMove(benchmark::State& state) {
- using VecT = InlVec<T>;
- std::array<VecT, kBatchSize> vector_batch{};
- BatchedBenchmark<T>(
- state,
- /* prepare_vec = */
- [&](InlVec<T>* vec, size_t i) {
- vector_batch[i].clear();
- vector_batch[i].resize(ToSize);
- vec->~VecT();
- },
- /* test_vec = */
- [&](void* ptr, size_t i) {
- benchmark::DoNotOptimize(vector_batch[i]);
- ::new (ptr) VecT(std::move(vector_batch[i]));
- });
-}
-ABSL_INTERNAL_BENCHMARK_ONE_SIZE(BM_ConstructFromMove, TrivialType);
-ABSL_INTERNAL_BENCHMARK_ONE_SIZE(BM_ConstructFromMove, NontrivialType);
-
-// Measure cost of copy-constructor+destructor.
-void BM_CopyTrivial(benchmark::State& state) {
- const int n = state.range(0);
- InlVec<int64_t> src(n);
- for (auto s : state) {
- InlVec<int64_t> copy(src);
- benchmark::DoNotOptimize(copy);
- }
-}
-BENCHMARK(BM_CopyTrivial)->Arg(0)->Arg(1)->Arg(kLargeSize);
-
-// Measure cost of copy-constructor+destructor.
-void BM_CopyNonTrivial(benchmark::State& state) {
- const int n = state.range(0);
- InlVec<InlVec<int64_t>> src(n);
- for (auto s : state) {
- InlVec<InlVec<int64_t>> copy(src);
- benchmark::DoNotOptimize(copy);
- }
-}
-BENCHMARK(BM_CopyNonTrivial)->Arg(0)->Arg(1)->Arg(kLargeSize);
-
-template <typename T, size_t FromSize, size_t ToSize>
-void BM_AssignSizeRef(benchmark::State& state) {
- auto size = ToSize;
- auto ref = T();
- BatchedBenchmark<T>(
- state,
- /* prepare_vec = */ [](InlVec<T>* vec, size_t) { vec->resize(FromSize); },
- /* test_vec = */
- [&](InlVec<T>* vec, size_t) {
- benchmark::DoNotOptimize(size);
- benchmark::DoNotOptimize(ref);
- vec->assign(size, ref);
- });
-}
-ABSL_INTERNAL_BENCHMARK_TWO_SIZE(BM_AssignSizeRef, TrivialType);
-ABSL_INTERNAL_BENCHMARK_TWO_SIZE(BM_AssignSizeRef, NontrivialType);
-
-template <typename T, size_t FromSize, size_t ToSize>
-void BM_AssignRange(benchmark::State& state) {
- std::array<T, ToSize> arr{};
- BatchedBenchmark<T>(
- state,
- /* prepare_vec = */ [](InlVec<T>* vec, size_t) { vec->resize(FromSize); },
- /* test_vec = */
- [&](InlVec<T>* vec, size_t) {
- benchmark::DoNotOptimize(arr);
- vec->assign(arr.begin(), arr.end());
- });
-}
-ABSL_INTERNAL_BENCHMARK_TWO_SIZE(BM_AssignRange, TrivialType);
-ABSL_INTERNAL_BENCHMARK_TWO_SIZE(BM_AssignRange, NontrivialType);
-
-template <typename T, size_t FromSize, size_t ToSize>
-void BM_AssignFromCopy(benchmark::State& state) {
- InlVec<T> other_vec(ToSize);
- BatchedBenchmark<T>(
- state,
- /* prepare_vec = */ [](InlVec<T>* vec, size_t) { vec->resize(FromSize); },
- /* test_vec = */
- [&](InlVec<T>* vec, size_t) {
- benchmark::DoNotOptimize(other_vec);
- *vec = other_vec;
- });
-}
-ABSL_INTERNAL_BENCHMARK_TWO_SIZE(BM_AssignFromCopy, TrivialType);
-ABSL_INTERNAL_BENCHMARK_TWO_SIZE(BM_AssignFromCopy, NontrivialType);
-
-template <typename T, size_t FromSize, size_t ToSize>
-void BM_AssignFromMove(benchmark::State& state) {
- using VecT = InlVec<T>;
- std::array<VecT, kBatchSize> vector_batch{};
- BatchedBenchmark<T>(
- state,
- /* prepare_vec = */
- [&](InlVec<T>* vec, size_t i) {
- vector_batch[i].clear();
- vector_batch[i].resize(ToSize);
- vec->resize(FromSize);
- },
- /* test_vec = */
- [&](InlVec<T>* vec, size_t i) {
- benchmark::DoNotOptimize(vector_batch[i]);
- *vec = std::move(vector_batch[i]);
- });
-}
-ABSL_INTERNAL_BENCHMARK_TWO_SIZE(BM_AssignFromMove, TrivialType);
-ABSL_INTERNAL_BENCHMARK_TWO_SIZE(BM_AssignFromMove, NontrivialType);
-
-template <typename T, size_t FromSize, size_t ToSize>
-void BM_ResizeSize(benchmark::State& state) {
- BatchedBenchmark<T>(
- state,
- /* prepare_vec = */
- [](InlVec<T>* vec, size_t) {
- vec->clear();
- vec->resize(FromSize);
- },
- /* test_vec = */
- [](InlVec<T>* vec, size_t) { vec->resize(ToSize); });
-}
-ABSL_INTERNAL_BENCHMARK_TWO_SIZE(BM_ResizeSize, TrivialType);
-ABSL_INTERNAL_BENCHMARK_TWO_SIZE(BM_ResizeSize, NontrivialType);
-
-template <typename T, size_t FromSize, size_t ToSize>
-void BM_ResizeSizeRef(benchmark::State& state) {
- auto t = T();
- BatchedBenchmark<T>(
- state,
- /* prepare_vec = */
- [](InlVec<T>* vec, size_t) {
- vec->clear();
- vec->resize(FromSize);
- },
- /* test_vec = */
- [&](InlVec<T>* vec, size_t) {
- benchmark::DoNotOptimize(t);
- vec->resize(ToSize, t);
- });
-}
-ABSL_INTERNAL_BENCHMARK_TWO_SIZE(BM_ResizeSizeRef, TrivialType);
-ABSL_INTERNAL_BENCHMARK_TWO_SIZE(BM_ResizeSizeRef, NontrivialType);
-
-template <typename T, size_t FromSize, size_t ToSize>
-void BM_InsertSizeRef(benchmark::State& state) {
- auto t = T();
- BatchedBenchmark<T>(
- state,
- /* prepare_vec = */
- [](InlVec<T>* vec, size_t) {
- vec->clear();
- vec->resize(FromSize);
- },
- /* test_vec = */
- [&](InlVec<T>* vec, size_t) {
- benchmark::DoNotOptimize(t);
- auto* pos = vec->data() + (vec->size() / 2);
- vec->insert(pos, t);
- });
-}
-ABSL_INTERNAL_BENCHMARK_TWO_SIZE(BM_InsertSizeRef, TrivialType);
-ABSL_INTERNAL_BENCHMARK_TWO_SIZE(BM_InsertSizeRef, NontrivialType);
-
-template <typename T, size_t FromSize, size_t ToSize>
-void BM_InsertRange(benchmark::State& state) {
- InlVec<T> other_vec(ToSize);
- BatchedBenchmark<T>(
- state,
- /* prepare_vec = */
- [](InlVec<T>* vec, size_t) {
- vec->clear();
- vec->resize(FromSize);
- },
- /* test_vec = */
- [&](InlVec<T>* vec, size_t) {
- benchmark::DoNotOptimize(other_vec);
- auto* pos = vec->data() + (vec->size() / 2);
- vec->insert(pos, other_vec.begin(), other_vec.end());
- });
-}
-ABSL_INTERNAL_BENCHMARK_TWO_SIZE(BM_InsertRange, TrivialType);
-ABSL_INTERNAL_BENCHMARK_TWO_SIZE(BM_InsertRange, NontrivialType);
-
-template <typename T, size_t FromSize>
-void BM_EmplaceBack(benchmark::State& state) {
- BatchedBenchmark<T>(
- state,
- /* prepare_vec = */
- [](InlVec<T>* vec, size_t) {
- vec->clear();
- vec->resize(FromSize);
- },
- /* test_vec = */
- [](InlVec<T>* vec, size_t) { vec->emplace_back(); });
-}
-ABSL_INTERNAL_BENCHMARK_ONE_SIZE(BM_EmplaceBack, TrivialType);
-ABSL_INTERNAL_BENCHMARK_ONE_SIZE(BM_EmplaceBack, NontrivialType);
-
-template <typename T, size_t FromSize>
-void BM_PopBack(benchmark::State& state) {
- BatchedBenchmark<T>(
- state,
- /* prepare_vec = */
- [](InlVec<T>* vec, size_t) {
- vec->clear();
- vec->resize(FromSize);
- },
- /* test_vec = */
- [](InlVec<T>* vec, size_t) { vec->pop_back(); });
-}
-ABSL_INTERNAL_BENCHMARK_ONE_SIZE(BM_PopBack, TrivialType);
-ABSL_INTERNAL_BENCHMARK_ONE_SIZE(BM_PopBack, NontrivialType);
-
-template <typename T, size_t FromSize>
-void BM_EraseOne(benchmark::State& state) {
- BatchedBenchmark<T>(
- state,
- /* prepare_vec = */
- [](InlVec<T>* vec, size_t) {
- vec->clear();
- vec->resize(FromSize);
- },
- /* test_vec = */
- [](InlVec<T>* vec, size_t) {
- auto* pos = vec->data() + (vec->size() / 2);
- vec->erase(pos);
- });
-}
-ABSL_INTERNAL_BENCHMARK_ONE_SIZE(BM_EraseOne, TrivialType);
-ABSL_INTERNAL_BENCHMARK_ONE_SIZE(BM_EraseOne, NontrivialType);
-
-template <typename T, size_t FromSize>
-void BM_EraseRange(benchmark::State& state) {
- BatchedBenchmark<T>(
- state,
- /* prepare_vec = */
- [](InlVec<T>* vec, size_t) {
- vec->clear();
- vec->resize(FromSize);
- },
- /* test_vec = */
- [](InlVec<T>* vec, size_t) {
- auto* pos = vec->data() + (vec->size() / 2);
- vec->erase(pos, pos + 1);
- });
-}
-ABSL_INTERNAL_BENCHMARK_ONE_SIZE(BM_EraseRange, TrivialType);
-ABSL_INTERNAL_BENCHMARK_ONE_SIZE(BM_EraseRange, NontrivialType);
-
-template <typename T, size_t FromSize>
-void BM_Clear(benchmark::State& state) {
- BatchedBenchmark<T>(
- state,
- /* prepare_vec = */ [](InlVec<T>* vec, size_t) { vec->resize(FromSize); },
- /* test_vec = */ [](InlVec<T>* vec, size_t) { vec->clear(); });
-}
-ABSL_INTERNAL_BENCHMARK_ONE_SIZE(BM_Clear, TrivialType);
-ABSL_INTERNAL_BENCHMARK_ONE_SIZE(BM_Clear, NontrivialType);
-
-template <typename T, size_t FromSize, size_t ToCapacity>
-void BM_Reserve(benchmark::State& state) {
- BatchedBenchmark<T>(
- state,
- /* prepare_vec = */
- [](InlVec<T>* vec, size_t) {
- vec->clear();
- vec->resize(FromSize);
- },
- /* test_vec = */
- [](InlVec<T>* vec, size_t) { vec->reserve(ToCapacity); });
-}
-ABSL_INTERNAL_BENCHMARK_TWO_SIZE(BM_Reserve, TrivialType);
-ABSL_INTERNAL_BENCHMARK_TWO_SIZE(BM_Reserve, NontrivialType);
-
-template <typename T, size_t FromCapacity, size_t ToCapacity>
-void BM_ShrinkToFit(benchmark::State& state) {
- BatchedBenchmark<T>(
- state,
- /* prepare_vec = */
- [](InlVec<T>* vec, size_t) {
- vec->clear();
- vec->resize(ToCapacity);
- vec->reserve(FromCapacity);
- },
- /* test_vec = */ [](InlVec<T>* vec, size_t) { vec->shrink_to_fit(); });
-}
-ABSL_INTERNAL_BENCHMARK_TWO_SIZE(BM_ShrinkToFit, TrivialType);
-ABSL_INTERNAL_BENCHMARK_TWO_SIZE(BM_ShrinkToFit, NontrivialType);
-
-template <typename T, size_t FromSize, size_t ToSize>
-void BM_Swap(benchmark::State& state) {
- using VecT = InlVec<T>;
- std::array<VecT, kBatchSize> vector_batch{};
- BatchedBenchmark<T>(
- state,
- /* prepare_vec = */
- [&](InlVec<T>* vec, size_t i) {
- vector_batch[i].clear();
- vector_batch[i].resize(ToSize);
- vec->resize(FromSize);
- },
- /* test_vec = */
- [&](InlVec<T>* vec, size_t i) {
- using std::swap;
- benchmark::DoNotOptimize(vector_batch[i]);
- swap(*vec, vector_batch[i]);
- });
-}
-ABSL_INTERNAL_BENCHMARK_TWO_SIZE(BM_Swap, TrivialType);
-ABSL_INTERNAL_BENCHMARK_TWO_SIZE(BM_Swap, NontrivialType);
-
-} // namespace
diff --git a/third_party/abseil-cpp/absl/container/inlined_vector_exception_safety_test.cc b/third_party/abseil-cpp/absl/container/inlined_vector_exception_safety_test.cc
deleted file mode 100644
index 0e6a05b..0000000
--- a/third_party/abseil-cpp/absl/container/inlined_vector_exception_safety_test.cc
+++ /dev/null
@@ -1,508 +0,0 @@
-// Copyright 2019 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/container/inlined_vector.h"
-
-#include "absl/base/config.h"
-
-#if defined(ABSL_HAVE_EXCEPTIONS)
-
-#include <array>
-#include <initializer_list>
-#include <iterator>
-#include <memory>
-#include <utility>
-
-#include "gtest/gtest.h"
-#include "absl/base/internal/exception_safety_testing.h"
-
-namespace {
-
-constexpr size_t kInlinedCapacity = 4;
-constexpr size_t kLargeSize = kInlinedCapacity * 2;
-constexpr size_t kSmallSize = kInlinedCapacity / 2;
-
-using Thrower = testing::ThrowingValue<>;
-using MovableThrower = testing::ThrowingValue<testing::TypeSpec::kNoThrowMove>;
-using ThrowAlloc = testing::ThrowingAllocator<Thrower>;
-
-using ThrowerVec = absl::InlinedVector<Thrower, kInlinedCapacity>;
-using MovableThrowerVec = absl::InlinedVector<MovableThrower, kInlinedCapacity>;
-
-using ThrowAllocThrowerVec =
- absl::InlinedVector<Thrower, kInlinedCapacity, ThrowAlloc>;
-using ThrowAllocMovableThrowerVec =
- absl::InlinedVector<MovableThrower, kInlinedCapacity, ThrowAlloc>;
-
-// In GCC, if an element of a `std::initializer_list` throws during construction
-// the elements that were constructed before it are not destroyed. This causes
-// incorrect exception safety test failures. Thus, `testing::nothrow_ctor` is
-// required. See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66139
-#define ABSL_INTERNAL_MAKE_INIT_LIST(T, N) \
- (N > kInlinedCapacity \
- ? std::initializer_list<T>{T(0, testing::nothrow_ctor), \
- T(1, testing::nothrow_ctor), \
- T(2, testing::nothrow_ctor), \
- T(3, testing::nothrow_ctor), \
- T(4, testing::nothrow_ctor), \
- T(5, testing::nothrow_ctor), \
- T(6, testing::nothrow_ctor), \
- T(7, testing::nothrow_ctor)} \
- \
- : std::initializer_list<T>{T(0, testing::nothrow_ctor), \
- T(1, testing::nothrow_ctor)})
-static_assert(kLargeSize == 8, "Must update ABSL_INTERNAL_MAKE_INIT_LIST(...)");
-static_assert(kSmallSize == 2, "Must update ABSL_INTERNAL_MAKE_INIT_LIST(...)");
-
-template <typename TheVecT, size_t... TheSizes>
-class TestParams {
- public:
- using VecT = TheVecT;
- constexpr static size_t GetSizeAt(size_t i) { return kSizes[1 + i]; }
-
- private:
- constexpr static size_t kSizes[1 + sizeof...(TheSizes)] = {1, TheSizes...};
-};
-
-using NoSizeTestParams =
- ::testing::Types<TestParams<ThrowerVec>, TestParams<MovableThrowerVec>,
- TestParams<ThrowAllocThrowerVec>,
- TestParams<ThrowAllocMovableThrowerVec>>;
-
-using OneSizeTestParams =
- ::testing::Types<TestParams<ThrowerVec, kLargeSize>,
- TestParams<ThrowerVec, kSmallSize>,
- TestParams<MovableThrowerVec, kLargeSize>,
- TestParams<MovableThrowerVec, kSmallSize>,
- TestParams<ThrowAllocThrowerVec, kLargeSize>,
- TestParams<ThrowAllocThrowerVec, kSmallSize>,
- TestParams<ThrowAllocMovableThrowerVec, kLargeSize>,
- TestParams<ThrowAllocMovableThrowerVec, kSmallSize>>;
-
-using TwoSizeTestParams = ::testing::Types<
- TestParams<ThrowerVec, kLargeSize, kLargeSize>,
- TestParams<ThrowerVec, kLargeSize, kSmallSize>,
- TestParams<ThrowerVec, kSmallSize, kLargeSize>,
- TestParams<ThrowerVec, kSmallSize, kSmallSize>,
- TestParams<MovableThrowerVec, kLargeSize, kLargeSize>,
- TestParams<MovableThrowerVec, kLargeSize, kSmallSize>,
- TestParams<MovableThrowerVec, kSmallSize, kLargeSize>,
- TestParams<MovableThrowerVec, kSmallSize, kSmallSize>,
- TestParams<ThrowAllocThrowerVec, kLargeSize, kLargeSize>,
- TestParams<ThrowAllocThrowerVec, kLargeSize, kSmallSize>,
- TestParams<ThrowAllocThrowerVec, kSmallSize, kLargeSize>,
- TestParams<ThrowAllocThrowerVec, kSmallSize, kSmallSize>,
- TestParams<ThrowAllocMovableThrowerVec, kLargeSize, kLargeSize>,
- TestParams<ThrowAllocMovableThrowerVec, kLargeSize, kSmallSize>,
- TestParams<ThrowAllocMovableThrowerVec, kSmallSize, kLargeSize>,
- TestParams<ThrowAllocMovableThrowerVec, kSmallSize, kSmallSize>>;
-
-template <typename>
-struct NoSizeTest : ::testing::Test {};
-TYPED_TEST_SUITE(NoSizeTest, NoSizeTestParams);
-
-template <typename>
-struct OneSizeTest : ::testing::Test {};
-TYPED_TEST_SUITE(OneSizeTest, OneSizeTestParams);
-
-template <typename>
-struct TwoSizeTest : ::testing::Test {};
-TYPED_TEST_SUITE(TwoSizeTest, TwoSizeTestParams);
-
-template <typename VecT>
-bool InlinedVectorInvariants(VecT* vec) {
- if (*vec != *vec) return false;
- if (vec->size() > vec->capacity()) return false;
- if (vec->size() > vec->max_size()) return false;
- if (vec->capacity() > vec->max_size()) return false;
- if (vec->data() != std::addressof(vec->at(0))) return false;
- if (vec->data() != vec->begin()) return false;
- if (*vec->data() != *vec->begin()) return false;
- if (vec->begin() > vec->end()) return false;
- if ((vec->end() - vec->begin()) != vec->size()) return false;
- if (std::distance(vec->begin(), vec->end()) != vec->size()) return false;
- return true;
-}
-
-// Function that always returns false is correct, but refactoring is required
-// for clarity. It's needed to express that, as a contract, certain operations
-// should not throw at all. Execution of this function means an exception was
-// thrown and thus the test should fail.
-// TODO(johnsoncj): Add `testing::NoThrowGuarantee` to the framework
-template <typename VecT>
-bool NoThrowGuarantee(VecT* /* vec */) {
- return false;
-}
-
-TYPED_TEST(NoSizeTest, DefaultConstructor) {
- using VecT = typename TypeParam::VecT;
- using allocator_type = typename VecT::allocator_type;
-
- testing::TestThrowingCtor<VecT>();
-
- testing::TestThrowingCtor<VecT>(allocator_type{});
-}
-
-TYPED_TEST(OneSizeTest, SizeConstructor) {
- using VecT = typename TypeParam::VecT;
- using allocator_type = typename VecT::allocator_type;
- constexpr static auto size = TypeParam::GetSizeAt(0);
-
- testing::TestThrowingCtor<VecT>(size);
-
- testing::TestThrowingCtor<VecT>(size, allocator_type{});
-}
-
-TYPED_TEST(OneSizeTest, SizeRefConstructor) {
- using VecT = typename TypeParam::VecT;
- using value_type = typename VecT::value_type;
- using allocator_type = typename VecT::allocator_type;
- constexpr static auto size = TypeParam::GetSizeAt(0);
-
- testing::TestThrowingCtor<VecT>(size, value_type{});
-
- testing::TestThrowingCtor<VecT>(size, value_type{}, allocator_type{});
-}
-
-TYPED_TEST(OneSizeTest, InitializerListConstructor) {
- using VecT = typename TypeParam::VecT;
- using value_type = typename VecT::value_type;
- using allocator_type = typename VecT::allocator_type;
- constexpr static auto size = TypeParam::GetSizeAt(0);
-
- testing::TestThrowingCtor<VecT>(
- ABSL_INTERNAL_MAKE_INIT_LIST(value_type, size));
-
- testing::TestThrowingCtor<VecT>(
- ABSL_INTERNAL_MAKE_INIT_LIST(value_type, size), allocator_type{});
-}
-
-TYPED_TEST(OneSizeTest, RangeConstructor) {
- using VecT = typename TypeParam::VecT;
- using value_type = typename VecT::value_type;
- using allocator_type = typename VecT::allocator_type;
- constexpr static auto size = TypeParam::GetSizeAt(0);
-
- std::array<value_type, size> arr{};
-
- testing::TestThrowingCtor<VecT>(arr.begin(), arr.end());
-
- testing::TestThrowingCtor<VecT>(arr.begin(), arr.end(), allocator_type{});
-}
-
-TYPED_TEST(OneSizeTest, CopyConstructor) {
- using VecT = typename TypeParam::VecT;
- using allocator_type = typename VecT::allocator_type;
- constexpr static auto size = TypeParam::GetSizeAt(0);
-
- VecT other_vec{size};
-
- testing::TestThrowingCtor<VecT>(other_vec);
-
- testing::TestThrowingCtor<VecT>(other_vec, allocator_type{});
-}
-
-TYPED_TEST(OneSizeTest, MoveConstructor) {
- using VecT = typename TypeParam::VecT;
- using allocator_type = typename VecT::allocator_type;
- constexpr static auto size = TypeParam::GetSizeAt(0);
-
- if (!absl::allocator_is_nothrow<allocator_type>::value) {
- testing::TestThrowingCtor<VecT>(VecT{size});
-
- testing::TestThrowingCtor<VecT>(VecT{size}, allocator_type{});
- }
-}
-
-TYPED_TEST(TwoSizeTest, Assign) {
- using VecT = typename TypeParam::VecT;
- using value_type = typename VecT::value_type;
- constexpr static auto from_size = TypeParam::GetSizeAt(0);
- constexpr static auto to_size = TypeParam::GetSizeAt(1);
-
- auto tester = testing::MakeExceptionSafetyTester()
- .WithInitialValue(VecT{from_size})
- .WithContracts(InlinedVectorInvariants<VecT>);
-
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- *vec = ABSL_INTERNAL_MAKE_INIT_LIST(value_type, to_size);
- }));
-
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- VecT other_vec{to_size};
- *vec = other_vec;
- }));
-
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- VecT other_vec{to_size};
- *vec = std::move(other_vec);
- }));
-
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- value_type val{};
- vec->assign(to_size, val);
- }));
-
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- vec->assign(ABSL_INTERNAL_MAKE_INIT_LIST(value_type, to_size));
- }));
-
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- std::array<value_type, to_size> arr{};
- vec->assign(arr.begin(), arr.end());
- }));
-}
-
-TYPED_TEST(TwoSizeTest, Resize) {
- using VecT = typename TypeParam::VecT;
- using value_type = typename VecT::value_type;
- constexpr static auto from_size = TypeParam::GetSizeAt(0);
- constexpr static auto to_size = TypeParam::GetSizeAt(1);
-
- auto tester = testing::MakeExceptionSafetyTester()
- .WithInitialValue(VecT{from_size})
- .WithContracts(InlinedVectorInvariants<VecT>,
- testing::strong_guarantee);
-
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- vec->resize(to_size); //
- }));
-
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- vec->resize(to_size, value_type{}); //
- }));
-}
-
-TYPED_TEST(OneSizeTest, Insert) {
- using VecT = typename TypeParam::VecT;
- using value_type = typename VecT::value_type;
- constexpr static auto from_size = TypeParam::GetSizeAt(0);
-
- auto tester = testing::MakeExceptionSafetyTester()
- .WithInitialValue(VecT{from_size})
- .WithContracts(InlinedVectorInvariants<VecT>);
-
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- auto it = vec->begin();
- vec->insert(it, value_type{});
- }));
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- auto it = vec->begin() + (vec->size() / 2);
- vec->insert(it, value_type{});
- }));
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- auto it = vec->end();
- vec->insert(it, value_type{});
- }));
-}
-
-TYPED_TEST(TwoSizeTest, Insert) {
- using VecT = typename TypeParam::VecT;
- using value_type = typename VecT::value_type;
- constexpr static auto from_size = TypeParam::GetSizeAt(0);
- constexpr static auto count = TypeParam::GetSizeAt(1);
-
- auto tester = testing::MakeExceptionSafetyTester()
- .WithInitialValue(VecT{from_size})
- .WithContracts(InlinedVectorInvariants<VecT>);
-
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- auto it = vec->begin();
- vec->insert(it, count, value_type{});
- }));
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- auto it = vec->begin() + (vec->size() / 2);
- vec->insert(it, count, value_type{});
- }));
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- auto it = vec->end();
- vec->insert(it, count, value_type{});
- }));
-
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- auto it = vec->begin();
- vec->insert(it, ABSL_INTERNAL_MAKE_INIT_LIST(value_type, count));
- }));
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- auto it = vec->begin() + (vec->size() / 2);
- vec->insert(it, ABSL_INTERNAL_MAKE_INIT_LIST(value_type, count));
- }));
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- auto it = vec->end();
- vec->insert(it, ABSL_INTERNAL_MAKE_INIT_LIST(value_type, count));
- }));
-
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- auto it = vec->begin();
- std::array<value_type, count> arr{};
- vec->insert(it, arr.begin(), arr.end());
- }));
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- auto it = vec->begin() + (vec->size() / 2);
- std::array<value_type, count> arr{};
- vec->insert(it, arr.begin(), arr.end());
- }));
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- auto it = vec->end();
- std::array<value_type, count> arr{};
- vec->insert(it, arr.begin(), arr.end());
- }));
-}
-
-TYPED_TEST(OneSizeTest, EmplaceBack) {
- using VecT = typename TypeParam::VecT;
- constexpr static auto size = TypeParam::GetSizeAt(0);
-
- // For testing calls to `emplace_back(...)` that reallocate.
- VecT full_vec{size};
- full_vec.resize(full_vec.capacity());
-
- // For testing calls to `emplace_back(...)` that don't reallocate.
- VecT nonfull_vec{size};
- nonfull_vec.reserve(size + 1);
-
- auto tester = testing::MakeExceptionSafetyTester().WithContracts(
- InlinedVectorInvariants<VecT>);
-
- EXPECT_TRUE(tester.WithInitialValue(nonfull_vec).Test([](VecT* vec) {
- vec->emplace_back();
- }));
-
- EXPECT_TRUE(tester.WithInitialValue(full_vec).Test(
- [](VecT* vec) { vec->emplace_back(); }));
-}
-
-TYPED_TEST(OneSizeTest, PopBack) {
- using VecT = typename TypeParam::VecT;
- constexpr static auto size = TypeParam::GetSizeAt(0);
-
- auto tester = testing::MakeExceptionSafetyTester()
- .WithInitialValue(VecT{size})
- .WithContracts(NoThrowGuarantee<VecT>);
-
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- vec->pop_back(); //
- }));
-}
-
-TYPED_TEST(OneSizeTest, Erase) {
- using VecT = typename TypeParam::VecT;
- constexpr static auto size = TypeParam::GetSizeAt(0);
-
- auto tester = testing::MakeExceptionSafetyTester()
- .WithInitialValue(VecT{size})
- .WithContracts(InlinedVectorInvariants<VecT>);
-
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- auto it = vec->begin();
- vec->erase(it);
- }));
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- auto it = vec->begin() + (vec->size() / 2);
- vec->erase(it);
- }));
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- auto it = vec->begin() + (vec->size() - 1);
- vec->erase(it);
- }));
-
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- auto it = vec->begin();
- vec->erase(it, it);
- }));
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- auto it = vec->begin() + (vec->size() / 2);
- vec->erase(it, it);
- }));
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- auto it = vec->begin() + (vec->size() - 1);
- vec->erase(it, it);
- }));
-
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- auto it = vec->begin();
- vec->erase(it, it + 1);
- }));
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- auto it = vec->begin() + (vec->size() / 2);
- vec->erase(it, it + 1);
- }));
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- auto it = vec->begin() + (vec->size() - 1);
- vec->erase(it, it + 1);
- }));
-}
-
-TYPED_TEST(OneSizeTest, Clear) {
- using VecT = typename TypeParam::VecT;
- constexpr static auto size = TypeParam::GetSizeAt(0);
-
- auto tester = testing::MakeExceptionSafetyTester()
- .WithInitialValue(VecT{size})
- .WithContracts(NoThrowGuarantee<VecT>);
-
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- vec->clear(); //
- }));
-}
-
-TYPED_TEST(TwoSizeTest, Reserve) {
- using VecT = typename TypeParam::VecT;
- constexpr static auto from_size = TypeParam::GetSizeAt(0);
- constexpr static auto to_capacity = TypeParam::GetSizeAt(1);
-
- auto tester = testing::MakeExceptionSafetyTester()
- .WithInitialValue(VecT{from_size})
- .WithContracts(InlinedVectorInvariants<VecT>);
-
- EXPECT_TRUE(tester.Test([](VecT* vec) { vec->reserve(to_capacity); }));
-}
-
-TYPED_TEST(OneSizeTest, ShrinkToFit) {
- using VecT = typename TypeParam::VecT;
- constexpr static auto size = TypeParam::GetSizeAt(0);
-
- auto tester = testing::MakeExceptionSafetyTester()
- .WithInitialValue(VecT{size})
- .WithContracts(InlinedVectorInvariants<VecT>);
-
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- vec->shrink_to_fit(); //
- }));
-}
-
-TYPED_TEST(TwoSizeTest, Swap) {
- using VecT = typename TypeParam::VecT;
- constexpr static auto from_size = TypeParam::GetSizeAt(0);
- constexpr static auto to_size = TypeParam::GetSizeAt(1);
-
- auto tester = testing::MakeExceptionSafetyTester()
- .WithInitialValue(VecT{from_size})
- .WithContracts(InlinedVectorInvariants<VecT>);
-
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- VecT other_vec{to_size};
- vec->swap(other_vec);
- }));
-
- EXPECT_TRUE(tester.Test([](VecT* vec) {
- using std::swap;
- VecT other_vec{to_size};
- swap(*vec, other_vec);
- }));
-}
-
-} // namespace
-
-#endif // defined(ABSL_HAVE_EXCEPTIONS)
diff --git a/third_party/abseil-cpp/absl/container/inlined_vector_test.cc b/third_party/abseil-cpp/absl/container/inlined_vector_test.cc
deleted file mode 100644
index 1dc6c81..0000000
--- a/third_party/abseil-cpp/absl/container/inlined_vector_test.cc
+++ /dev/null
@@ -1,2025 +0,0 @@
-// Copyright 2019 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/container/inlined_vector.h"
-
-#include <algorithm>
-#include <forward_list>
-#include <iterator>
-#include <list>
-#include <memory>
-#include <scoped_allocator>
-#include <sstream>
-#include <stdexcept>
-#include <string>
-#include <utility>
-#include <vector>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/base/attributes.h"
-#include "absl/base/internal/exception_testing.h"
-#include "absl/base/internal/raw_logging.h"
-#include "absl/base/macros.h"
-#include "absl/base/options.h"
-#include "absl/container/internal/counting_allocator.h"
-#include "absl/container/internal/test_instance_tracker.h"
-#include "absl/hash/hash_testing.h"
-#include "absl/memory/memory.h"
-#include "absl/strings/str_cat.h"
-
-namespace {
-
-using absl::container_internal::CountingAllocator;
-using absl::test_internal::CopyableMovableInstance;
-using absl::test_internal::CopyableOnlyInstance;
-using absl::test_internal::InstanceTracker;
-using testing::AllOf;
-using testing::Each;
-using testing::ElementsAre;
-using testing::ElementsAreArray;
-using testing::Eq;
-using testing::Gt;
-using testing::Pointwise;
-using testing::PrintToString;
-
-using IntVec = absl::InlinedVector<int, 8>;
-
-MATCHER_P(SizeIs, n, "") {
- return testing::ExplainMatchResult(n, arg.size(), result_listener);
-}
-
-MATCHER_P(CapacityIs, n, "") {
- return testing::ExplainMatchResult(n, arg.capacity(), result_listener);
-}
-
-MATCHER_P(ValueIs, e, "") {
- return testing::ExplainMatchResult(e, arg.value(), result_listener);
-}
-
-// TODO(bsamwel): Add support for movable-only types.
-
-// Test fixture for typed tests on BaseCountedInstance derived classes, see
-// test_instance_tracker.h.
-template <typename T>
-class InstanceTest : public ::testing::Test {};
-TYPED_TEST_SUITE_P(InstanceTest);
-
-// A simple reference counted class to make sure that the proper elements are
-// destroyed in the erase(begin, end) test.
-class RefCounted {
- public:
- RefCounted(int value, int* count) : value_(value), count_(count) { Ref(); }
-
- RefCounted(const RefCounted& v) : value_(v.value_), count_(v.count_) {
- Ref();
- }
-
- ~RefCounted() {
- Unref();
- count_ = nullptr;
- }
-
- friend void swap(RefCounted& a, RefCounted& b) {
- using std::swap;
- swap(a.value_, b.value_);
- swap(a.count_, b.count_);
- }
-
- RefCounted& operator=(RefCounted v) {
- using std::swap;
- swap(*this, v);
- return *this;
- }
-
- void Ref() const {
- ABSL_RAW_CHECK(count_ != nullptr, "");
- ++(*count_);
- }
-
- void Unref() const {
- --(*count_);
- ABSL_RAW_CHECK(*count_ >= 0, "");
- }
-
- int value_;
- int* count_;
-};
-
-using RefCountedVec = absl::InlinedVector<RefCounted, 8>;
-
-// A class with a vtable pointer
-class Dynamic {
- public:
- virtual ~Dynamic() {}
-};
-
-using DynamicVec = absl::InlinedVector<Dynamic, 8>;
-
-// Append 0..len-1 to *v
-template <typename Container>
-static void Fill(Container* v, size_t len, int offset = 0) {
- for (size_t i = 0; i < len; i++) {
- v->push_back(static_cast<int>(i) + offset);
- }
-}
-
-static IntVec Fill(size_t len, int offset = 0) {
- IntVec v;
- Fill(&v, len, offset);
- return v;
-}
-
-TEST(IntVec, SimpleOps) {
- for (size_t len = 0; len < 20; len++) {
- IntVec v;
- const IntVec& cv = v; // const alias
-
- Fill(&v, len);
- EXPECT_EQ(len, v.size());
- EXPECT_LE(len, v.capacity());
-
- for (size_t i = 0; i < len; i++) {
- EXPECT_EQ(static_cast<int>(i), v[i]);
- EXPECT_EQ(static_cast<int>(i), v.at(i));
- }
- EXPECT_EQ(v.begin(), v.data());
- EXPECT_EQ(cv.begin(), cv.data());
-
- size_t counter = 0;
- for (IntVec::iterator iter = v.begin(); iter != v.end(); ++iter) {
- EXPECT_EQ(static_cast<int>(counter), *iter);
- counter++;
- }
- EXPECT_EQ(counter, len);
-
- counter = 0;
- for (IntVec::const_iterator iter = v.begin(); iter != v.end(); ++iter) {
- EXPECT_EQ(static_cast<int>(counter), *iter);
- counter++;
- }
- EXPECT_EQ(counter, len);
-
- counter = 0;
- for (IntVec::const_iterator iter = v.cbegin(); iter != v.cend(); ++iter) {
- EXPECT_EQ(static_cast<int>(counter), *iter);
- counter++;
- }
- EXPECT_EQ(counter, len);
-
- if (len > 0) {
- EXPECT_EQ(0, v.front());
- EXPECT_EQ(static_cast<int>(len - 1), v.back());
- v.pop_back();
- EXPECT_EQ(len - 1, v.size());
- for (size_t i = 0; i < v.size(); ++i) {
- EXPECT_EQ(static_cast<int>(i), v[i]);
- EXPECT_EQ(static_cast<int>(i), v.at(i));
- }
- }
- }
-}
-
-TEST(IntVec, PopBackNoOverflow) {
- IntVec v = {1};
- v.pop_back();
- EXPECT_EQ(v.size(), 0u);
-}
-
-TEST(IntVec, AtThrows) {
- IntVec v = {1, 2, 3};
- EXPECT_EQ(v.at(2), 3);
- ABSL_BASE_INTERNAL_EXPECT_FAIL(v.at(3), std::out_of_range,
- "failed bounds check");
-}
-
-TEST(IntVec, ReverseIterator) {
- for (size_t len = 0; len < 20; len++) {
- IntVec v;
- Fill(&v, len);
-
- size_t counter = len;
- for (IntVec::reverse_iterator iter = v.rbegin(); iter != v.rend(); ++iter) {
- counter--;
- EXPECT_EQ(static_cast<int>(counter), *iter);
- }
- EXPECT_EQ(counter, 0u);
-
- counter = len;
- for (IntVec::const_reverse_iterator iter = v.rbegin(); iter != v.rend();
- ++iter) {
- counter--;
- EXPECT_EQ(static_cast<int>(counter), *iter);
- }
- EXPECT_EQ(counter, 0u);
-
- counter = len;
- for (IntVec::const_reverse_iterator iter = v.crbegin(); iter != v.crend();
- ++iter) {
- counter--;
- EXPECT_EQ(static_cast<int>(counter), *iter);
- }
- EXPECT_EQ(counter, 0u);
- }
-}
-
-TEST(IntVec, Erase) {
- for (size_t len = 1; len < 20; len++) {
- for (size_t i = 0; i < len; ++i) {
- IntVec v;
- Fill(&v, len);
- v.erase(v.begin() + i);
- EXPECT_EQ(len - 1, v.size());
- for (size_t j = 0; j < i; ++j) {
- EXPECT_EQ(static_cast<int>(j), v[j]);
- }
- for (size_t j = i; j < len - 1; ++j) {
- EXPECT_EQ(static_cast<int>(j + 1), v[j]);
- }
- }
- }
-}
-
-TEST(IntVec, Hardened) {
- IntVec v;
- Fill(&v, 10);
- EXPECT_EQ(v[9], 9);
-#if !defined(NDEBUG) || ABSL_OPTION_HARDENED
- EXPECT_DEATH_IF_SUPPORTED(v[10], "");
- EXPECT_DEATH_IF_SUPPORTED(v[static_cast<size_t>(-1)], "");
- EXPECT_DEATH_IF_SUPPORTED(v.resize(v.max_size() + 1), "");
-#endif
-}
-
-// At the end of this test loop, the elements between [erase_begin, erase_end)
-// should have reference counts == 0, and all others elements should have
-// reference counts == 1.
-TEST(RefCountedVec, EraseBeginEnd) {
- for (size_t len = 1; len < 20; ++len) {
- for (size_t erase_begin = 0; erase_begin < len; ++erase_begin) {
- for (size_t erase_end = erase_begin; erase_end <= len; ++erase_end) {
- std::vector<int> counts(len, 0);
- RefCountedVec v;
- for (size_t i = 0; i < len; ++i) {
- v.push_back(RefCounted(static_cast<int>(i), &counts[i]));
- }
-
- size_t erase_len = erase_end - erase_begin;
-
- v.erase(v.begin() + erase_begin, v.begin() + erase_end);
-
- EXPECT_EQ(len - erase_len, v.size());
-
- // Check the elements before the first element erased.
- for (size_t i = 0; i < erase_begin; ++i) {
- EXPECT_EQ(static_cast<int>(i), v[i].value_);
- }
-
- // Check the elements after the first element erased.
- for (size_t i = erase_begin; i < v.size(); ++i) {
- EXPECT_EQ(static_cast<int>(i + erase_len), v[i].value_);
- }
-
- // Check that the elements at the beginning are preserved.
- for (size_t i = 0; i < erase_begin; ++i) {
- EXPECT_EQ(1, counts[i]);
- }
-
- // Check that the erased elements are destroyed
- for (size_t i = erase_begin; i < erase_end; ++i) {
- EXPECT_EQ(0, counts[i]);
- }
-
- // Check that the elements at the end are preserved.
- for (size_t i = erase_end; i < len; ++i) {
- EXPECT_EQ(1, counts[i]);
- }
- }
- }
- }
-}
-
-struct NoDefaultCtor {
- explicit NoDefaultCtor(int) {}
-};
-struct NoCopy {
- NoCopy() {}
- NoCopy(const NoCopy&) = delete;
-};
-struct NoAssign {
- NoAssign() {}
- NoAssign& operator=(const NoAssign&) = delete;
-};
-struct MoveOnly {
- MoveOnly() {}
- MoveOnly(MoveOnly&&) = default;
- MoveOnly& operator=(MoveOnly&&) = default;
-};
-TEST(InlinedVectorTest, NoDefaultCtor) {
- absl::InlinedVector<NoDefaultCtor, 1> v(10, NoDefaultCtor(2));
- (void)v;
-}
-TEST(InlinedVectorTest, NoCopy) {
- absl::InlinedVector<NoCopy, 1> v(10);
- (void)v;
-}
-TEST(InlinedVectorTest, NoAssign) {
- absl::InlinedVector<NoAssign, 1> v(10);
- (void)v;
-}
-TEST(InlinedVectorTest, MoveOnly) {
- absl::InlinedVector<MoveOnly, 2> v;
- v.push_back(MoveOnly{});
- v.push_back(MoveOnly{});
- v.push_back(MoveOnly{});
- v.erase(v.begin());
- v.push_back(MoveOnly{});
- v.erase(v.begin(), v.begin() + 1);
- v.insert(v.begin(), MoveOnly{});
- v.emplace(v.begin());
- v.emplace(v.begin(), MoveOnly{});
-}
-TEST(InlinedVectorTest, Noexcept) {
- EXPECT_TRUE(std::is_nothrow_move_constructible<IntVec>::value);
- EXPECT_TRUE((std::is_nothrow_move_constructible<
- absl::InlinedVector<MoveOnly, 2>>::value));
-
- struct MoveCanThrow {
- MoveCanThrow(MoveCanThrow&&) {}
- };
- EXPECT_EQ(absl::default_allocator_is_nothrow::value,
- (std::is_nothrow_move_constructible<
- absl::InlinedVector<MoveCanThrow, 2>>::value));
-}
-
-TEST(InlinedVectorTest, EmplaceBack) {
- absl::InlinedVector<std::pair<std::string, int>, 1> v;
-
- auto& inlined_element = v.emplace_back("answer", 42);
- EXPECT_EQ(&inlined_element, &v[0]);
- EXPECT_EQ(inlined_element.first, "answer");
- EXPECT_EQ(inlined_element.second, 42);
-
- auto& allocated_element = v.emplace_back("taxicab", 1729);
- EXPECT_EQ(&allocated_element, &v[1]);
- EXPECT_EQ(allocated_element.first, "taxicab");
- EXPECT_EQ(allocated_element.second, 1729);
-}
-
-TEST(InlinedVectorTest, ShrinkToFitGrowingVector) {
- absl::InlinedVector<std::pair<std::string, int>, 1> v;
-
- v.shrink_to_fit();
- EXPECT_EQ(v.capacity(), 1u);
-
- v.emplace_back("answer", 42);
- v.shrink_to_fit();
- EXPECT_EQ(v.capacity(), 1u);
-
- v.emplace_back("taxicab", 1729);
- EXPECT_GE(v.capacity(), 2u);
- v.shrink_to_fit();
- EXPECT_EQ(v.capacity(), 2u);
-
- v.reserve(100);
- EXPECT_GE(v.capacity(), 100u);
- v.shrink_to_fit();
- EXPECT_EQ(v.capacity(), 2u);
-}
-
-TEST(InlinedVectorTest, ShrinkToFitEdgeCases) {
- {
- absl::InlinedVector<std::pair<std::string, int>, 1> v;
- v.emplace_back("answer", 42);
- v.emplace_back("taxicab", 1729);
- EXPECT_GE(v.capacity(), 2u);
- v.pop_back();
- v.shrink_to_fit();
- EXPECT_EQ(v.capacity(), 1u);
- EXPECT_EQ(v[0].first, "answer");
- EXPECT_EQ(v[0].second, 42);
- }
-
- {
- absl::InlinedVector<std::string, 2> v(100);
- v.resize(0);
- v.shrink_to_fit();
- EXPECT_EQ(v.capacity(), 2u); // inlined capacity
- }
-
- {
- absl::InlinedVector<std::string, 2> v(100);
- v.resize(1);
- v.shrink_to_fit();
- EXPECT_EQ(v.capacity(), 2u); // inlined capacity
- }
-
- {
- absl::InlinedVector<std::string, 2> v(100);
- v.resize(2);
- v.shrink_to_fit();
- EXPECT_EQ(v.capacity(), 2u);
- }
-
- {
- absl::InlinedVector<std::string, 2> v(100);
- v.resize(3);
- v.shrink_to_fit();
- EXPECT_EQ(v.capacity(), 3u);
- }
-}
-
-TEST(IntVec, Insert) {
- for (size_t len = 0; len < 20; len++) {
- for (ptrdiff_t pos = 0; pos <= static_cast<ptrdiff_t>(len); pos++) {
- {
- // Single element
- std::vector<int> std_v;
- Fill(&std_v, len);
- IntVec v;
- Fill(&v, len);
-
- std_v.insert(std_v.begin() + pos, 9999);
- IntVec::iterator it = v.insert(v.cbegin() + pos, 9999);
- EXPECT_THAT(v, ElementsAreArray(std_v));
- EXPECT_EQ(it, v.cbegin() + pos);
- }
- {
- // n elements
- std::vector<int> std_v;
- Fill(&std_v, len);
- IntVec v;
- Fill(&v, len);
-
- IntVec::size_type n = 5;
- std_v.insert(std_v.begin() + pos, n, 9999);
- IntVec::iterator it = v.insert(v.cbegin() + pos, n, 9999);
- EXPECT_THAT(v, ElementsAreArray(std_v));
- EXPECT_EQ(it, v.cbegin() + pos);
- }
- {
- // Iterator range (random access iterator)
- std::vector<int> std_v;
- Fill(&std_v, len);
- IntVec v;
- Fill(&v, len);
-
- const std::vector<int> input = {9999, 8888, 7777};
- std_v.insert(std_v.begin() + pos, input.cbegin(), input.cend());
- IntVec::iterator it =
- v.insert(v.cbegin() + pos, input.cbegin(), input.cend());
- EXPECT_THAT(v, ElementsAreArray(std_v));
- EXPECT_EQ(it, v.cbegin() + pos);
- }
- {
- // Iterator range (forward iterator)
- std::vector<int> std_v;
- Fill(&std_v, len);
- IntVec v;
- Fill(&v, len);
-
- const std::forward_list<int> input = {9999, 8888, 7777};
- std_v.insert(std_v.begin() + pos, input.cbegin(), input.cend());
- IntVec::iterator it =
- v.insert(v.cbegin() + pos, input.cbegin(), input.cend());
- EXPECT_THAT(v, ElementsAreArray(std_v));
- EXPECT_EQ(it, v.cbegin() + pos);
- }
- {
- // Iterator range (input iterator)
- std::vector<int> std_v;
- Fill(&std_v, len);
- IntVec v;
- Fill(&v, len);
-
- std_v.insert(std_v.begin() + pos, {9999, 8888, 7777});
- std::istringstream input("9999 8888 7777");
- IntVec::iterator it =
- v.insert(v.cbegin() + pos, std::istream_iterator<int>(input),
- std::istream_iterator<int>());
- EXPECT_THAT(v, ElementsAreArray(std_v));
- EXPECT_EQ(it, v.cbegin() + pos);
- }
- {
- // Initializer list
- std::vector<int> std_v;
- Fill(&std_v, len);
- IntVec v;
- Fill(&v, len);
-
- std_v.insert(std_v.begin() + pos, {9999, 8888});
- IntVec::iterator it = v.insert(v.cbegin() + pos, {9999, 8888});
- EXPECT_THAT(v, ElementsAreArray(std_v));
- EXPECT_EQ(it, v.cbegin() + pos);
- }
- }
- }
-}
-
-TEST(RefCountedVec, InsertConstructorDestructor) {
- // Make sure the proper construction/destruction happen during insert
- // operations.
- for (size_t len = 0; len < 20; len++) {
- SCOPED_TRACE(len);
- for (size_t pos = 0; pos <= len; pos++) {
- SCOPED_TRACE(pos);
- std::vector<int> counts(len, 0);
- int inserted_count = 0;
- RefCountedVec v;
- for (size_t i = 0; i < len; ++i) {
- SCOPED_TRACE(i);
- v.push_back(RefCounted(static_cast<int>(i), &counts[i]));
- }
-
- EXPECT_THAT(counts, Each(Eq(1)));
-
- RefCounted insert_element(9999, &inserted_count);
- EXPECT_EQ(1, inserted_count);
- v.insert(v.begin() + pos, insert_element);
- EXPECT_EQ(2, inserted_count);
- // Check that the elements at the end are preserved.
- EXPECT_THAT(counts, Each(Eq(1)));
- EXPECT_EQ(2, inserted_count);
- }
- }
-}
-
-TEST(IntVec, Resize) {
- for (size_t len = 0; len < 20; len++) {
- IntVec v;
- Fill(&v, len);
-
- // Try resizing up and down by k elements
- static const int kResizeElem = 1000000;
- for (size_t k = 0; k < 10; k++) {
- // Enlarging resize
- v.resize(len + k, kResizeElem);
- EXPECT_EQ(len + k, v.size());
- EXPECT_LE(len + k, v.capacity());
- for (size_t i = 0; i < len + k; i++) {
- if (i < len) {
- EXPECT_EQ(static_cast<int>(i), v[i]);
- } else {
- EXPECT_EQ(kResizeElem, v[i]);
- }
- }
-
- // Shrinking resize
- v.resize(len, kResizeElem);
- EXPECT_EQ(len, v.size());
- EXPECT_LE(len, v.capacity());
- for (size_t i = 0; i < len; i++) {
- EXPECT_EQ(static_cast<int>(i), v[i]);
- }
- }
- }
-}
-
-TEST(IntVec, InitWithLength) {
- for (size_t len = 0; len < 20; len++) {
- IntVec v(len, 7);
- EXPECT_EQ(len, v.size());
- EXPECT_LE(len, v.capacity());
- for (size_t i = 0; i < len; i++) {
- EXPECT_EQ(7, v[i]);
- }
- }
-}
-
-TEST(IntVec, CopyConstructorAndAssignment) {
- for (size_t len = 0; len < 20; len++) {
- IntVec v;
- Fill(&v, len);
- EXPECT_EQ(len, v.size());
- EXPECT_LE(len, v.capacity());
-
- IntVec v2(v);
- EXPECT_TRUE(v == v2) << PrintToString(v) << PrintToString(v2);
-
- for (size_t start_len = 0; start_len < 20; start_len++) {
- IntVec v3;
- Fill(&v3, start_len, 99); // Add dummy elements that should go away
- v3 = v;
- EXPECT_TRUE(v == v3) << PrintToString(v) << PrintToString(v3);
- }
- }
-}
-
-TEST(IntVec, AliasingCopyAssignment) {
- for (size_t len = 0; len < 20; ++len) {
- IntVec original;
- Fill(&original, len);
- IntVec dup = original;
- dup = *&dup;
- EXPECT_EQ(dup, original);
- }
-}
-
-TEST(IntVec, MoveConstructorAndAssignment) {
- for (size_t len = 0; len < 20; len++) {
- IntVec v_in;
- const size_t inlined_capacity = v_in.capacity();
- Fill(&v_in, len);
- EXPECT_EQ(len, v_in.size());
- EXPECT_LE(len, v_in.capacity());
-
- {
- IntVec v_temp(v_in);
- auto* old_data = v_temp.data();
- IntVec v_out(std::move(v_temp));
- EXPECT_TRUE(v_in == v_out) << PrintToString(v_in) << PrintToString(v_out);
- if (v_in.size() > inlined_capacity) {
- // Allocation is moved as a whole, data stays in place.
- EXPECT_TRUE(v_out.data() == old_data);
- } else {
- EXPECT_FALSE(v_out.data() == old_data);
- }
- }
- for (size_t start_len = 0; start_len < 20; start_len++) {
- IntVec v_out;
- Fill(&v_out, start_len, 99); // Add dummy elements that should go away
- IntVec v_temp(v_in);
- auto* old_data = v_temp.data();
- v_out = std::move(v_temp);
- EXPECT_TRUE(v_in == v_out) << PrintToString(v_in) << PrintToString(v_out);
- if (v_in.size() > inlined_capacity) {
- // Allocation is moved as a whole, data stays in place.
- EXPECT_TRUE(v_out.data() == old_data);
- } else {
- EXPECT_FALSE(v_out.data() == old_data);
- }
- }
- }
-}
-
-class NotTriviallyDestructible {
- public:
- NotTriviallyDestructible() : p_(new int(1)) {}
- explicit NotTriviallyDestructible(int i) : p_(new int(i)) {}
-
- NotTriviallyDestructible(const NotTriviallyDestructible& other)
- : p_(new int(*other.p_)) {}
-
- NotTriviallyDestructible& operator=(const NotTriviallyDestructible& other) {
- p_ = absl::make_unique<int>(*other.p_);
- return *this;
- }
-
- bool operator==(const NotTriviallyDestructible& other) const {
- return *p_ == *other.p_;
- }
-
- private:
- std::unique_ptr<int> p_;
-};
-
-TEST(AliasingTest, Emplace) {
- for (size_t i = 2; i < 20; ++i) {
- absl::InlinedVector<NotTriviallyDestructible, 10> vec;
- for (size_t j = 0; j < i; ++j) {
- vec.push_back(NotTriviallyDestructible(static_cast<int>(j)));
- }
- vec.emplace(vec.begin(), vec[0]);
- EXPECT_EQ(vec[0], vec[1]);
- vec.emplace(vec.begin() + i / 2, vec[i / 2]);
- EXPECT_EQ(vec[i / 2], vec[i / 2 + 1]);
- vec.emplace(vec.end() - 1, vec.back());
- EXPECT_EQ(vec[vec.size() - 2], vec.back());
- }
-}
-
-TEST(AliasingTest, InsertWithCount) {
- for (size_t i = 1; i < 20; ++i) {
- absl::InlinedVector<NotTriviallyDestructible, 10> vec;
- for (size_t j = 0; j < i; ++j) {
- vec.push_back(NotTriviallyDestructible(static_cast<int>(j)));
- }
- for (size_t n = 0; n < 5; ++n) {
- // We use back where we can because it's guaranteed to become invalidated
- vec.insert(vec.begin(), n, vec.back());
- auto b = vec.begin();
- EXPECT_TRUE(
- std::all_of(b, b + n, [&vec](const NotTriviallyDestructible& x) {
- return x == vec.back();
- }));
-
- auto m_idx = vec.size() / 2;
- vec.insert(vec.begin() + m_idx, n, vec.back());
- auto m = vec.begin() + m_idx;
- EXPECT_TRUE(
- std::all_of(m, m + n, [&vec](const NotTriviallyDestructible& x) {
- return x == vec.back();
- }));
-
- // We want distinct values so the equality test is meaningful,
- // vec[vec.size() - 1] is also almost always invalidated.
- auto old_e = vec.size() - 1;
- auto val = vec[old_e];
- vec.insert(vec.end(), n, vec[old_e]);
- auto e = vec.begin() + old_e;
- EXPECT_TRUE(std::all_of(
- e, e + n,
- [&val](const NotTriviallyDestructible& x) { return x == val; }));
- }
- }
-}
-
-TEST(OverheadTest, Storage) {
- // Check for size overhead.
- // In particular, ensure that std::allocator doesn't cost anything to store.
- // The union should be absorbing some of the allocation bookkeeping overhead
- // in the larger vectors, leaving only the size_ field as overhead.
-
- struct T { void* val; };
- size_t expected_overhead = sizeof(T);
-
- EXPECT_EQ((2 * expected_overhead),
- sizeof(absl::InlinedVector<T, 1>) - sizeof(T[1]));
- EXPECT_EQ(expected_overhead,
- sizeof(absl::InlinedVector<T, 2>) - sizeof(T[2]));
- EXPECT_EQ(expected_overhead,
- sizeof(absl::InlinedVector<T, 3>) - sizeof(T[3]));
- EXPECT_EQ(expected_overhead,
- sizeof(absl::InlinedVector<T, 4>) - sizeof(T[4]));
- EXPECT_EQ(expected_overhead,
- sizeof(absl::InlinedVector<T, 5>) - sizeof(T[5]));
- EXPECT_EQ(expected_overhead,
- sizeof(absl::InlinedVector<T, 6>) - sizeof(T[6]));
- EXPECT_EQ(expected_overhead,
- sizeof(absl::InlinedVector<T, 7>) - sizeof(T[7]));
- EXPECT_EQ(expected_overhead,
- sizeof(absl::InlinedVector<T, 8>) - sizeof(T[8]));
-}
-
-TEST(IntVec, Clear) {
- for (size_t len = 0; len < 20; len++) {
- SCOPED_TRACE(len);
- IntVec v;
- Fill(&v, len);
- v.clear();
- EXPECT_EQ(0u, v.size());
- EXPECT_EQ(v.begin(), v.end());
- }
-}
-
-TEST(IntVec, Reserve) {
- for (size_t len = 0; len < 20; len++) {
- IntVec v;
- Fill(&v, len);
-
- for (size_t newlen = 0; newlen < 100; newlen++) {
- const int* start_rep = v.data();
- v.reserve(newlen);
- const int* final_rep = v.data();
- if (newlen <= len) {
- EXPECT_EQ(start_rep, final_rep);
- }
- EXPECT_LE(newlen, v.capacity());
-
- // Filling up to newlen should not change rep
- while (v.size() < newlen) {
- v.push_back(0);
- }
- EXPECT_EQ(final_rep, v.data());
- }
- }
-}
-
-TEST(StringVec, SelfRefPushBack) {
- std::vector<std::string> std_v;
- absl::InlinedVector<std::string, 4> v;
- const std::string s = "A quite long string to ensure heap.";
- std_v.push_back(s);
- v.push_back(s);
- for (int i = 0; i < 20; ++i) {
- EXPECT_THAT(v, ElementsAreArray(std_v));
-
- v.push_back(v.back());
- std_v.push_back(std_v.back());
- }
- EXPECT_THAT(v, ElementsAreArray(std_v));
-}
-
-TEST(StringVec, SelfRefPushBackWithMove) {
- std::vector<std::string> std_v;
- absl::InlinedVector<std::string, 4> v;
- const std::string s = "A quite long string to ensure heap.";
- std_v.push_back(s);
- v.push_back(s);
- for (int i = 0; i < 20; ++i) {
- EXPECT_EQ(v.back(), std_v.back());
-
- v.push_back(std::move(v.back()));
- std_v.push_back(std::move(std_v.back()));
- }
- EXPECT_EQ(v.back(), std_v.back());
-}
-
-TEST(StringVec, SelfMove) {
- const std::string s = "A quite long string to ensure heap.";
- for (int len = 0; len < 20; len++) {
- SCOPED_TRACE(len);
- absl::InlinedVector<std::string, 8> v;
- for (int i = 0; i < len; ++i) {
- SCOPED_TRACE(i);
- v.push_back(s);
- }
- // Indirection necessary to avoid compiler warning.
- v = std::move(*(&v));
- // Ensure that the inlined vector is still in a valid state by copying it.
- // We don't expect specific contents since a self-move results in an
- // unspecified valid state.
- std::vector<std::string> copy(v.begin(), v.end());
- }
-}
-
-TEST(IntVec, Swap) {
- for (size_t l1 = 0; l1 < 20; l1++) {
- SCOPED_TRACE(l1);
- for (size_t l2 = 0; l2 < 20; l2++) {
- SCOPED_TRACE(l2);
- IntVec a = Fill(l1, 0);
- IntVec b = Fill(l2, 100);
- {
- using std::swap;
- swap(a, b);
- }
- EXPECT_EQ(l1, b.size());
- EXPECT_EQ(l2, a.size());
- for (size_t i = 0; i < l1; i++) {
- SCOPED_TRACE(i);
- EXPECT_EQ(static_cast<int>(i), b[i]);
- }
- for (size_t i = 0; i < l2; i++) {
- SCOPED_TRACE(i);
- EXPECT_EQ(100 + static_cast<int>(i), a[i]);
- }
- }
- }
-}
-
-TYPED_TEST_P(InstanceTest, Swap) {
- using Instance = TypeParam;
- using InstanceVec = absl::InlinedVector<Instance, 8>;
- for (size_t l1 = 0; l1 < 20; l1++) {
- SCOPED_TRACE(l1);
- for (size_t l2 = 0; l2 < 20; l2++) {
- SCOPED_TRACE(l2);
- InstanceTracker tracker;
- InstanceVec a, b;
- const size_t inlined_capacity = a.capacity();
- auto min_len = std::min(l1, l2);
- auto max_len = std::max(l1, l2);
- for (size_t i = 0; i < l1; i++)
- a.push_back(Instance(static_cast<int>(i)));
- for (size_t i = 0; i < l2; i++)
- b.push_back(Instance(100 + static_cast<int>(i)));
- EXPECT_EQ(tracker.instances(), static_cast<int>(l1 + l2));
- tracker.ResetCopiesMovesSwaps();
- {
- using std::swap;
- swap(a, b);
- }
- EXPECT_EQ(tracker.instances(), static_cast<int>(l1 + l2));
- if (a.size() > inlined_capacity && b.size() > inlined_capacity) {
- EXPECT_EQ(tracker.swaps(), 0); // Allocations are swapped.
- EXPECT_EQ(tracker.moves(), 0);
- } else if (a.size() <= inlined_capacity && b.size() <= inlined_capacity) {
- EXPECT_EQ(tracker.swaps(), static_cast<int>(min_len));
- EXPECT_EQ((tracker.moves() ? tracker.moves() : tracker.copies()),
- static_cast<int>(max_len - min_len));
- } else {
- // One is allocated and the other isn't. The allocation is transferred
- // without copying elements, and the inlined instances are copied/moved.
- EXPECT_EQ(tracker.swaps(), 0);
- EXPECT_EQ((tracker.moves() ? tracker.moves() : tracker.copies()),
- static_cast<int>(min_len));
- }
-
- EXPECT_EQ(l1, b.size());
- EXPECT_EQ(l2, a.size());
- for (size_t i = 0; i < l1; i++) {
- EXPECT_EQ(static_cast<int>(i), b[i].value());
- }
- for (size_t i = 0; i < l2; i++) {
- EXPECT_EQ(100 + static_cast<int>(i), a[i].value());
- }
- }
- }
-}
-
-TEST(IntVec, EqualAndNotEqual) {
- IntVec a, b;
- EXPECT_TRUE(a == b);
- EXPECT_FALSE(a != b);
-
- a.push_back(3);
- EXPECT_FALSE(a == b);
- EXPECT_TRUE(a != b);
-
- b.push_back(3);
- EXPECT_TRUE(a == b);
- EXPECT_FALSE(a != b);
-
- b.push_back(7);
- EXPECT_FALSE(a == b);
- EXPECT_TRUE(a != b);
-
- a.push_back(6);
- EXPECT_FALSE(a == b);
- EXPECT_TRUE(a != b);
-
- a.clear();
- b.clear();
- for (size_t i = 0; i < 100; i++) {
- a.push_back(static_cast<int>(i));
- b.push_back(static_cast<int>(i));
- EXPECT_TRUE(a == b);
- EXPECT_FALSE(a != b);
-
- b[i] = b[i] + 1;
- EXPECT_FALSE(a == b);
- EXPECT_TRUE(a != b);
-
- b[i] = b[i] - 1; // Back to before
- EXPECT_TRUE(a == b);
- EXPECT_FALSE(a != b);
- }
-}
-
-TEST(IntVec, RelationalOps) {
- IntVec a, b;
- EXPECT_FALSE(a < b);
- EXPECT_FALSE(b < a);
- EXPECT_FALSE(a > b);
- EXPECT_FALSE(b > a);
- EXPECT_TRUE(a <= b);
- EXPECT_TRUE(b <= a);
- EXPECT_TRUE(a >= b);
- EXPECT_TRUE(b >= a);
- b.push_back(3);
- EXPECT_TRUE(a < b);
- EXPECT_FALSE(b < a);
- EXPECT_FALSE(a > b);
- EXPECT_TRUE(b > a);
- EXPECT_TRUE(a <= b);
- EXPECT_FALSE(b <= a);
- EXPECT_FALSE(a >= b);
- EXPECT_TRUE(b >= a);
-}
-
-TYPED_TEST_P(InstanceTest, CountConstructorsDestructors) {
- using Instance = TypeParam;
- using InstanceVec = absl::InlinedVector<Instance, 8>;
- InstanceTracker tracker;
- for (size_t len = 0; len < 20; len++) {
- SCOPED_TRACE(len);
- tracker.ResetCopiesMovesSwaps();
-
- InstanceVec v;
- const size_t inlined_capacity = v.capacity();
- for (size_t i = 0; i < len; i++) {
- v.push_back(Instance(static_cast<int>(i)));
- }
- EXPECT_EQ(tracker.instances(), static_cast<int>(len));
- EXPECT_GE(tracker.copies() + tracker.moves(),
- static_cast<int>(len)); // More due to reallocation.
- tracker.ResetCopiesMovesSwaps();
-
- // Enlarging resize() must construct some objects
- tracker.ResetCopiesMovesSwaps();
- v.resize(len + 10, Instance(100));
- EXPECT_EQ(tracker.instances(), static_cast<int>(len) + 10);
- if (len <= inlined_capacity && len + 10 > inlined_capacity) {
- EXPECT_EQ(tracker.copies() + tracker.moves(), 10 + static_cast<int>(len));
- } else {
- // Only specify a minimum number of copies + moves. We don't want to
- // depend on the reallocation policy here.
- EXPECT_GE(tracker.copies() + tracker.moves(),
- 10); // More due to reallocation.
- }
-
- // Shrinking resize() must destroy some objects
- tracker.ResetCopiesMovesSwaps();
- v.resize(len, Instance(100));
- EXPECT_EQ(tracker.instances(), static_cast<int>(len));
- EXPECT_EQ(tracker.copies(), 0);
- EXPECT_EQ(tracker.moves(), 0);
-
- // reserve() must not increase the number of initialized objects
- SCOPED_TRACE("reserve");
- v.reserve(len + 1000);
- EXPECT_EQ(tracker.instances(), static_cast<int>(len));
- EXPECT_EQ(tracker.copies() + tracker.moves(), static_cast<int>(len));
-
- // pop_back() and erase() must destroy one object
- if (len > 0) {
- tracker.ResetCopiesMovesSwaps();
- v.pop_back();
- EXPECT_EQ(tracker.instances(), static_cast<int>(len) - 1);
- EXPECT_EQ(tracker.copies(), 0);
- EXPECT_EQ(tracker.moves(), 0);
-
- if (!v.empty()) {
- tracker.ResetCopiesMovesSwaps();
- v.erase(v.begin());
- EXPECT_EQ(tracker.instances(), static_cast<int>(len) - 2);
- EXPECT_EQ(tracker.copies() + tracker.moves(),
- static_cast<int>(len) - 2);
- }
- }
-
- tracker.ResetCopiesMovesSwaps();
- int instances_before_empty_erase = tracker.instances();
- v.erase(v.begin(), v.begin());
- EXPECT_EQ(tracker.instances(), instances_before_empty_erase);
- EXPECT_EQ(tracker.copies() + tracker.moves(), 0);
- }
-}
-
-TYPED_TEST_P(InstanceTest, CountConstructorsDestructorsOnCopyConstruction) {
- using Instance = TypeParam;
- using InstanceVec = absl::InlinedVector<Instance, 8>;
- InstanceTracker tracker;
- for (int len = 0; len < 20; len++) {
- SCOPED_TRACE(len);
- tracker.ResetCopiesMovesSwaps();
-
- InstanceVec v;
- for (int i = 0; i < len; i++) {
- v.push_back(Instance(i));
- }
- EXPECT_EQ(tracker.instances(), len);
- EXPECT_GE(tracker.copies() + tracker.moves(),
- len); // More due to reallocation.
- tracker.ResetCopiesMovesSwaps();
- { // Copy constructor should create 'len' more instances.
- InstanceVec v_copy(v);
- EXPECT_EQ(tracker.instances(), len + len);
- EXPECT_EQ(tracker.copies(), len);
- EXPECT_EQ(tracker.moves(), 0);
- }
- EXPECT_EQ(tracker.instances(), len);
- }
-}
-
-TYPED_TEST_P(InstanceTest, CountConstructorsDestructorsOnMoveConstruction) {
- using Instance = TypeParam;
- using InstanceVec = absl::InlinedVector<Instance, 8>;
- InstanceTracker tracker;
- for (int len = 0; len < 20; len++) {
- SCOPED_TRACE(len);
- tracker.ResetCopiesMovesSwaps();
-
- InstanceVec v;
- const size_t inlined_capacity = v.capacity();
- for (int i = 0; i < len; i++) {
- v.push_back(Instance(i));
- }
- EXPECT_EQ(tracker.instances(), len);
- EXPECT_GE(tracker.copies() + tracker.moves(),
- len); // More due to reallocation.
- tracker.ResetCopiesMovesSwaps();
- {
- InstanceVec v_copy(std::move(v));
- if (static_cast<size_t>(len) > inlined_capacity) {
- // Allocation is moved as a whole.
- EXPECT_EQ(tracker.instances(), len);
- EXPECT_EQ(tracker.live_instances(), len);
- // Tests an implementation detail, don't rely on this in your code.
- EXPECT_EQ(v.size(), 0u); // NOLINT misc-use-after-move
- EXPECT_EQ(tracker.copies(), 0);
- EXPECT_EQ(tracker.moves(), 0);
- } else {
- EXPECT_EQ(tracker.instances(), len + len);
- if (Instance::supports_move()) {
- EXPECT_EQ(tracker.live_instances(), len);
- EXPECT_EQ(tracker.copies(), 0);
- EXPECT_EQ(tracker.moves(), len);
- } else {
- EXPECT_EQ(tracker.live_instances(), len + len);
- EXPECT_EQ(tracker.copies(), len);
- EXPECT_EQ(tracker.moves(), 0);
- }
- }
- EXPECT_EQ(tracker.swaps(), 0);
- }
- }
-}
-
-TYPED_TEST_P(InstanceTest, CountConstructorsDestructorsOnAssignment) {
- using Instance = TypeParam;
- using InstanceVec = absl::InlinedVector<Instance, 8>;
- InstanceTracker tracker;
- for (int len = 0; len < 20; len++) {
- SCOPED_TRACE(len);
- for (int longorshort = 0; longorshort <= 1; ++longorshort) {
- SCOPED_TRACE(longorshort);
- tracker.ResetCopiesMovesSwaps();
-
- InstanceVec longer, shorter;
- for (int i = 0; i < len; i++) {
- longer.push_back(Instance(i));
- shorter.push_back(Instance(i));
- }
- longer.push_back(Instance(len));
- EXPECT_EQ(tracker.instances(), len + len + 1);
- EXPECT_GE(tracker.copies() + tracker.moves(),
- len + len + 1); // More due to reallocation.
-
- tracker.ResetCopiesMovesSwaps();
- if (longorshort) {
- shorter = longer;
- EXPECT_EQ(tracker.instances(), (len + 1) + (len + 1));
- EXPECT_GE(tracker.copies() + tracker.moves(),
- len + 1); // More due to reallocation.
- } else {
- longer = shorter;
- EXPECT_EQ(tracker.instances(), len + len);
- EXPECT_EQ(tracker.copies() + tracker.moves(), len);
- }
- }
- }
-}
-
-TYPED_TEST_P(InstanceTest, CountConstructorsDestructorsOnMoveAssignment) {
- using Instance = TypeParam;
- using InstanceVec = absl::InlinedVector<Instance, 8>;
- InstanceTracker tracker;
- for (int len = 0; len < 20; len++) {
- SCOPED_TRACE(len);
- for (int longorshort = 0; longorshort <= 1; ++longorshort) {
- SCOPED_TRACE(longorshort);
- tracker.ResetCopiesMovesSwaps();
-
- InstanceVec longer, shorter;
- const size_t inlined_capacity = longer.capacity();
- for (int i = 0; i < len; i++) {
- longer.push_back(Instance(i));
- shorter.push_back(Instance(i));
- }
- longer.push_back(Instance(len));
- EXPECT_EQ(tracker.instances(), len + len + 1);
- EXPECT_GE(tracker.copies() + tracker.moves(),
- len + len + 1); // More due to reallocation.
-
- tracker.ResetCopiesMovesSwaps();
- int src_len;
- if (longorshort) {
- src_len = len + 1;
- shorter = std::move(longer);
- } else {
- src_len = len;
- longer = std::move(shorter);
- }
- if (static_cast<size_t>(src_len) > inlined_capacity) {
- // Allocation moved as a whole.
- EXPECT_EQ(tracker.instances(), src_len);
- EXPECT_EQ(tracker.live_instances(), src_len);
- EXPECT_EQ(tracker.copies(), 0);
- EXPECT_EQ(tracker.moves(), 0);
- } else {
- // Elements are all copied.
- EXPECT_EQ(tracker.instances(), src_len + src_len);
- if (Instance::supports_move()) {
- EXPECT_EQ(tracker.copies(), 0);
- EXPECT_EQ(tracker.moves(), src_len);
- EXPECT_EQ(tracker.live_instances(), src_len);
- } else {
- EXPECT_EQ(tracker.copies(), src_len);
- EXPECT_EQ(tracker.moves(), 0);
- EXPECT_EQ(tracker.live_instances(), src_len + src_len);
- }
- }
- EXPECT_EQ(tracker.swaps(), 0);
- }
- }
-}
-
-TEST(CountElemAssign, SimpleTypeWithInlineBacking) {
- for (size_t original_size = 0; original_size <= 5; ++original_size) {
- SCOPED_TRACE(original_size);
- // Original contents are [12345, 12345, ...]
- std::vector<int> original_contents(original_size, 12345);
-
- absl::InlinedVector<int, 2> v(original_contents.begin(),
- original_contents.end());
- v.assign(2, 123);
- EXPECT_THAT(v, AllOf(SizeIs(2u), ElementsAre(123, 123)));
- if (original_size <= 2) {
- // If the original had inline backing, it should stay inline.
- EXPECT_EQ(2u, v.capacity());
- }
- }
-}
-
-TEST(CountElemAssign, SimpleTypeWithAllocation) {
- for (size_t original_size = 0; original_size <= 5; ++original_size) {
- SCOPED_TRACE(original_size);
- // Original contents are [12345, 12345, ...]
- std::vector<int> original_contents(original_size, 12345);
-
- absl::InlinedVector<int, 2> v(original_contents.begin(),
- original_contents.end());
- v.assign(3, 123);
- EXPECT_THAT(v, AllOf(SizeIs(3u), ElementsAre(123, 123, 123)));
- EXPECT_LE(v.size(), v.capacity());
- }
-}
-
-TYPED_TEST_P(InstanceTest, CountElemAssignInlineBacking) {
- using Instance = TypeParam;
- for (size_t original_size = 0; original_size <= 5; ++original_size) {
- SCOPED_TRACE(original_size);
- // Original contents are [12345, 12345, ...]
- std::vector<Instance> original_contents(original_size, Instance(12345));
-
- absl::InlinedVector<Instance, 2> v(original_contents.begin(),
- original_contents.end());
- v.assign(2, Instance(123));
- EXPECT_THAT(v, AllOf(SizeIs(2u), ElementsAre(ValueIs(123), ValueIs(123))));
- if (original_size <= 2) {
- // If the original had inline backing, it should stay inline.
- EXPECT_EQ(2u, v.capacity());
- }
- }
-}
-
-template <typename Instance>
-void InstanceCountElemAssignWithAllocationTest() {
- for (size_t original_size = 0; original_size <= 5; ++original_size) {
- SCOPED_TRACE(original_size);
- // Original contents are [12345, 12345, ...]
- std::vector<Instance> original_contents(original_size, Instance(12345));
-
- absl::InlinedVector<Instance, 2> v(original_contents.begin(),
- original_contents.end());
- v.assign(3, Instance(123));
- EXPECT_THAT(v, AllOf(SizeIs(3u), ElementsAre(ValueIs(123), ValueIs(123),
- ValueIs(123))));
- EXPECT_LE(v.size(), v.capacity());
- }
-}
-TEST(CountElemAssign, WithAllocationCopyableInstance) {
- InstanceCountElemAssignWithAllocationTest<CopyableOnlyInstance>();
-}
-TEST(CountElemAssign, WithAllocationCopyableMovableInstance) {
- InstanceCountElemAssignWithAllocationTest<CopyableMovableInstance>();
-}
-
-TEST(RangedConstructor, SimpleType) {
- std::vector<int> source_v = {4, 5, 6};
- // First try to fit in inline backing
- absl::InlinedVector<int, 4> v(source_v.begin(), source_v.end());
- EXPECT_EQ(3u, v.size());
- EXPECT_EQ(4u,
- v.capacity()); // Indication that we're still on inlined storage
- EXPECT_EQ(4, v[0]);
- EXPECT_EQ(5, v[1]);
- EXPECT_EQ(6, v[2]);
-
- // Now, force a re-allocate
- absl::InlinedVector<int, 2> realloc_v(source_v.begin(), source_v.end());
- EXPECT_EQ(3u, realloc_v.size());
- EXPECT_LT(2u, realloc_v.capacity());
- EXPECT_EQ(4, realloc_v[0]);
- EXPECT_EQ(5, realloc_v[1]);
- EXPECT_EQ(6, realloc_v[2]);
-}
-
-// Test for ranged constructors using Instance as the element type and
-// SourceContainer as the source container type.
-template <typename Instance, typename SourceContainer, int inlined_capacity>
-void InstanceRangedConstructorTestForContainer() {
- InstanceTracker tracker;
- SourceContainer source_v = {Instance(0), Instance(1)};
- tracker.ResetCopiesMovesSwaps();
- absl::InlinedVector<Instance, inlined_capacity> v(source_v.begin(),
- source_v.end());
- EXPECT_EQ(2u, v.size());
- EXPECT_LT(1u, v.capacity());
- EXPECT_EQ(0, v[0].value());
- EXPECT_EQ(1, v[1].value());
- EXPECT_EQ(tracker.copies(), 2);
- EXPECT_EQ(tracker.moves(), 0);
-}
-
-template <typename Instance, int inlined_capacity>
-void InstanceRangedConstructorTestWithCapacity() {
- // Test with const and non-const, random access and non-random-access sources.
- // TODO(bsamwel): Test with an input iterator source.
- {
- SCOPED_TRACE("std::list");
- InstanceRangedConstructorTestForContainer<Instance, std::list<Instance>,
- inlined_capacity>();
- {
- SCOPED_TRACE("const std::list");
- InstanceRangedConstructorTestForContainer<
- Instance, const std::list<Instance>, inlined_capacity>();
- }
- {
- SCOPED_TRACE("std::vector");
- InstanceRangedConstructorTestForContainer<Instance, std::vector<Instance>,
- inlined_capacity>();
- }
- {
- SCOPED_TRACE("const std::vector");
- InstanceRangedConstructorTestForContainer<
- Instance, const std::vector<Instance>, inlined_capacity>();
- }
- }
-}
-
-TYPED_TEST_P(InstanceTest, RangedConstructor) {
- using Instance = TypeParam;
- SCOPED_TRACE("capacity=1");
- InstanceRangedConstructorTestWithCapacity<Instance, 1>();
- SCOPED_TRACE("capacity=2");
- InstanceRangedConstructorTestWithCapacity<Instance, 2>();
-}
-
-TEST(RangedConstructor, ElementsAreConstructed) {
- std::vector<std::string> source_v = {"cat", "dog"};
-
- // Force expansion and re-allocation of v. Ensures that when the vector is
- // expanded that new elements are constructed.
- absl::InlinedVector<std::string, 1> v(source_v.begin(), source_v.end());
- EXPECT_EQ("cat", v[0]);
- EXPECT_EQ("dog", v[1]);
-}
-
-TEST(RangedAssign, SimpleType) {
- // Test for all combinations of original sizes (empty and non-empty inline,
- // and out of line) and target sizes.
- for (size_t original_size = 0; original_size <= 5; ++original_size) {
- SCOPED_TRACE(original_size);
- // Original contents are [12345, 12345, ...]
- std::vector<int> original_contents(original_size, 12345);
-
- for (int target_size = 0; target_size <= 5; ++target_size) {
- SCOPED_TRACE(target_size);
-
- // New contents are [3, 4, ...]
- std::vector<int> new_contents;
- for (int i = 0; i < target_size; ++i) {
- new_contents.push_back(i + 3);
- }
-
- absl::InlinedVector<int, 3> v(original_contents.begin(),
- original_contents.end());
- v.assign(new_contents.begin(), new_contents.end());
-
- EXPECT_EQ(new_contents.size(), v.size());
- EXPECT_LE(new_contents.size(), v.capacity());
- if (target_size <= 3 && original_size <= 3) {
- // Storage should stay inline when target size is small.
- EXPECT_EQ(3u, v.capacity());
- }
- EXPECT_THAT(v, ElementsAreArray(new_contents));
- }
- }
-}
-
-// Returns true if lhs and rhs have the same value.
-template <typename Instance>
-static bool InstanceValuesEqual(const Instance& lhs, const Instance& rhs) {
- return lhs.value() == rhs.value();
-}
-
-// Test for ranged assign() using Instance as the element type and
-// SourceContainer as the source container type.
-template <typename Instance, typename SourceContainer>
-void InstanceRangedAssignTestForContainer() {
- // Test for all combinations of original sizes (empty and non-empty inline,
- // and out of line) and target sizes.
- for (size_t original_size = 0; original_size <= 5; ++original_size) {
- SCOPED_TRACE(original_size);
- // Original contents are [12345, 12345, ...]
- std::vector<Instance> original_contents(original_size, Instance(12345));
-
- for (size_t target_size = 0; target_size <= 5; ++target_size) {
- SCOPED_TRACE(target_size);
-
- // New contents are [3, 4, ...]
- // Generate data using a non-const container, because SourceContainer
- // itself may be const.
- // TODO(bsamwel): Test with an input iterator.
- std::vector<Instance> new_contents_in;
- for (size_t i = 0; i < target_size; ++i) {
- new_contents_in.push_back(Instance(static_cast<int>(i) + 3));
- }
- SourceContainer new_contents(new_contents_in.begin(),
- new_contents_in.end());
-
- absl::InlinedVector<Instance, 3> v(original_contents.begin(),
- original_contents.end());
- v.assign(new_contents.begin(), new_contents.end());
-
- EXPECT_EQ(new_contents.size(), v.size());
- EXPECT_LE(new_contents.size(), v.capacity());
- if (target_size <= 3 && original_size <= 3) {
- // Storage should stay inline when target size is small.
- EXPECT_EQ(3u, v.capacity());
- }
- EXPECT_TRUE(std::equal(v.begin(), v.end(), new_contents.begin(),
- InstanceValuesEqual<Instance>));
- }
- }
-}
-
-TYPED_TEST_P(InstanceTest, RangedAssign) {
- using Instance = TypeParam;
- // Test with const and non-const, random access and non-random-access sources.
- // TODO(bsamwel): Test with an input iterator source.
- SCOPED_TRACE("std::list");
- InstanceRangedAssignTestForContainer<Instance, std::list<Instance>>();
- SCOPED_TRACE("const std::list");
- InstanceRangedAssignTestForContainer<Instance, const std::list<Instance>>();
- SCOPED_TRACE("std::vector");
- InstanceRangedAssignTestForContainer<Instance, std::vector<Instance>>();
- SCOPED_TRACE("const std::vector");
- InstanceRangedAssignTestForContainer<Instance, const std::vector<Instance>>();
-}
-
-TEST(InitializerListConstructor, SimpleTypeWithInlineBacking) {
- EXPECT_THAT((absl::InlinedVector<int, 4>{4, 5, 6}),
- AllOf(SizeIs(3u), CapacityIs(4u), ElementsAre(4, 5, 6)));
-}
-
-TEST(InitializerListConstructor, SimpleTypeWithReallocationRequired) {
- EXPECT_THAT((absl::InlinedVector<int, 2>{4, 5, 6}),
- AllOf(SizeIs(3u), CapacityIs(Gt(2u)), ElementsAre(4, 5, 6)));
-}
-
-TEST(InitializerListConstructor, DisparateTypesInList) {
- EXPECT_THAT((absl::InlinedVector<int, 2>{-7, 8ULL}), ElementsAre(-7, 8));
-
- EXPECT_THAT((absl::InlinedVector<std::string, 2>{"foo", std::string("bar")}),
- ElementsAre("foo", "bar"));
-}
-
-TEST(InitializerListConstructor, ComplexTypeWithInlineBacking) {
- EXPECT_THAT((absl::InlinedVector<CopyableMovableInstance, 1>{
- CopyableMovableInstance(0)}),
- AllOf(SizeIs(1u), CapacityIs(1u), ElementsAre(ValueIs(0))));
-}
-
-TEST(InitializerListConstructor, ComplexTypeWithReallocationRequired) {
- EXPECT_THAT((absl::InlinedVector<CopyableMovableInstance, 1>{
- CopyableMovableInstance(0), CopyableMovableInstance(1)}),
- AllOf(SizeIs(2u), CapacityIs(Gt(1u)),
- ElementsAre(ValueIs(0), ValueIs(1))));
-}
-
-TEST(InitializerListAssign, SimpleTypeFitsInlineBacking) {
- for (size_t original_size = 0; original_size <= 4; ++original_size) {
- SCOPED_TRACE(original_size);
-
- absl::InlinedVector<int, 2> v1(original_size, 12345);
- const size_t original_capacity_v1 = v1.capacity();
- v1.assign({3});
- EXPECT_THAT(v1, AllOf(SizeIs(1u), CapacityIs(original_capacity_v1),
- ElementsAre(3)));
-
- absl::InlinedVector<int, 2> v2(original_size, 12345);
- const size_t original_capacity_v2 = v2.capacity();
- v2 = {3};
- EXPECT_THAT(v2, AllOf(SizeIs(1u), CapacityIs(original_capacity_v2),
- ElementsAre(3)));
- }
-}
-
-TEST(InitializerListAssign, SimpleTypeDoesNotFitInlineBacking) {
- for (size_t original_size = 0; original_size <= 4; ++original_size) {
- SCOPED_TRACE(original_size);
- absl::InlinedVector<int, 2> v1(original_size, 12345);
- v1.assign({3, 4, 5});
- EXPECT_THAT(v1, AllOf(SizeIs(3u), ElementsAre(3, 4, 5)));
- EXPECT_LE(3u, v1.capacity());
-
- absl::InlinedVector<int, 2> v2(original_size, 12345);
- v2 = {3, 4, 5};
- EXPECT_THAT(v2, AllOf(SizeIs(3u), ElementsAre(3, 4, 5)));
- EXPECT_LE(3u, v2.capacity());
- }
-}
-
-TEST(InitializerListAssign, DisparateTypesInList) {
- absl::InlinedVector<int, 2> v_int1;
- v_int1.assign({-7, 8ULL});
- EXPECT_THAT(v_int1, ElementsAre(-7, 8));
-
- absl::InlinedVector<int, 2> v_int2;
- v_int2 = {-7, 8ULL};
- EXPECT_THAT(v_int2, ElementsAre(-7, 8));
-
- absl::InlinedVector<std::string, 2> v_string1;
- v_string1.assign({"foo", std::string("bar")});
- EXPECT_THAT(v_string1, ElementsAre("foo", "bar"));
-
- absl::InlinedVector<std::string, 2> v_string2;
- v_string2 = {"foo", std::string("bar")};
- EXPECT_THAT(v_string2, ElementsAre("foo", "bar"));
-}
-
-TYPED_TEST_P(InstanceTest, InitializerListAssign) {
- using Instance = TypeParam;
- for (size_t original_size = 0; original_size <= 4; ++original_size) {
- SCOPED_TRACE(original_size);
- absl::InlinedVector<Instance, 2> v(original_size, Instance(12345));
- const size_t original_capacity = v.capacity();
- v.assign({Instance(3)});
- EXPECT_THAT(v, AllOf(SizeIs(1u), CapacityIs(original_capacity),
- ElementsAre(ValueIs(3))));
- }
- for (size_t original_size = 0; original_size <= 4; ++original_size) {
- SCOPED_TRACE(original_size);
- absl::InlinedVector<Instance, 2> v(original_size, Instance(12345));
- v.assign({Instance(3), Instance(4), Instance(5)});
- EXPECT_THAT(
- v, AllOf(SizeIs(3u), ElementsAre(ValueIs(3), ValueIs(4), ValueIs(5))));
- EXPECT_LE(3u, v.capacity());
- }
-}
-
-REGISTER_TYPED_TEST_SUITE_P(InstanceTest, Swap, CountConstructorsDestructors,
- CountConstructorsDestructorsOnCopyConstruction,
- CountConstructorsDestructorsOnMoveConstruction,
- CountConstructorsDestructorsOnAssignment,
- CountConstructorsDestructorsOnMoveAssignment,
- CountElemAssignInlineBacking, RangedConstructor,
- RangedAssign, InitializerListAssign);
-
-using InstanceTypes =
- ::testing::Types<CopyableOnlyInstance, CopyableMovableInstance>;
-INSTANTIATE_TYPED_TEST_SUITE_P(InstanceTestOnTypes, InstanceTest,
- InstanceTypes);
-
-TEST(DynamicVec, DynamicVecCompiles) {
- DynamicVec v;
- (void)v;
-}
-
-TEST(AllocatorSupportTest, Constructors) {
- using MyAlloc = CountingAllocator<int>;
- using AllocVec = absl::InlinedVector<int, 4, MyAlloc>;
- const int ia[] = {0, 1, 2, 3, 4, 5, 6, 7};
- int64_t allocated = 0;
- MyAlloc alloc(&allocated);
- { AllocVec ABSL_ATTRIBUTE_UNUSED v; }
- { AllocVec ABSL_ATTRIBUTE_UNUSED v(alloc); }
- { AllocVec ABSL_ATTRIBUTE_UNUSED v(ia, ia + ABSL_ARRAYSIZE(ia), alloc); }
- { AllocVec ABSL_ATTRIBUTE_UNUSED v({1, 2, 3}, alloc); }
-
- AllocVec v2;
- { AllocVec ABSL_ATTRIBUTE_UNUSED v(v2, alloc); }
- { AllocVec ABSL_ATTRIBUTE_UNUSED v(std::move(v2), alloc); }
-}
-
-TEST(AllocatorSupportTest, CountAllocations) {
- using MyAlloc = CountingAllocator<int>;
- using AllocVec = absl::InlinedVector<int, 4, MyAlloc>;
- const int ia[] = {0, 1, 2, 3, 4, 5, 6, 7};
- int64_t allocated = 0;
- MyAlloc alloc(&allocated);
- {
- AllocVec ABSL_ATTRIBUTE_UNUSED v(ia, ia + 4, alloc);
- EXPECT_THAT(allocated, Eq(0));
- }
- EXPECT_THAT(allocated, Eq(0));
- {
- AllocVec ABSL_ATTRIBUTE_UNUSED v(ia, ia + ABSL_ARRAYSIZE(ia), alloc);
- EXPECT_THAT(allocated, Eq(static_cast<int64_t>(v.size() * sizeof(int))));
- }
- EXPECT_THAT(allocated, Eq(0));
- {
- AllocVec v(4, 1, alloc);
- EXPECT_THAT(allocated, Eq(0));
-
- int64_t allocated2 = 0;
- MyAlloc alloc2(&allocated2);
- AllocVec v2(v, alloc2);
- EXPECT_THAT(allocated2, Eq(0));
-
- int64_t allocated3 = 0;
- MyAlloc alloc3(&allocated3);
- AllocVec v3(std::move(v), alloc3);
- EXPECT_THAT(allocated3, Eq(0));
- }
- EXPECT_THAT(allocated, 0);
- {
- AllocVec v(8, 2, alloc);
- EXPECT_THAT(allocated, Eq(static_cast<int64_t>(v.size() * sizeof(int))));
-
- int64_t allocated2 = 0;
- MyAlloc alloc2(&allocated2);
- AllocVec v2(v, alloc2);
- EXPECT_THAT(allocated2, Eq(static_cast<int64_t>(v2.size() * sizeof(int))));
-
- int64_t allocated3 = 0;
- MyAlloc alloc3(&allocated3);
- AllocVec v3(std::move(v), alloc3);
- EXPECT_THAT(allocated3, Eq(static_cast<int64_t>(v3.size() * sizeof(int))));
- }
- EXPECT_EQ(allocated, 0);
- {
- // Test shrink_to_fit deallocations.
- AllocVec v(8, 2, alloc);
- EXPECT_EQ(allocated, static_cast<int64_t>(8 * sizeof(int)));
- v.resize(5);
- EXPECT_EQ(allocated, static_cast<int64_t>(8 * sizeof(int)));
- v.shrink_to_fit();
- EXPECT_EQ(allocated, static_cast<int64_t>(5 * sizeof(int)));
- v.resize(4);
- EXPECT_EQ(allocated, static_cast<int64_t>(5 * sizeof(int)));
- v.shrink_to_fit();
- EXPECT_EQ(allocated, 0);
- }
-}
-
-TEST(AllocatorSupportTest, SwapBothAllocated) {
- using MyAlloc = CountingAllocator<int>;
- using AllocVec = absl::InlinedVector<int, 4, MyAlloc>;
- int64_t allocated1 = 0;
- int64_t allocated2 = 0;
- {
- const int ia1[] = {0, 1, 2, 3, 4, 5, 6, 7};
- const int ia2[] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
- MyAlloc a1(&allocated1);
- MyAlloc a2(&allocated2);
- AllocVec v1(ia1, ia1 + ABSL_ARRAYSIZE(ia1), a1);
- AllocVec v2(ia2, ia2 + ABSL_ARRAYSIZE(ia2), a2);
- EXPECT_LT(v1.capacity(), v2.capacity());
- EXPECT_THAT(allocated1,
- Eq(static_cast<int64_t>(v1.capacity() * sizeof(int))));
- EXPECT_THAT(allocated2,
- Eq(static_cast<int64_t>(v2.capacity() * sizeof(int))));
- v1.swap(v2);
- EXPECT_THAT(v1, ElementsAreArray(ia2));
- EXPECT_THAT(v2, ElementsAreArray(ia1));
- EXPECT_THAT(allocated1,
- Eq(static_cast<int64_t>(v2.capacity() * sizeof(int))));
- EXPECT_THAT(allocated2,
- Eq(static_cast<int64_t>(v1.capacity() * sizeof(int))));
- }
- EXPECT_THAT(allocated1, 0);
- EXPECT_THAT(allocated2, 0);
-}
-
-TEST(AllocatorSupportTest, SwapOneAllocated) {
- using MyAlloc = CountingAllocator<int>;
- using AllocVec = absl::InlinedVector<int, 4, MyAlloc>;
- int64_t allocated1 = 0;
- int64_t allocated2 = 0;
- {
- const int ia1[] = {0, 1, 2, 3, 4, 5, 6, 7};
- const int ia2[] = {0, 1, 2, 3};
- MyAlloc a1(&allocated1);
- MyAlloc a2(&allocated2);
- AllocVec v1(ia1, ia1 + ABSL_ARRAYSIZE(ia1), a1);
- AllocVec v2(ia2, ia2 + ABSL_ARRAYSIZE(ia2), a2);
- EXPECT_THAT(allocated1,
- Eq(static_cast<int64_t>(v1.capacity() * sizeof(int))));
- EXPECT_THAT(allocated2, Eq(0));
- v1.swap(v2);
- EXPECT_THAT(v1, ElementsAreArray(ia2));
- EXPECT_THAT(v2, ElementsAreArray(ia1));
- EXPECT_THAT(allocated1,
- Eq(static_cast<int64_t>(v2.capacity() * sizeof(int))));
- EXPECT_THAT(allocated2, Eq(0));
- EXPECT_TRUE(v2.get_allocator() == a1);
- EXPECT_TRUE(v1.get_allocator() == a2);
- }
- EXPECT_THAT(allocated1, 0);
- EXPECT_THAT(allocated2, 0);
-}
-
-TEST(AllocatorSupportTest, ScopedAllocatorWorksInlined) {
- using StdVector = std::vector<int, CountingAllocator<int>>;
- using Alloc = CountingAllocator<StdVector>;
- using ScopedAlloc = std::scoped_allocator_adaptor<Alloc>;
- using AllocVec = absl::InlinedVector<StdVector, 1, ScopedAlloc>;
-
- int64_t total_allocated_byte_count = 0;
-
- AllocVec inlined_case(ScopedAlloc(Alloc(+&total_allocated_byte_count)));
-
- // Called only once to remain inlined
- inlined_case.emplace_back();
-
- int64_t absl_responsible_for_count = total_allocated_byte_count;
-
- // MSVC's allocator preemptively allocates in debug mode
-#if !defined(_MSC_VER)
- EXPECT_EQ(absl_responsible_for_count, 0);
-#endif // !defined(_MSC_VER)
-
- inlined_case[0].emplace_back();
- EXPECT_GT(total_allocated_byte_count, absl_responsible_for_count);
-
- inlined_case.clear();
- inlined_case.shrink_to_fit();
- EXPECT_EQ(total_allocated_byte_count, 0);
-}
-
-TEST(AllocatorSupportTest, ScopedAllocatorWorksAllocated) {
- using StdVector = std::vector<int, CountingAllocator<int>>;
- using Alloc = CountingAllocator<StdVector>;
- using ScopedAlloc = std::scoped_allocator_adaptor<Alloc>;
- using AllocVec = absl::InlinedVector<StdVector, 1, ScopedAlloc>;
-
- int64_t total_allocated_byte_count = 0;
-
- AllocVec allocated_case(ScopedAlloc(Alloc(+&total_allocated_byte_count)));
-
- // Called twice to force into being allocated
- allocated_case.emplace_back();
- allocated_case.emplace_back();
-
- int64_t absl_responsible_for_count = total_allocated_byte_count;
- EXPECT_GT(absl_responsible_for_count, 0);
-
- allocated_case[1].emplace_back();
- EXPECT_GT(total_allocated_byte_count, absl_responsible_for_count);
-
- allocated_case.clear();
- allocated_case.shrink_to_fit();
- EXPECT_EQ(total_allocated_byte_count, 0);
-}
-
-TEST(AllocatorSupportTest, SizeAllocConstructor) {
- constexpr size_t inlined_size = 4;
- using Alloc = CountingAllocator<int>;
- using AllocVec = absl::InlinedVector<int, inlined_size, Alloc>;
-
- {
- auto len = inlined_size / 2;
- int64_t allocated = 0;
- auto v = AllocVec(len, Alloc(&allocated));
-
- // Inline storage used; allocator should not be invoked
- EXPECT_THAT(allocated, Eq(0));
- EXPECT_THAT(v, AllOf(SizeIs(len), Each(0)));
- }
-
- {
- auto len = inlined_size * 2;
- int64_t allocated = 0;
- auto v = AllocVec(len, Alloc(&allocated));
-
- // Out of line storage used; allocation of 8 elements expected
- EXPECT_THAT(allocated, Eq(static_cast<int64_t>(len * sizeof(int))));
- EXPECT_THAT(v, AllOf(SizeIs(len), Each(0)));
- }
-}
-
-TEST(InlinedVectorTest, MinimumAllocatorCompilesUsingTraits) {
- using T = int;
- using A = std::allocator<T>;
- using ATraits = absl::allocator_traits<A>;
-
- struct MinimumAllocator {
- using value_type = T;
-
- value_type* allocate(size_t n) {
- A a;
- return ATraits::allocate(a, n);
- }
-
- void deallocate(value_type* p, size_t n) {
- A a;
- ATraits::deallocate(a, p, n);
- }
- };
-
- absl::InlinedVector<T, 1, MinimumAllocator> vec;
- vec.emplace_back();
- vec.resize(0);
-}
-
-TEST(InlinedVectorTest, AbslHashValueWorks) {
- using V = absl::InlinedVector<int, 4>;
- std::vector<V> cases;
-
- // Generate a variety of vectors some of these are small enough for the inline
- // space but are stored out of line.
- for (size_t i = 0; i < 10; ++i) {
- V v;
- for (int j = 0; j < static_cast<int>(i); ++j) {
- v.push_back(j);
- }
- cases.push_back(v);
- v.resize(i % 4);
- cases.push_back(v);
- }
-
- EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(cases));
-}
-
-class MoveConstructibleOnlyInstance
- : public absl::test_internal::BaseCountedInstance {
- public:
- explicit MoveConstructibleOnlyInstance(int x) : BaseCountedInstance(x) {}
- MoveConstructibleOnlyInstance(MoveConstructibleOnlyInstance&& other) =
- default;
- MoveConstructibleOnlyInstance& operator=(
- MoveConstructibleOnlyInstance&& other) = delete;
-};
-
-MATCHER(HasValue, "") {
- return ::testing::get<0>(arg).value() == ::testing::get<1>(arg);
-}
-
-TEST(NonAssignableMoveAssignmentTest, AllocatedToInline) {
- using X = MoveConstructibleOnlyInstance;
- InstanceTracker tracker;
- absl::InlinedVector<X, 2> inlined;
- inlined.emplace_back(1);
- absl::InlinedVector<X, 2> allocated;
- allocated.emplace_back(1);
- allocated.emplace_back(2);
- allocated.emplace_back(3);
- tracker.ResetCopiesMovesSwaps();
-
- inlined = std::move(allocated);
- // passed ownership of the allocated storage
- EXPECT_EQ(tracker.moves(), 0);
- EXPECT_EQ(tracker.live_instances(), 3);
-
- EXPECT_THAT(inlined, Pointwise(HasValue(), {1, 2, 3}));
-}
-
-TEST(NonAssignableMoveAssignmentTest, InlineToAllocated) {
- using X = MoveConstructibleOnlyInstance;
- InstanceTracker tracker;
- absl::InlinedVector<X, 2> inlined;
- inlined.emplace_back(1);
- absl::InlinedVector<X, 2> allocated;
- allocated.emplace_back(1);
- allocated.emplace_back(2);
- allocated.emplace_back(3);
- tracker.ResetCopiesMovesSwaps();
-
- allocated = std::move(inlined);
- // Moved elements
- EXPECT_EQ(tracker.moves(), 1);
- EXPECT_EQ(tracker.live_instances(), 1);
-
- EXPECT_THAT(allocated, Pointwise(HasValue(), {1}));
-}
-
-TEST(NonAssignableMoveAssignmentTest, InlineToInline) {
- using X = MoveConstructibleOnlyInstance;
- InstanceTracker tracker;
- absl::InlinedVector<X, 2> inlined_a;
- inlined_a.emplace_back(1);
- absl::InlinedVector<X, 2> inlined_b;
- inlined_b.emplace_back(1);
- tracker.ResetCopiesMovesSwaps();
-
- inlined_a = std::move(inlined_b);
- // Moved elements
- EXPECT_EQ(tracker.moves(), 1);
- EXPECT_EQ(tracker.live_instances(), 1);
-
- EXPECT_THAT(inlined_a, Pointwise(HasValue(), {1}));
-}
-
-TEST(NonAssignableMoveAssignmentTest, AllocatedToAllocated) {
- using X = MoveConstructibleOnlyInstance;
- InstanceTracker tracker;
- absl::InlinedVector<X, 2> allocated_a;
- allocated_a.emplace_back(1);
- allocated_a.emplace_back(2);
- allocated_a.emplace_back(3);
- absl::InlinedVector<X, 2> allocated_b;
- allocated_b.emplace_back(4);
- allocated_b.emplace_back(5);
- allocated_b.emplace_back(6);
- allocated_b.emplace_back(7);
- tracker.ResetCopiesMovesSwaps();
-
- allocated_a = std::move(allocated_b);
- // passed ownership of the allocated storage
- EXPECT_EQ(tracker.moves(), 0);
- EXPECT_EQ(tracker.live_instances(), 4);
-
- EXPECT_THAT(allocated_a, Pointwise(HasValue(), {4, 5, 6, 7}));
-}
-
-TEST(NonAssignableMoveAssignmentTest, AssignThis) {
- using X = MoveConstructibleOnlyInstance;
- InstanceTracker tracker;
- absl::InlinedVector<X, 2> v;
- v.emplace_back(1);
- v.emplace_back(2);
- v.emplace_back(3);
-
- tracker.ResetCopiesMovesSwaps();
-
- // Obfuscated in order to pass -Wself-move.
- v = std::move(*std::addressof(v));
- // nothing happens
- EXPECT_EQ(tracker.moves(), 0);
- EXPECT_EQ(tracker.live_instances(), 3);
-
- EXPECT_THAT(v, Pointwise(HasValue(), {1, 2, 3}));
-}
-
-class NonSwappableInstance : public absl::test_internal::BaseCountedInstance {
- public:
- explicit NonSwappableInstance(int x) : BaseCountedInstance(x) {}
- NonSwappableInstance(const NonSwappableInstance& other) = default;
- NonSwappableInstance& operator=(const NonSwappableInstance& other) = default;
- NonSwappableInstance(NonSwappableInstance&& other) = default;
- NonSwappableInstance& operator=(NonSwappableInstance&& other) = default;
-};
-
-void swap(NonSwappableInstance&, NonSwappableInstance&) = delete;
-
-TEST(NonSwappableSwapTest, InlineAndAllocatedTransferStorageAndMove) {
- using X = NonSwappableInstance;
- InstanceTracker tracker;
- absl::InlinedVector<X, 2> inlined;
- inlined.emplace_back(1);
- absl::InlinedVector<X, 2> allocated;
- allocated.emplace_back(1);
- allocated.emplace_back(2);
- allocated.emplace_back(3);
- tracker.ResetCopiesMovesSwaps();
-
- inlined.swap(allocated);
- EXPECT_EQ(tracker.moves(), 1);
- EXPECT_EQ(tracker.live_instances(), 4);
-
- EXPECT_THAT(inlined, Pointwise(HasValue(), {1, 2, 3}));
-}
-
-TEST(NonSwappableSwapTest, InlineAndInlineMoveIndividualElements) {
- using X = NonSwappableInstance;
- InstanceTracker tracker;
- absl::InlinedVector<X, 2> inlined_a;
- inlined_a.emplace_back(1);
- absl::InlinedVector<X, 2> inlined_b;
- inlined_b.emplace_back(2);
- tracker.ResetCopiesMovesSwaps();
-
- inlined_a.swap(inlined_b);
- EXPECT_EQ(tracker.moves(), 3);
- EXPECT_EQ(tracker.live_instances(), 2);
-
- EXPECT_THAT(inlined_a, Pointwise(HasValue(), {2}));
- EXPECT_THAT(inlined_b, Pointwise(HasValue(), {1}));
-}
-
-TEST(NonSwappableSwapTest, AllocatedAndAllocatedOnlyTransferStorage) {
- using X = NonSwappableInstance;
- InstanceTracker tracker;
- absl::InlinedVector<X, 2> allocated_a;
- allocated_a.emplace_back(1);
- allocated_a.emplace_back(2);
- allocated_a.emplace_back(3);
- absl::InlinedVector<X, 2> allocated_b;
- allocated_b.emplace_back(4);
- allocated_b.emplace_back(5);
- allocated_b.emplace_back(6);
- allocated_b.emplace_back(7);
- tracker.ResetCopiesMovesSwaps();
-
- allocated_a.swap(allocated_b);
- EXPECT_EQ(tracker.moves(), 0);
- EXPECT_EQ(tracker.live_instances(), 7);
-
- EXPECT_THAT(allocated_a, Pointwise(HasValue(), {4, 5, 6, 7}));
- EXPECT_THAT(allocated_b, Pointwise(HasValue(), {1, 2, 3}));
-}
-
-TEST(NonSwappableSwapTest, SwapThis) {
- using X = NonSwappableInstance;
- InstanceTracker tracker;
- absl::InlinedVector<X, 2> v;
- v.emplace_back(1);
- v.emplace_back(2);
- v.emplace_back(3);
-
- tracker.ResetCopiesMovesSwaps();
-
- v.swap(v);
- EXPECT_EQ(tracker.moves(), 0);
- EXPECT_EQ(tracker.live_instances(), 3);
-
- EXPECT_THAT(v, Pointwise(HasValue(), {1, 2, 3}));
-}
-
-} // anonymous namespace
diff --git a/third_party/abseil-cpp/absl/container/internal/btree.h b/third_party/abseil-cpp/absl/container/internal/btree.h
deleted file mode 100644
index 2e21dc6..0000000
--- a/third_party/abseil-cpp/absl/container/internal/btree.h
+++ /dev/null
@@ -1,2939 +0,0 @@
-// Copyright 2018 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.
-
-// A btree implementation of the STL set and map interfaces. A btree is smaller
-// and generally also faster than STL set/map (refer to the benchmarks below).
-// The red-black tree implementation of STL set/map has an overhead of 3
-// pointers (left, right and parent) plus the node color information for each
-// stored value. So a set<int32_t> consumes 40 bytes for each value stored in
-// 64-bit mode. This btree implementation stores multiple values on fixed
-// size nodes (usually 256 bytes) and doesn't store child pointers for leaf
-// nodes. The result is that a btree_set<int32_t> may use much less memory per
-// stored value. For the random insertion benchmark in btree_bench.cc, a
-// btree_set<int32_t> with node-size of 256 uses 5.1 bytes per stored value.
-//
-// The packing of multiple values on to each node of a btree has another effect
-// besides better space utilization: better cache locality due to fewer cache
-// lines being accessed. Better cache locality translates into faster
-// operations.
-//
-// CAVEATS
-//
-// Insertions and deletions on a btree can cause splitting, merging or
-// rebalancing of btree nodes. And even without these operations, insertions
-// and deletions on a btree will move values around within a node. In both
-// cases, the result is that insertions and deletions can invalidate iterators
-// pointing to values other than the one being inserted/deleted. Therefore, this
-// container does not provide pointer stability. This is notably different from
-// STL set/map which takes care to not invalidate iterators on insert/erase
-// except, of course, for iterators pointing to the value being erased. A
-// partial workaround when erasing is available: erase() returns an iterator
-// pointing to the item just after the one that was erased (or end() if none
-// exists).
-
-#ifndef ABSL_CONTAINER_INTERNAL_BTREE_H_
-#define ABSL_CONTAINER_INTERNAL_BTREE_H_
-
-#include <algorithm>
-#include <cassert>
-#include <cstddef>
-#include <cstdint>
-#include <cstring>
-#include <functional>
-#include <iterator>
-#include <limits>
-#include <new>
-#include <string>
-#include <type_traits>
-#include <utility>
-
-#include "absl/base/internal/raw_logging.h"
-#include "absl/base/macros.h"
-#include "absl/container/internal/common.h"
-#include "absl/container/internal/common_policy_traits.h"
-#include "absl/container/internal/compressed_tuple.h"
-#include "absl/container/internal/container_memory.h"
-#include "absl/container/internal/layout.h"
-#include "absl/memory/memory.h"
-#include "absl/meta/type_traits.h"
-#include "absl/strings/cord.h"
-#include "absl/strings/string_view.h"
-#include "absl/types/compare.h"
-#include "absl/utility/utility.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-
-#ifdef ABSL_BTREE_ENABLE_GENERATIONS
-#error ABSL_BTREE_ENABLE_GENERATIONS cannot be directly set
-#elif defined(ABSL_HAVE_ADDRESS_SANITIZER) || \
- defined(ABSL_HAVE_MEMORY_SANITIZER)
-// When compiled in sanitizer mode, we add generation integers to the nodes and
-// iterators. When iterators are used, we validate that the container has not
-// been mutated since the iterator was constructed.
-#define ABSL_BTREE_ENABLE_GENERATIONS
-#endif
-
-template <typename Compare, typename T, typename U>
-using compare_result_t = absl::result_of_t<const Compare(const T &, const U &)>;
-
-// A helper class that indicates if the Compare parameter is a key-compare-to
-// comparator.
-template <typename Compare, typename T>
-using btree_is_key_compare_to =
- std::is_convertible<compare_result_t<Compare, T, T>, absl::weak_ordering>;
-
-struct StringBtreeDefaultLess {
- using is_transparent = void;
-
- StringBtreeDefaultLess() = default;
-
- // Compatibility constructor.
- StringBtreeDefaultLess(std::less<std::string>) {} // NOLINT
- StringBtreeDefaultLess(std::less<absl::string_view>) {} // NOLINT
-
- // Allow converting to std::less for use in key_comp()/value_comp().
- explicit operator std::less<std::string>() const { return {}; }
- explicit operator std::less<absl::string_view>() const { return {}; }
- explicit operator std::less<absl::Cord>() const { return {}; }
-
- absl::weak_ordering operator()(absl::string_view lhs,
- absl::string_view rhs) const {
- return compare_internal::compare_result_as_ordering(lhs.compare(rhs));
- }
- StringBtreeDefaultLess(std::less<absl::Cord>) {} // NOLINT
- absl::weak_ordering operator()(const absl::Cord &lhs,
- const absl::Cord &rhs) const {
- return compare_internal::compare_result_as_ordering(lhs.Compare(rhs));
- }
- absl::weak_ordering operator()(const absl::Cord &lhs,
- absl::string_view rhs) const {
- return compare_internal::compare_result_as_ordering(lhs.Compare(rhs));
- }
- absl::weak_ordering operator()(absl::string_view lhs,
- const absl::Cord &rhs) const {
- return compare_internal::compare_result_as_ordering(-rhs.Compare(lhs));
- }
-};
-
-struct StringBtreeDefaultGreater {
- using is_transparent = void;
-
- StringBtreeDefaultGreater() = default;
-
- StringBtreeDefaultGreater(std::greater<std::string>) {} // NOLINT
- StringBtreeDefaultGreater(std::greater<absl::string_view>) {} // NOLINT
-
- // Allow converting to std::greater for use in key_comp()/value_comp().
- explicit operator std::greater<std::string>() const { return {}; }
- explicit operator std::greater<absl::string_view>() const { return {}; }
- explicit operator std::greater<absl::Cord>() const { return {}; }
-
- absl::weak_ordering operator()(absl::string_view lhs,
- absl::string_view rhs) const {
- return compare_internal::compare_result_as_ordering(rhs.compare(lhs));
- }
- StringBtreeDefaultGreater(std::greater<absl::Cord>) {} // NOLINT
- absl::weak_ordering operator()(const absl::Cord &lhs,
- const absl::Cord &rhs) const {
- return compare_internal::compare_result_as_ordering(rhs.Compare(lhs));
- }
- absl::weak_ordering operator()(const absl::Cord &lhs,
- absl::string_view rhs) const {
- return compare_internal::compare_result_as_ordering(-lhs.Compare(rhs));
- }
- absl::weak_ordering operator()(absl::string_view lhs,
- const absl::Cord &rhs) const {
- return compare_internal::compare_result_as_ordering(rhs.Compare(lhs));
- }
-};
-
-// See below comments for checked_compare.
-template <typename Compare, bool is_class = std::is_class<Compare>::value>
-struct checked_compare_base : Compare {
- using Compare::Compare;
- explicit checked_compare_base(Compare c) : Compare(std::move(c)) {}
- const Compare &comp() const { return *this; }
-};
-template <typename Compare>
-struct checked_compare_base<Compare, false> {
- explicit checked_compare_base(Compare c) : compare(std::move(c)) {}
- const Compare &comp() const { return compare; }
- Compare compare;
-};
-
-// A mechanism for opting out of checked_compare for use only in btree_test.cc.
-struct BtreeTestOnlyCheckedCompareOptOutBase {};
-
-// A helper class to adapt the specified comparator for two use cases:
-// (1) When using common Abseil string types with common comparison functors,
-// convert a boolean comparison into a three-way comparison that returns an
-// `absl::weak_ordering`. This helper class is specialized for
-// less<std::string>, greater<std::string>, less<string_view>,
-// greater<string_view>, less<absl::Cord>, and greater<absl::Cord>.
-// (2) Adapt the comparator to diagnose cases of non-strict-weak-ordering (see
-// https://en.cppreference.com/w/cpp/named_req/Compare) in debug mode. Whenever
-// a comparison is made, we will make assertions to verify that the comparator
-// is valid.
-template <typename Compare, typename Key>
-struct key_compare_adapter {
- // Inherit from checked_compare_base to support function pointers and also
- // keep empty-base-optimization (EBO) support for classes.
- // Note: we can't use CompressedTuple here because that would interfere
- // with the EBO for `btree::rightmost_`. `btree::rightmost_` is itself a
- // CompressedTuple and nested `CompressedTuple`s don't support EBO.
- // TODO(b/214288561): use CompressedTuple instead once it supports EBO for
- // nested `CompressedTuple`s.
- struct checked_compare : checked_compare_base<Compare> {
- private:
- using Base = typename checked_compare::checked_compare_base;
- using Base::comp;
-
- // If possible, returns whether `t` is equivalent to itself. We can only do
- // this for `Key`s because we can't be sure that it's safe to call
- // `comp()(k, k)` otherwise. Even if SFINAE allows it, there could be a
- // compilation failure inside the implementation of the comparison operator.
- bool is_self_equivalent(const Key &k) const {
- // Note: this works for both boolean and three-way comparators.
- return comp()(k, k) == 0;
- }
- // If we can't compare `t` with itself, returns true unconditionally.
- template <typename T>
- bool is_self_equivalent(const T &) const {
- return true;
- }
-
- public:
- using Base::Base;
- checked_compare(Compare comp) : Base(std::move(comp)) {} // NOLINT
-
- // Allow converting to Compare for use in key_comp()/value_comp().
- explicit operator Compare() const { return comp(); }
-
- template <typename T, typename U,
- absl::enable_if_t<
- std::is_same<bool, compare_result_t<Compare, T, U>>::value,
- int> = 0>
- bool operator()(const T &lhs, const U &rhs) const {
- // NOTE: if any of these assertions fail, then the comparator does not
- // establish a strict-weak-ordering (see
- // https://en.cppreference.com/w/cpp/named_req/Compare).
- assert(is_self_equivalent(lhs));
- assert(is_self_equivalent(rhs));
- const bool lhs_comp_rhs = comp()(lhs, rhs);
- assert(!lhs_comp_rhs || !comp()(rhs, lhs));
- return lhs_comp_rhs;
- }
-
- template <
- typename T, typename U,
- absl::enable_if_t<std::is_convertible<compare_result_t<Compare, T, U>,
- absl::weak_ordering>::value,
- int> = 0>
- absl::weak_ordering operator()(const T &lhs, const U &rhs) const {
- // NOTE: if any of these assertions fail, then the comparator does not
- // establish a strict-weak-ordering (see
- // https://en.cppreference.com/w/cpp/named_req/Compare).
- assert(is_self_equivalent(lhs));
- assert(is_self_equivalent(rhs));
- const absl::weak_ordering lhs_comp_rhs = comp()(lhs, rhs);
-#ifndef NDEBUG
- const absl::weak_ordering rhs_comp_lhs = comp()(rhs, lhs);
- if (lhs_comp_rhs > 0) {
- assert(rhs_comp_lhs < 0 && "lhs_comp_rhs > 0 -> rhs_comp_lhs < 0");
- } else if (lhs_comp_rhs == 0) {
- assert(rhs_comp_lhs == 0 && "lhs_comp_rhs == 0 -> rhs_comp_lhs == 0");
- } else {
- assert(rhs_comp_lhs > 0 && "lhs_comp_rhs < 0 -> rhs_comp_lhs > 0");
- }
-#endif
- return lhs_comp_rhs;
- }
- };
- using type = absl::conditional_t<
- std::is_base_of<BtreeTestOnlyCheckedCompareOptOutBase, Compare>::value,
- Compare, checked_compare>;
-};
-
-template <>
-struct key_compare_adapter<std::less<std::string>, std::string> {
- using type = StringBtreeDefaultLess;
-};
-
-template <>
-struct key_compare_adapter<std::greater<std::string>, std::string> {
- using type = StringBtreeDefaultGreater;
-};
-
-template <>
-struct key_compare_adapter<std::less<absl::string_view>, absl::string_view> {
- using type = StringBtreeDefaultLess;
-};
-
-template <>
-struct key_compare_adapter<std::greater<absl::string_view>, absl::string_view> {
- using type = StringBtreeDefaultGreater;
-};
-
-template <>
-struct key_compare_adapter<std::less<absl::Cord>, absl::Cord> {
- using type = StringBtreeDefaultLess;
-};
-
-template <>
-struct key_compare_adapter<std::greater<absl::Cord>, absl::Cord> {
- using type = StringBtreeDefaultGreater;
-};
-
-// Detects an 'absl_btree_prefer_linear_node_search' member. This is
-// a protocol used as an opt-in or opt-out of linear search.
-//
-// For example, this would be useful for key types that wrap an integer
-// and define their own cheap operator<(). For example:
-//
-// class K {
-// public:
-// using absl_btree_prefer_linear_node_search = std::true_type;
-// ...
-// private:
-// friend bool operator<(K a, K b) { return a.k_ < b.k_; }
-// int k_;
-// };
-//
-// btree_map<K, V> m; // Uses linear search
-//
-// If T has the preference tag, then it has a preference.
-// Btree will use the tag's truth value.
-template <typename T, typename = void>
-struct has_linear_node_search_preference : std::false_type {};
-template <typename T, typename = void>
-struct prefers_linear_node_search : std::false_type {};
-template <typename T>
-struct has_linear_node_search_preference<
- T, absl::void_t<typename T::absl_btree_prefer_linear_node_search>>
- : std::true_type {};
-template <typename T>
-struct prefers_linear_node_search<
- T, absl::void_t<typename T::absl_btree_prefer_linear_node_search>>
- : T::absl_btree_prefer_linear_node_search {};
-
-template <typename Compare, typename Key>
-constexpr bool compare_has_valid_result_type() {
- using compare_result_type = compare_result_t<Compare, Key, Key>;
- return std::is_same<compare_result_type, bool>::value ||
- std::is_convertible<compare_result_type, absl::weak_ordering>::value;
-}
-
-template <typename original_key_compare, typename value_type>
-class map_value_compare {
- template <typename Params>
- friend class btree;
-
- // Note: this `protected` is part of the API of std::map::value_compare. See
- // https://en.cppreference.com/w/cpp/container/map/value_compare.
- protected:
- explicit map_value_compare(original_key_compare c) : comp(std::move(c)) {}
-
- original_key_compare comp; // NOLINT
-
- public:
- auto operator()(const value_type &lhs, const value_type &rhs) const
- -> decltype(comp(lhs.first, rhs.first)) {
- return comp(lhs.first, rhs.first);
- }
-};
-
-template <typename Key, typename Compare, typename Alloc, int TargetNodeSize,
- bool IsMulti, bool IsMap, typename SlotPolicy>
-struct common_params : common_policy_traits<SlotPolicy> {
- using original_key_compare = Compare;
-
- // If Compare is a common comparator for a string-like type, then we adapt it
- // to use heterogeneous lookup and to be a key-compare-to comparator.
- // We also adapt the comparator to diagnose invalid comparators in debug mode.
- // We disable this when `Compare` is invalid in a way that will cause
- // adaptation to fail (having invalid return type) so that we can give a
- // better compilation failure in static_assert_validation. If we don't do
- // this, then there will be cascading compilation failures that are confusing
- // for users.
- using key_compare =
- absl::conditional_t<!compare_has_valid_result_type<Compare, Key>(),
- Compare,
- typename key_compare_adapter<Compare, Key>::type>;
-
- static constexpr bool kIsKeyCompareStringAdapted =
- std::is_same<key_compare, StringBtreeDefaultLess>::value ||
- std::is_same<key_compare, StringBtreeDefaultGreater>::value;
- static constexpr bool kIsKeyCompareTransparent =
- IsTransparent<original_key_compare>::value || kIsKeyCompareStringAdapted;
- static constexpr bool kEnableGenerations =
-#ifdef ABSL_BTREE_ENABLE_GENERATIONS
- true;
-#else
- false;
-#endif
-
- // A type which indicates if we have a key-compare-to functor or a plain old
- // key-compare functor.
- using is_key_compare_to = btree_is_key_compare_to<key_compare, Key>;
-
- using allocator_type = Alloc;
- using key_type = Key;
- using size_type = size_t;
- using difference_type = ptrdiff_t;
-
- using slot_policy = SlotPolicy;
- using slot_type = typename slot_policy::slot_type;
- using value_type = typename slot_policy::value_type;
- using init_type = typename slot_policy::mutable_value_type;
- using pointer = value_type *;
- using const_pointer = const value_type *;
- using reference = value_type &;
- using const_reference = const value_type &;
-
- using value_compare =
- absl::conditional_t<IsMap,
- map_value_compare<original_key_compare, value_type>,
- original_key_compare>;
- using is_map_container = std::integral_constant<bool, IsMap>;
-
- // For the given lookup key type, returns whether we can have multiple
- // equivalent keys in the btree. If this is a multi-container, then we can.
- // Otherwise, we can have multiple equivalent keys only if all of the
- // following conditions are met:
- // - The comparator is transparent.
- // - The lookup key type is not the same as key_type.
- // - The comparator is not a StringBtreeDefault{Less,Greater} comparator
- // that we know has the same equivalence classes for all lookup types.
- template <typename LookupKey>
- constexpr static bool can_have_multiple_equivalent_keys() {
- return IsMulti || (IsTransparent<key_compare>::value &&
- !std::is_same<LookupKey, Key>::value &&
- !kIsKeyCompareStringAdapted);
- }
-
- enum {
- kTargetNodeSize = TargetNodeSize,
-
- // Upper bound for the available space for slots. This is largest for leaf
- // nodes, which have overhead of at least a pointer + 4 bytes (for storing
- // 3 field_types and an enum).
- kNodeSlotSpace = TargetNodeSize - /*minimum overhead=*/(sizeof(void *) + 4),
- };
-
- // This is an integral type large enough to hold as many slots as will fit a
- // node of TargetNodeSize bytes.
- using node_count_type =
- absl::conditional_t<(kNodeSlotSpace / sizeof(slot_type) >
- (std::numeric_limits<uint8_t>::max)()),
- uint16_t, uint8_t>; // NOLINT
-};
-
-// An adapter class that converts a lower-bound compare into an upper-bound
-// compare. Note: there is no need to make a version of this adapter specialized
-// for key-compare-to functors because the upper-bound (the first value greater
-// than the input) is never an exact match.
-template <typename Compare>
-struct upper_bound_adapter {
- explicit upper_bound_adapter(const Compare &c) : comp(c) {}
- template <typename K1, typename K2>
- bool operator()(const K1 &a, const K2 &b) const {
- // Returns true when a is not greater than b.
- return !compare_internal::compare_result_as_less_than(comp(b, a));
- }
-
- private:
- Compare comp;
-};
-
-enum class MatchKind : uint8_t { kEq, kNe };
-
-template <typename V, bool IsCompareTo>
-struct SearchResult {
- V value;
- MatchKind match;
-
- static constexpr bool HasMatch() { return true; }
- bool IsEq() const { return match == MatchKind::kEq; }
-};
-
-// When we don't use CompareTo, `match` is not present.
-// This ensures that callers can't use it accidentally when it provides no
-// useful information.
-template <typename V>
-struct SearchResult<V, false> {
- SearchResult() {}
- explicit SearchResult(V v) : value(v) {}
- SearchResult(V v, MatchKind /*match*/) : value(v) {}
-
- V value;
-
- static constexpr bool HasMatch() { return false; }
- static constexpr bool IsEq() { return false; }
-};
-
-// A node in the btree holding. The same node type is used for both internal
-// and leaf nodes in the btree, though the nodes are allocated in such a way
-// that the children array is only valid in internal nodes.
-template <typename Params>
-class btree_node {
- using is_key_compare_to = typename Params::is_key_compare_to;
- using field_type = typename Params::node_count_type;
- using allocator_type = typename Params::allocator_type;
- using slot_type = typename Params::slot_type;
- using original_key_compare = typename Params::original_key_compare;
-
- public:
- using params_type = Params;
- using key_type = typename Params::key_type;
- using value_type = typename Params::value_type;
- using pointer = typename Params::pointer;
- using const_pointer = typename Params::const_pointer;
- using reference = typename Params::reference;
- using const_reference = typename Params::const_reference;
- using key_compare = typename Params::key_compare;
- using size_type = typename Params::size_type;
- using difference_type = typename Params::difference_type;
-
- // Btree decides whether to use linear node search as follows:
- // - If the comparator expresses a preference, use that.
- // - If the key expresses a preference, use that.
- // - If the key is arithmetic and the comparator is std::less or
- // std::greater, choose linear.
- // - Otherwise, choose binary.
- // TODO(ezb): Might make sense to add condition(s) based on node-size.
- using use_linear_search = std::integral_constant<
- bool, has_linear_node_search_preference<original_key_compare>::value
- ? prefers_linear_node_search<original_key_compare>::value
- : has_linear_node_search_preference<key_type>::value
- ? prefers_linear_node_search<key_type>::value
- : std::is_arithmetic<key_type>::value &&
- (std::is_same<std::less<key_type>,
- original_key_compare>::value ||
- std::is_same<std::greater<key_type>,
- original_key_compare>::value)>;
-
- // This class is organized by absl::container_internal::Layout as if it had
- // the following structure:
- // // A pointer to the node's parent.
- // btree_node *parent;
- //
- // // When ABSL_BTREE_ENABLE_GENERATIONS is defined, we also have a
- // // generation integer in order to check that when iterators are
- // // used, they haven't been invalidated already. Only the generation on
- // // the root is used, but we have one on each node because whether a node
- // // is root or not can change.
- // uint32_t generation;
- //
- // // The position of the node in the node's parent.
- // field_type position;
- // // The index of the first populated value in `values`.
- // // TODO(ezb): right now, `start` is always 0. Update insertion/merge
- // // logic to allow for floating storage within nodes.
- // field_type start;
- // // The index after the last populated value in `values`. Currently, this
- // // is the same as the count of values.
- // field_type finish;
- // // The maximum number of values the node can hold. This is an integer in
- // // [1, kNodeSlots] for root leaf nodes, kNodeSlots for non-root leaf
- // // nodes, and kInternalNodeMaxCount (as a sentinel value) for internal
- // // nodes (even though there are still kNodeSlots values in the node).
- // // TODO(ezb): make max_count use only 4 bits and record log2(capacity)
- // // to free extra bits for is_root, etc.
- // field_type max_count;
- //
- // // The array of values. The capacity is `max_count` for leaf nodes and
- // // kNodeSlots for internal nodes. Only the values in
- // // [start, finish) have been initialized and are valid.
- // slot_type values[max_count];
- //
- // // The array of child pointers. The keys in children[i] are all less
- // // than key(i). The keys in children[i + 1] are all greater than key(i).
- // // There are 0 children for leaf nodes and kNodeSlots + 1 children for
- // // internal nodes.
- // btree_node *children[kNodeSlots + 1];
- //
- // This class is only constructed by EmptyNodeType. Normally, pointers to the
- // layout above are allocated, cast to btree_node*, and de-allocated within
- // the btree implementation.
- ~btree_node() = default;
- btree_node(btree_node const &) = delete;
- btree_node &operator=(btree_node const &) = delete;
-
- // Public for EmptyNodeType.
- constexpr static size_type Alignment() {
- static_assert(LeafLayout(1).Alignment() == InternalLayout().Alignment(),
- "Alignment of all nodes must be equal.");
- return InternalLayout().Alignment();
- }
-
- protected:
- btree_node() = default;
-
- private:
- using layout_type =
- absl::container_internal::Layout<btree_node *, uint32_t, field_type,
- slot_type, btree_node *>;
- constexpr static size_type SizeWithNSlots(size_type n) {
- return layout_type(
- /*parent*/ 1,
- /*generation*/ params_type::kEnableGenerations ? 1 : 0,
- /*position, start, finish, max_count*/ 4,
- /*slots*/ n,
- /*children*/ 0)
- .AllocSize();
- }
- // A lower bound for the overhead of fields other than slots in a leaf node.
- constexpr static size_type MinimumOverhead() {
- return SizeWithNSlots(1) - sizeof(slot_type);
- }
-
- // Compute how many values we can fit onto a leaf node taking into account
- // padding.
- constexpr static size_type NodeTargetSlots(const size_type begin,
- const size_type end) {
- return begin == end ? begin
- : SizeWithNSlots((begin + end) / 2 + 1) >
- params_type::kTargetNodeSize
- ? NodeTargetSlots(begin, (begin + end) / 2)
- : NodeTargetSlots((begin + end) / 2 + 1, end);
- }
-
- constexpr static size_type kTargetNodeSize = params_type::kTargetNodeSize;
- constexpr static size_type kNodeTargetSlots =
- NodeTargetSlots(0, kTargetNodeSize);
-
- // We need a minimum of 3 slots per internal node in order to perform
- // splitting (1 value for the two nodes involved in the split and 1 value
- // propagated to the parent as the delimiter for the split). For performance
- // reasons, we don't allow 3 slots-per-node due to bad worst case occupancy of
- // 1/3 (for a node, not a b-tree).
- constexpr static size_type kMinNodeSlots = 4;
-
- constexpr static size_type kNodeSlots =
- kNodeTargetSlots >= kMinNodeSlots ? kNodeTargetSlots : kMinNodeSlots;
-
- // The node is internal (i.e. is not a leaf node) if and only if `max_count`
- // has this value.
- constexpr static field_type kInternalNodeMaxCount = 0;
-
- // Leaves can have less than kNodeSlots values.
- constexpr static layout_type LeafLayout(
- const size_type slot_count = kNodeSlots) {
- return layout_type(
- /*parent*/ 1,
- /*generation*/ params_type::kEnableGenerations ? 1 : 0,
- /*position, start, finish, max_count*/ 4,
- /*slots*/ slot_count,
- /*children*/ 0);
- }
- constexpr static layout_type InternalLayout() {
- return layout_type(
- /*parent*/ 1,
- /*generation*/ params_type::kEnableGenerations ? 1 : 0,
- /*position, start, finish, max_count*/ 4,
- /*slots*/ kNodeSlots,
- /*children*/ kNodeSlots + 1);
- }
- constexpr static size_type LeafSize(const size_type slot_count = kNodeSlots) {
- return LeafLayout(slot_count).AllocSize();
- }
- constexpr static size_type InternalSize() {
- return InternalLayout().AllocSize();
- }
-
- // N is the index of the type in the Layout definition.
- // ElementType<N> is the Nth type in the Layout definition.
- template <size_type N>
- inline typename layout_type::template ElementType<N> *GetField() {
- // We assert that we don't read from values that aren't there.
- assert(N < 4 || is_internal());
- return InternalLayout().template Pointer<N>(reinterpret_cast<char *>(this));
- }
- template <size_type N>
- inline const typename layout_type::template ElementType<N> *GetField() const {
- assert(N < 4 || is_internal());
- return InternalLayout().template Pointer<N>(
- reinterpret_cast<const char *>(this));
- }
- void set_parent(btree_node *p) { *GetField<0>() = p; }
- field_type &mutable_finish() { return GetField<2>()[2]; }
- slot_type *slot(size_type i) { return &GetField<3>()[i]; }
- slot_type *start_slot() { return slot(start()); }
- slot_type *finish_slot() { return slot(finish()); }
- const slot_type *slot(size_type i) const { return &GetField<3>()[i]; }
- void set_position(field_type v) { GetField<2>()[0] = v; }
- void set_start(field_type v) { GetField<2>()[1] = v; }
- void set_finish(field_type v) { GetField<2>()[2] = v; }
- // This method is only called by the node init methods.
- void set_max_count(field_type v) { GetField<2>()[3] = v; }
-
- public:
- // Whether this is a leaf node or not. This value doesn't change after the
- // node is created.
- bool is_leaf() const { return GetField<2>()[3] != kInternalNodeMaxCount; }
- // Whether this is an internal node or not. This value doesn't change after
- // the node is created.
- bool is_internal() const { return !is_leaf(); }
-
- // Getter for the position of this node in its parent.
- field_type position() const { return GetField<2>()[0]; }
-
- // Getter for the offset of the first value in the `values` array.
- field_type start() const {
- // TODO(ezb): when floating storage is implemented, return GetField<2>()[1];
- assert(GetField<2>()[1] == 0);
- return 0;
- }
-
- // Getter for the offset after the last value in the `values` array.
- field_type finish() const { return GetField<2>()[2]; }
-
- // Getters for the number of values stored in this node.
- field_type count() const {
- assert(finish() >= start());
- return finish() - start();
- }
- field_type max_count() const {
- // Internal nodes have max_count==kInternalNodeMaxCount.
- // Leaf nodes have max_count in [1, kNodeSlots].
- const field_type max_count = GetField<2>()[3];
- return max_count == field_type{kInternalNodeMaxCount}
- ? field_type{kNodeSlots}
- : max_count;
- }
-
- // Getter for the parent of this node.
- btree_node *parent() const { return *GetField<0>(); }
- // Getter for whether the node is the root of the tree. The parent of the
- // root of the tree is the leftmost node in the tree which is guaranteed to
- // be a leaf.
- bool is_root() const { return parent()->is_leaf(); }
- void make_root() {
- assert(parent()->is_root());
- set_generation(parent()->generation());
- set_parent(parent()->parent());
- }
-
- // Gets the root node's generation integer, which is the one used by the tree.
- uint32_t *get_root_generation() const {
- assert(params_type::kEnableGenerations);
- const btree_node *curr = this;
- for (; !curr->is_root(); curr = curr->parent()) continue;
- return const_cast<uint32_t *>(&curr->GetField<1>()[0]);
- }
-
- // Returns the generation for iterator validation.
- uint32_t generation() const {
- return params_type::kEnableGenerations ? *get_root_generation() : 0;
- }
- // Updates generation. Should only be called on a root node or during node
- // initialization.
- void set_generation(uint32_t generation) {
- if (params_type::kEnableGenerations) GetField<1>()[0] = generation;
- }
- // Updates the generation. We do this whenever the node is mutated.
- void next_generation() {
- if (params_type::kEnableGenerations) ++*get_root_generation();
- }
-
- // Getters for the key/value at position i in the node.
- const key_type &key(size_type i) const { return params_type::key(slot(i)); }
- reference value(size_type i) { return params_type::element(slot(i)); }
- const_reference value(size_type i) const {
- return params_type::element(slot(i));
- }
-
- // Getters/setter for the child at position i in the node.
- btree_node *child(field_type i) const { return GetField<4>()[i]; }
- btree_node *start_child() const { return child(start()); }
- btree_node *&mutable_child(field_type i) { return GetField<4>()[i]; }
- void clear_child(field_type i) {
- absl::container_internal::SanitizerPoisonObject(&mutable_child(i));
- }
- void set_child(field_type i, btree_node *c) {
- absl::container_internal::SanitizerUnpoisonObject(&mutable_child(i));
- mutable_child(i) = c;
- c->set_position(i);
- }
- void init_child(field_type i, btree_node *c) {
- set_child(i, c);
- c->set_parent(this);
- }
-
- // Returns the position of the first value whose key is not less than k.
- template <typename K>
- SearchResult<size_type, is_key_compare_to::value> lower_bound(
- const K &k, const key_compare &comp) const {
- return use_linear_search::value ? linear_search(k, comp)
- : binary_search(k, comp);
- }
- // Returns the position of the first value whose key is greater than k.
- template <typename K>
- size_type upper_bound(const K &k, const key_compare &comp) const {
- auto upper_compare = upper_bound_adapter<key_compare>(comp);
- return use_linear_search::value ? linear_search(k, upper_compare).value
- : binary_search(k, upper_compare).value;
- }
-
- template <typename K, typename Compare>
- SearchResult<size_type, btree_is_key_compare_to<Compare, key_type>::value>
- linear_search(const K &k, const Compare &comp) const {
- return linear_search_impl(k, start(), finish(), comp,
- btree_is_key_compare_to<Compare, key_type>());
- }
-
- template <typename K, typename Compare>
- SearchResult<size_type, btree_is_key_compare_to<Compare, key_type>::value>
- binary_search(const K &k, const Compare &comp) const {
- return binary_search_impl(k, start(), finish(), comp,
- btree_is_key_compare_to<Compare, key_type>());
- }
-
- // Returns the position of the first value whose key is not less than k using
- // linear search performed using plain compare.
- template <typename K, typename Compare>
- SearchResult<size_type, false> linear_search_impl(
- const K &k, size_type s, const size_type e, const Compare &comp,
- std::false_type /* IsCompareTo */) const {
- while (s < e) {
- if (!comp(key(s), k)) {
- break;
- }
- ++s;
- }
- return SearchResult<size_type, false>{s};
- }
-
- // Returns the position of the first value whose key is not less than k using
- // linear search performed using compare-to.
- template <typename K, typename Compare>
- SearchResult<size_type, true> linear_search_impl(
- const K &k, size_type s, const size_type e, const Compare &comp,
- std::true_type /* IsCompareTo */) const {
- while (s < e) {
- const absl::weak_ordering c = comp(key(s), k);
- if (c == 0) {
- return {s, MatchKind::kEq};
- } else if (c > 0) {
- break;
- }
- ++s;
- }
- return {s, MatchKind::kNe};
- }
-
- // Returns the position of the first value whose key is not less than k using
- // binary search performed using plain compare.
- template <typename K, typename Compare>
- SearchResult<size_type, false> binary_search_impl(
- const K &k, size_type s, size_type e, const Compare &comp,
- std::false_type /* IsCompareTo */) const {
- while (s != e) {
- const size_type mid = (s + e) >> 1;
- if (comp(key(mid), k)) {
- s = mid + 1;
- } else {
- e = mid;
- }
- }
- return SearchResult<size_type, false>{s};
- }
-
- // Returns the position of the first value whose key is not less than k using
- // binary search performed using compare-to.
- template <typename K, typename CompareTo>
- SearchResult<size_type, true> binary_search_impl(
- const K &k, size_type s, size_type e, const CompareTo &comp,
- std::true_type /* IsCompareTo */) const {
- if (params_type::template can_have_multiple_equivalent_keys<K>()) {
- MatchKind exact_match = MatchKind::kNe;
- while (s != e) {
- const size_type mid = (s + e) >> 1;
- const absl::weak_ordering c = comp(key(mid), k);
- if (c < 0) {
- s = mid + 1;
- } else {
- e = mid;
- if (c == 0) {
- // Need to return the first value whose key is not less than k,
- // which requires continuing the binary search if there could be
- // multiple equivalent keys.
- exact_match = MatchKind::kEq;
- }
- }
- }
- return {s, exact_match};
- } else { // Can't have multiple equivalent keys.
- while (s != e) {
- const size_type mid = (s + e) >> 1;
- const absl::weak_ordering c = comp(key(mid), k);
- if (c < 0) {
- s = mid + 1;
- } else if (c > 0) {
- e = mid;
- } else {
- return {mid, MatchKind::kEq};
- }
- }
- return {s, MatchKind::kNe};
- }
- }
-
- // Emplaces a value at position i, shifting all existing values and
- // children at positions >= i to the right by 1.
- template <typename... Args>
- void emplace_value(field_type i, allocator_type *alloc, Args &&...args);
-
- // Removes the values at positions [i, i + to_erase), shifting all existing
- // values and children after that range to the left by to_erase. Clears all
- // children between [i, i + to_erase).
- void remove_values(field_type i, field_type to_erase, allocator_type *alloc);
-
- // Rebalances a node with its right sibling.
- void rebalance_right_to_left(field_type to_move, btree_node *right,
- allocator_type *alloc);
- void rebalance_left_to_right(field_type to_move, btree_node *right,
- allocator_type *alloc);
-
- // Splits a node, moving a portion of the node's values to its right sibling.
- void split(int insert_position, btree_node *dest, allocator_type *alloc);
-
- // Merges a node with its right sibling, moving all of the values and the
- // delimiting key in the parent node onto itself, and deleting the src node.
- void merge(btree_node *src, allocator_type *alloc);
-
- // Node allocation/deletion routines.
- void init_leaf(field_type max_count, btree_node *parent) {
- set_generation(0);
- set_parent(parent);
- set_position(0);
- set_start(0);
- set_finish(0);
- set_max_count(max_count);
- absl::container_internal::SanitizerPoisonMemoryRegion(
- start_slot(), max_count * sizeof(slot_type));
- }
- void init_internal(btree_node *parent) {
- init_leaf(kNodeSlots, parent);
- // Set `max_count` to a sentinel value to indicate that this node is
- // internal.
- set_max_count(kInternalNodeMaxCount);
- absl::container_internal::SanitizerPoisonMemoryRegion(
- &mutable_child(start()), (kNodeSlots + 1) * sizeof(btree_node *));
- }
-
- static void deallocate(const size_type size, btree_node *node,
- allocator_type *alloc) {
- absl::container_internal::SanitizerUnpoisonMemoryRegion(node, size);
- absl::container_internal::Deallocate<Alignment()>(alloc, node, size);
- }
-
- // Deletes a node and all of its children.
- static void clear_and_delete(btree_node *node, allocator_type *alloc);
-
- private:
- template <typename... Args>
- void value_init(const field_type i, allocator_type *alloc, Args &&...args) {
- next_generation();
- absl::container_internal::SanitizerUnpoisonObject(slot(i));
- params_type::construct(alloc, slot(i), std::forward<Args>(args)...);
- }
- void value_destroy(const field_type i, allocator_type *alloc) {
- next_generation();
- params_type::destroy(alloc, slot(i));
- absl::container_internal::SanitizerPoisonObject(slot(i));
- }
- void value_destroy_n(const field_type i, const field_type n,
- allocator_type *alloc) {
- next_generation();
- for (slot_type *s = slot(i), *end = slot(i + n); s != end; ++s) {
- params_type::destroy(alloc, s);
- absl::container_internal::SanitizerPoisonObject(s);
- }
- }
-
- static void transfer(slot_type *dest, slot_type *src, allocator_type *alloc) {
- absl::container_internal::SanitizerUnpoisonObject(dest);
- params_type::transfer(alloc, dest, src);
- absl::container_internal::SanitizerPoisonObject(src);
- }
-
- // Transfers value from slot `src_i` in `src_node` to slot `dest_i` in `this`.
- void transfer(const size_type dest_i, const size_type src_i,
- btree_node *src_node, allocator_type *alloc) {
- next_generation();
- transfer(slot(dest_i), src_node->slot(src_i), alloc);
- }
-
- // Transfers `n` values starting at value `src_i` in `src_node` into the
- // values starting at value `dest_i` in `this`.
- void transfer_n(const size_type n, const size_type dest_i,
- const size_type src_i, btree_node *src_node,
- allocator_type *alloc) {
- next_generation();
- for (slot_type *src = src_node->slot(src_i), *end = src + n,
- *dest = slot(dest_i);
- src != end; ++src, ++dest) {
- transfer(dest, src, alloc);
- }
- }
-
- // Same as above, except that we start at the end and work our way to the
- // beginning.
- void transfer_n_backward(const size_type n, const size_type dest_i,
- const size_type src_i, btree_node *src_node,
- allocator_type *alloc) {
- next_generation();
- for (slot_type *src = src_node->slot(src_i + n), *end = src - n,
- *dest = slot(dest_i + n);
- src != end; --src, --dest) {
- // If we modified the loop index calculations above to avoid the -1s here,
- // it would result in UB in the computation of `end` (and possibly `src`
- // as well, if n == 0), since slot() is effectively an array index and it
- // is UB to compute the address of any out-of-bounds array element except
- // for one-past-the-end.
- transfer(dest - 1, src - 1, alloc);
- }
- }
-
- template <typename P>
- friend class btree;
- template <typename N, typename R, typename P>
- friend class btree_iterator;
- friend class BtreeNodePeer;
- friend struct btree_access;
-};
-
-template <typename Node, typename Reference, typename Pointer>
-class btree_iterator {
- using field_type = typename Node::field_type;
- using key_type = typename Node::key_type;
- using size_type = typename Node::size_type;
- using params_type = typename Node::params_type;
- using is_map_container = typename params_type::is_map_container;
-
- using node_type = Node;
- using normal_node = typename std::remove_const<Node>::type;
- using const_node = const Node;
- using normal_pointer = typename params_type::pointer;
- using normal_reference = typename params_type::reference;
- using const_pointer = typename params_type::const_pointer;
- using const_reference = typename params_type::const_reference;
- using slot_type = typename params_type::slot_type;
-
- using iterator =
- btree_iterator<normal_node, normal_reference, normal_pointer>;
- using const_iterator =
- btree_iterator<const_node, const_reference, const_pointer>;
-
- public:
- // These aliases are public for std::iterator_traits.
- using difference_type = typename Node::difference_type;
- using value_type = typename params_type::value_type;
- using pointer = Pointer;
- using reference = Reference;
- using iterator_category = std::bidirectional_iterator_tag;
-
- btree_iterator() : btree_iterator(nullptr, -1) {}
- explicit btree_iterator(Node *n) : btree_iterator(n, n->start()) {}
- btree_iterator(Node *n, int p) : node_(n), position_(p) {
-#ifdef ABSL_BTREE_ENABLE_GENERATIONS
- // Use `~uint32_t{}` as a sentinel value for iterator generations so it
- // doesn't match the initial value for the actual generation.
- generation_ = n != nullptr ? n->generation() : ~uint32_t{};
-#endif
- }
-
- // NOTE: this SFINAE allows for implicit conversions from iterator to
- // const_iterator, but it specifically avoids hiding the copy constructor so
- // that the trivial one will be used when possible.
- template <typename N, typename R, typename P,
- absl::enable_if_t<
- std::is_same<btree_iterator<N, R, P>, iterator>::value &&
- std::is_same<btree_iterator, const_iterator>::value,
- int> = 0>
- btree_iterator(const btree_iterator<N, R, P> other) // NOLINT
- : node_(other.node_), position_(other.position_) {
-#ifdef ABSL_BTREE_ENABLE_GENERATIONS
- generation_ = other.generation_;
-#endif
- }
-
- bool operator==(const iterator &other) const {
- return node_ == other.node_ && position_ == other.position_;
- }
- bool operator==(const const_iterator &other) const {
- return node_ == other.node_ && position_ == other.position_;
- }
- bool operator!=(const iterator &other) const {
- return node_ != other.node_ || position_ != other.position_;
- }
- bool operator!=(const const_iterator &other) const {
- return node_ != other.node_ || position_ != other.position_;
- }
-
- // Returns n such that n calls to ++other yields *this.
- // Precondition: n exists.
- difference_type operator-(const_iterator other) const {
- if (node_ == other.node_) {
- if (node_->is_leaf()) return position_ - other.position_;
- if (position_ == other.position_) return 0;
- }
- return distance_slow(other);
- }
-
- // Accessors for the key/value the iterator is pointing at.
- reference operator*() const {
- ABSL_HARDENING_ASSERT(node_ != nullptr);
- assert_valid_generation();
- ABSL_HARDENING_ASSERT(position_ >= node_->start());
- if (position_ >= node_->finish()) {
- ABSL_HARDENING_ASSERT(!IsEndIterator() && "Dereferencing end() iterator");
- ABSL_HARDENING_ASSERT(position_ < node_->finish());
- }
- return node_->value(static_cast<field_type>(position_));
- }
- pointer operator->() const { return &operator*(); }
-
- btree_iterator &operator++() {
- increment();
- return *this;
- }
- btree_iterator &operator--() {
- decrement();
- return *this;
- }
- btree_iterator operator++(int) {
- btree_iterator tmp = *this;
- ++*this;
- return tmp;
- }
- btree_iterator operator--(int) {
- btree_iterator tmp = *this;
- --*this;
- return tmp;
- }
-
- private:
- friend iterator;
- friend const_iterator;
- template <typename Params>
- friend class btree;
- template <typename Tree>
- friend class btree_container;
- template <typename Tree>
- friend class btree_set_container;
- template <typename Tree>
- friend class btree_map_container;
- template <typename Tree>
- friend class btree_multiset_container;
- template <typename TreeType, typename CheckerType>
- friend class base_checker;
- friend struct btree_access;
-
- // This SFINAE allows explicit conversions from const_iterator to
- // iterator, but also avoids hiding the copy constructor.
- // NOTE: the const_cast is safe because this constructor is only called by
- // non-const methods and the container owns the nodes.
- template <typename N, typename R, typename P,
- absl::enable_if_t<
- std::is_same<btree_iterator<N, R, P>, const_iterator>::value &&
- std::is_same<btree_iterator, iterator>::value,
- int> = 0>
- explicit btree_iterator(const btree_iterator<N, R, P> other)
- : node_(const_cast<node_type *>(other.node_)),
- position_(other.position_) {
-#ifdef ABSL_BTREE_ENABLE_GENERATIONS
- generation_ = other.generation_;
-#endif
- }
-
- bool IsEndIterator() const {
- if (position_ != node_->finish()) return false;
- // Navigate to the rightmost node.
- node_type *node = node_;
- while (!node->is_root()) node = node->parent();
- while (node->is_internal()) node = node->child(node->finish());
- return node == node_;
- }
-
- // Returns n such that n calls to ++other yields *this.
- // Precondition: n exists && (this->node_ != other.node_ ||
- // !this->node_->is_leaf() || this->position_ != other.position_).
- difference_type distance_slow(const_iterator other) const;
-
- // Increment/decrement the iterator.
- void increment() {
- assert_valid_generation();
- if (node_->is_leaf() && ++position_ < node_->finish()) {
- return;
- }
- increment_slow();
- }
- void increment_slow();
-
- void decrement() {
- assert_valid_generation();
- if (node_->is_leaf() && --position_ >= node_->start()) {
- return;
- }
- decrement_slow();
- }
- void decrement_slow();
-
- // Updates the generation. For use internally right before we return an
- // iterator to the user.
- void update_generation() {
-#ifdef ABSL_BTREE_ENABLE_GENERATIONS
- if (node_ != nullptr) generation_ = node_->generation();
-#endif
- }
-
- const key_type &key() const {
- return node_->key(static_cast<size_type>(position_));
- }
- decltype(std::declval<Node *>()->slot(0)) slot() {
- return node_->slot(static_cast<size_type>(position_));
- }
-
- void assert_valid_generation() const {
-#ifdef ABSL_BTREE_ENABLE_GENERATIONS
- if (node_ != nullptr && node_->generation() != generation_) {
- ABSL_INTERNAL_LOG(
- FATAL,
- "Attempting to use an invalidated iterator. The corresponding b-tree "
- "container has been mutated since this iterator was constructed.");
- }
-#endif
- }
-
- // The node in the tree the iterator is pointing at.
- Node *node_;
- // The position within the node of the tree the iterator is pointing at.
- // NOTE: this is an int rather than a field_type because iterators can point
- // to invalid positions (such as -1) in certain circumstances.
- int position_;
-#ifdef ABSL_BTREE_ENABLE_GENERATIONS
- // Used to check that the iterator hasn't been invalidated.
- uint32_t generation_;
-#endif
-};
-
-template <typename Params>
-class btree {
- using node_type = btree_node<Params>;
- using is_key_compare_to = typename Params::is_key_compare_to;
- using field_type = typename node_type::field_type;
-
- // We use a static empty node for the root/leftmost/rightmost of empty btrees
- // in order to avoid branching in begin()/end().
- struct alignas(node_type::Alignment()) EmptyNodeType : node_type {
- using field_type = typename node_type::field_type;
- node_type *parent;
-#ifdef ABSL_BTREE_ENABLE_GENERATIONS
- uint32_t generation = 0;
-#endif
- field_type position = 0;
- field_type start = 0;
- field_type finish = 0;
- // max_count must be != kInternalNodeMaxCount (so that this node is regarded
- // as a leaf node). max_count() is never called when the tree is empty.
- field_type max_count = node_type::kInternalNodeMaxCount + 1;
-
-#ifdef _MSC_VER
- // MSVC has constexpr code generations bugs here.
- EmptyNodeType() : parent(this) {}
-#else
- explicit constexpr EmptyNodeType(node_type *p) : parent(p) {}
-#endif
- };
-
- static node_type *EmptyNode() {
-#ifdef _MSC_VER
- static EmptyNodeType *empty_node = new EmptyNodeType;
- // This assert fails on some other construction methods.
- assert(empty_node->parent == empty_node);
- return empty_node;
-#else
- static constexpr EmptyNodeType empty_node(
- const_cast<EmptyNodeType *>(&empty_node));
- return const_cast<EmptyNodeType *>(&empty_node);
-#endif
- }
-
- enum : uint32_t {
- kNodeSlots = node_type::kNodeSlots,
- kMinNodeValues = kNodeSlots / 2,
- };
-
- struct node_stats {
- using size_type = typename Params::size_type;
-
- node_stats(size_type l, size_type i) : leaf_nodes(l), internal_nodes(i) {}
-
- node_stats &operator+=(const node_stats &other) {
- leaf_nodes += other.leaf_nodes;
- internal_nodes += other.internal_nodes;
- return *this;
- }
-
- size_type leaf_nodes;
- size_type internal_nodes;
- };
-
- public:
- using key_type = typename Params::key_type;
- using value_type = typename Params::value_type;
- using size_type = typename Params::size_type;
- using difference_type = typename Params::difference_type;
- using key_compare = typename Params::key_compare;
- using original_key_compare = typename Params::original_key_compare;
- using value_compare = typename Params::value_compare;
- using allocator_type = typename Params::allocator_type;
- using reference = typename Params::reference;
- using const_reference = typename Params::const_reference;
- using pointer = typename Params::pointer;
- using const_pointer = typename Params::const_pointer;
- using iterator =
- typename btree_iterator<node_type, reference, pointer>::iterator;
- using const_iterator = typename iterator::const_iterator;
- using reverse_iterator = std::reverse_iterator<iterator>;
- using const_reverse_iterator = std::reverse_iterator<const_iterator>;
- using node_handle_type = node_handle<Params, Params, allocator_type>;
-
- // Internal types made public for use by btree_container types.
- using params_type = Params;
- using slot_type = typename Params::slot_type;
-
- private:
- // Copies or moves (depending on the template parameter) the values in
- // other into this btree in their order in other. This btree must be empty
- // before this method is called. This method is used in copy construction,
- // copy assignment, and move assignment.
- template <typename Btree>
- void copy_or_move_values_in_order(Btree &other);
-
- // Validates that various assumptions/requirements are true at compile time.
- constexpr static bool static_assert_validation();
-
- public:
- btree(const key_compare &comp, const allocator_type &alloc)
- : root_(EmptyNode()), rightmost_(comp, alloc, EmptyNode()), size_(0) {}
-
- btree(const btree &other) : btree(other, other.allocator()) {}
- btree(const btree &other, const allocator_type &alloc)
- : btree(other.key_comp(), alloc) {
- copy_or_move_values_in_order(other);
- }
- btree(btree &&other) noexcept
- : root_(absl::exchange(other.root_, EmptyNode())),
- rightmost_(std::move(other.rightmost_)),
- size_(absl::exchange(other.size_, 0u)) {
- other.mutable_rightmost() = EmptyNode();
- }
- btree(btree &&other, const allocator_type &alloc)
- : btree(other.key_comp(), alloc) {
- if (alloc == other.allocator()) {
- swap(other);
- } else {
- // Move values from `other` one at a time when allocators are different.
- copy_or_move_values_in_order(other);
- }
- }
-
- ~btree() {
- // Put static_asserts in destructor to avoid triggering them before the type
- // is complete.
- static_assert(static_assert_validation(), "This call must be elided.");
- clear();
- }
-
- // Assign the contents of other to *this.
- btree &operator=(const btree &other);
- btree &operator=(btree &&other) noexcept;
-
- iterator begin() { return iterator(leftmost()); }
- const_iterator begin() const { return const_iterator(leftmost()); }
- iterator end() { return iterator(rightmost(), rightmost()->finish()); }
- const_iterator end() const {
- return const_iterator(rightmost(), rightmost()->finish());
- }
- reverse_iterator rbegin() { return reverse_iterator(end()); }
- const_reverse_iterator rbegin() const {
- return const_reverse_iterator(end());
- }
- reverse_iterator rend() { return reverse_iterator(begin()); }
- const_reverse_iterator rend() const {
- return const_reverse_iterator(begin());
- }
-
- // Finds the first element whose key is not less than `key`.
- template <typename K>
- iterator lower_bound(const K &key) {
- return internal_end(internal_lower_bound(key).value);
- }
- template <typename K>
- const_iterator lower_bound(const K &key) const {
- return internal_end(internal_lower_bound(key).value);
- }
-
- // Finds the first element whose key is not less than `key` and also returns
- // whether that element is equal to `key`.
- template <typename K>
- std::pair<iterator, bool> lower_bound_equal(const K &key) const;
-
- // Finds the first element whose key is greater than `key`.
- template <typename K>
- iterator upper_bound(const K &key) {
- return internal_end(internal_upper_bound(key));
- }
- template <typename K>
- const_iterator upper_bound(const K &key) const {
- return internal_end(internal_upper_bound(key));
- }
-
- // Finds the range of values which compare equal to key. The first member of
- // the returned pair is equal to lower_bound(key). The second member of the
- // pair is equal to upper_bound(key).
- template <typename K>
- std::pair<iterator, iterator> equal_range(const K &key);
- template <typename K>
- std::pair<const_iterator, const_iterator> equal_range(const K &key) const {
- return const_cast<btree *>(this)->equal_range(key);
- }
-
- // Inserts a value into the btree only if it does not already exist. The
- // boolean return value indicates whether insertion succeeded or failed.
- // Requirement: if `key` already exists in the btree, does not consume `args`.
- // Requirement: `key` is never referenced after consuming `args`.
- template <typename K, typename... Args>
- std::pair<iterator, bool> insert_unique(const K &key, Args &&...args);
-
- // Inserts with hint. Checks to see if the value should be placed immediately
- // before `position` in the tree. If so, then the insertion will take
- // amortized constant time. If not, the insertion will take amortized
- // logarithmic time as if a call to insert_unique() were made.
- // Requirement: if `key` already exists in the btree, does not consume `args`.
- // Requirement: `key` is never referenced after consuming `args`.
- template <typename K, typename... Args>
- std::pair<iterator, bool> insert_hint_unique(iterator position, const K &key,
- Args &&...args);
-
- // Insert a range of values into the btree.
- // Note: the first overload avoids constructing a value_type if the key
- // already exists in the btree.
- template <typename InputIterator,
- typename = decltype(std::declval<const key_compare &>()(
- params_type::key(*std::declval<InputIterator>()),
- std::declval<const key_type &>()))>
- void insert_iterator_unique(InputIterator b, InputIterator e, int);
- // We need the second overload for cases in which we need to construct a
- // value_type in order to compare it with the keys already in the btree.
- template <typename InputIterator>
- void insert_iterator_unique(InputIterator b, InputIterator e, char);
-
- // Inserts a value into the btree.
- template <typename ValueType>
- iterator insert_multi(const key_type &key, ValueType &&v);
-
- // Inserts a value into the btree.
- template <typename ValueType>
- iterator insert_multi(ValueType &&v) {
- return insert_multi(params_type::key(v), std::forward<ValueType>(v));
- }
-
- // Insert with hint. Check to see if the value should be placed immediately
- // before position in the tree. If it does, then the insertion will take
- // amortized constant time. If not, the insertion will take amortized
- // logarithmic time as if a call to insert_multi(v) were made.
- template <typename ValueType>
- iterator insert_hint_multi(iterator position, ValueType &&v);
-
- // Insert a range of values into the btree.
- template <typename InputIterator>
- void insert_iterator_multi(InputIterator b, InputIterator e);
-
- // Erase the specified iterator from the btree. The iterator must be valid
- // (i.e. not equal to end()). Return an iterator pointing to the node after
- // the one that was erased (or end() if none exists).
- // Requirement: does not read the value at `*iter`.
- iterator erase(iterator iter);
-
- // Erases range. Returns the number of keys erased and an iterator pointing
- // to the element after the last erased element.
- std::pair<size_type, iterator> erase_range(iterator begin, iterator end);
-
- // Finds an element with key equivalent to `key` or returns `end()` if `key`
- // is not present.
- template <typename K>
- iterator find(const K &key) {
- return internal_end(internal_find(key));
- }
- template <typename K>
- const_iterator find(const K &key) const {
- return internal_end(internal_find(key));
- }
-
- // Clear the btree, deleting all of the values it contains.
- void clear();
-
- // Swaps the contents of `this` and `other`.
- void swap(btree &other);
-
- const key_compare &key_comp() const noexcept {
- return rightmost_.template get<0>();
- }
- template <typename K1, typename K2>
- bool compare_keys(const K1 &a, const K2 &b) const {
- return compare_internal::compare_result_as_less_than(key_comp()(a, b));
- }
-
- value_compare value_comp() const {
- return value_compare(original_key_compare(key_comp()));
- }
-
- // Verifies the structure of the btree.
- void verify() const;
-
- // Size routines.
- size_type size() const { return size_; }
- size_type max_size() const { return (std::numeric_limits<size_type>::max)(); }
- bool empty() const { return size_ == 0; }
-
- // The height of the btree. An empty tree will have height 0.
- size_type height() const {
- size_type h = 0;
- if (!empty()) {
- // Count the length of the chain from the leftmost node up to the
- // root. We actually count from the root back around to the level below
- // the root, but the calculation is the same because of the circularity
- // of that traversal.
- const node_type *n = root();
- do {
- ++h;
- n = n->parent();
- } while (n != root());
- }
- return h;
- }
-
- // The number of internal, leaf and total nodes used by the btree.
- size_type leaf_nodes() const { return internal_stats(root()).leaf_nodes; }
- size_type internal_nodes() const {
- return internal_stats(root()).internal_nodes;
- }
- size_type nodes() const {
- node_stats stats = internal_stats(root());
- return stats.leaf_nodes + stats.internal_nodes;
- }
-
- // The total number of bytes used by the btree.
- // TODO(b/169338300): update to support node_btree_*.
- size_type bytes_used() const {
- node_stats stats = internal_stats(root());
- if (stats.leaf_nodes == 1 && stats.internal_nodes == 0) {
- return sizeof(*this) + node_type::LeafSize(root()->max_count());
- } else {
- return sizeof(*this) + stats.leaf_nodes * node_type::LeafSize() +
- stats.internal_nodes * node_type::InternalSize();
- }
- }
-
- // The average number of bytes used per value stored in the btree assuming
- // random insertion order.
- static double average_bytes_per_value() {
- // The expected number of values per node with random insertion order is the
- // average of the maximum and minimum numbers of values per node.
- const double expected_values_per_node = (kNodeSlots + kMinNodeValues) / 2.0;
- return node_type::LeafSize() / expected_values_per_node;
- }
-
- // The fullness of the btree. Computed as the number of elements in the btree
- // divided by the maximum number of elements a tree with the current number
- // of nodes could hold. A value of 1 indicates perfect space
- // utilization. Smaller values indicate space wastage.
- // Returns 0 for empty trees.
- double fullness() const {
- if (empty()) return 0.0;
- return static_cast<double>(size()) / (nodes() * kNodeSlots);
- }
- // The overhead of the btree structure in bytes per node. Computed as the
- // total number of bytes used by the btree minus the number of bytes used for
- // storing elements divided by the number of elements.
- // Returns 0 for empty trees.
- double overhead() const {
- if (empty()) return 0.0;
- return (bytes_used() - size() * sizeof(value_type)) /
- static_cast<double>(size());
- }
-
- // The allocator used by the btree.
- allocator_type get_allocator() const { return allocator(); }
-
- private:
- friend struct btree_access;
-
- // Internal accessor routines.
- node_type *root() { return root_; }
- const node_type *root() const { return root_; }
- node_type *&mutable_root() noexcept { return root_; }
- node_type *rightmost() { return rightmost_.template get<2>(); }
- const node_type *rightmost() const { return rightmost_.template get<2>(); }
- node_type *&mutable_rightmost() noexcept {
- return rightmost_.template get<2>();
- }
- key_compare *mutable_key_comp() noexcept {
- return &rightmost_.template get<0>();
- }
-
- // The leftmost node is stored as the parent of the root node.
- node_type *leftmost() { return root()->parent(); }
- const node_type *leftmost() const { return root()->parent(); }
-
- // Allocator routines.
- allocator_type *mutable_allocator() noexcept {
- return &rightmost_.template get<1>();
- }
- const allocator_type &allocator() const noexcept {
- return rightmost_.template get<1>();
- }
-
- // Allocates a correctly aligned node of at least size bytes using the
- // allocator.
- node_type *allocate(size_type size) {
- return reinterpret_cast<node_type *>(
- absl::container_internal::Allocate<node_type::Alignment()>(
- mutable_allocator(), size));
- }
-
- // Node creation/deletion routines.
- node_type *new_internal_node(node_type *parent) {
- node_type *n = allocate(node_type::InternalSize());
- n->init_internal(parent);
- return n;
- }
- node_type *new_leaf_node(node_type *parent) {
- node_type *n = allocate(node_type::LeafSize());
- n->init_leaf(kNodeSlots, parent);
- return n;
- }
- node_type *new_leaf_root_node(field_type max_count) {
- node_type *n = allocate(node_type::LeafSize(max_count));
- n->init_leaf(max_count, /*parent=*/n);
- return n;
- }
-
- // Deletion helper routines.
- iterator rebalance_after_delete(iterator iter);
-
- // Rebalances or splits the node iter points to.
- void rebalance_or_split(iterator *iter);
-
- // Merges the values of left, right and the delimiting key on their parent
- // onto left, removing the delimiting key and deleting right.
- void merge_nodes(node_type *left, node_type *right);
-
- // Tries to merge node with its left or right sibling, and failing that,
- // rebalance with its left or right sibling. Returns true if a merge
- // occurred, at which point it is no longer valid to access node. Returns
- // false if no merging took place.
- bool try_merge_or_rebalance(iterator *iter);
-
- // Tries to shrink the height of the tree by 1.
- void try_shrink();
-
- iterator internal_end(iterator iter) {
- return iter.node_ != nullptr ? iter : end();
- }
- const_iterator internal_end(const_iterator iter) const {
- return iter.node_ != nullptr ? iter : end();
- }
-
- // Emplaces a value into the btree immediately before iter. Requires that
- // key(v) <= iter.key() and (--iter).key() <= key(v).
- template <typename... Args>
- iterator internal_emplace(iterator iter, Args &&...args);
-
- // Returns an iterator pointing to the first value >= the value "iter" is
- // pointing at. Note that "iter" might be pointing to an invalid location such
- // as iter.position_ == iter.node_->finish(). This routine simply moves iter
- // up in the tree to a valid location. Requires: iter.node_ is non-null.
- template <typename IterType>
- static IterType internal_last(IterType iter);
-
- // Returns an iterator pointing to the leaf position at which key would
- // reside in the tree, unless there is an exact match - in which case, the
- // result may not be on a leaf. When there's a three-way comparator, we can
- // return whether there was an exact match. This allows the caller to avoid a
- // subsequent comparison to determine if an exact match was made, which is
- // important for keys with expensive comparison, such as strings.
- template <typename K>
- SearchResult<iterator, is_key_compare_to::value> internal_locate(
- const K &key) const;
-
- // Internal routine which implements lower_bound().
- template <typename K>
- SearchResult<iterator, is_key_compare_to::value> internal_lower_bound(
- const K &key) const;
-
- // Internal routine which implements upper_bound().
- template <typename K>
- iterator internal_upper_bound(const K &key) const;
-
- // Internal routine which implements find().
- template <typename K>
- iterator internal_find(const K &key) const;
-
- // Verifies the tree structure of node.
- size_type internal_verify(const node_type *node, const key_type *lo,
- const key_type *hi) const;
-
- node_stats internal_stats(const node_type *node) const {
- // The root can be a static empty node.
- if (node == nullptr || (node == root() && empty())) {
- return node_stats(0, 0);
- }
- if (node->is_leaf()) {
- return node_stats(1, 0);
- }
- node_stats res(0, 1);
- for (int i = node->start(); i <= node->finish(); ++i) {
- res += internal_stats(node->child(i));
- }
- return res;
- }
-
- node_type *root_;
-
- // A pointer to the rightmost node. Note that the leftmost node is stored as
- // the root's parent. We use compressed tuple in order to save space because
- // key_compare and allocator_type are usually empty.
- absl::container_internal::CompressedTuple<key_compare, allocator_type,
- node_type *>
- rightmost_;
-
- // Number of values.
- size_type size_;
-};
-
-////
-// btree_node methods
-template <typename P>
-template <typename... Args>
-inline void btree_node<P>::emplace_value(const field_type i,
- allocator_type *alloc,
- Args &&...args) {
- assert(i >= start());
- assert(i <= finish());
- // Shift old values to create space for new value and then construct it in
- // place.
- if (i < finish()) {
- transfer_n_backward(finish() - i, /*dest_i=*/i + 1, /*src_i=*/i, this,
- alloc);
- }
- value_init(static_cast<field_type>(i), alloc, std::forward<Args>(args)...);
- set_finish(finish() + 1);
-
- if (is_internal() && finish() > i + 1) {
- for (field_type j = finish(); j > i + 1; --j) {
- set_child(j, child(j - 1));
- }
- clear_child(i + 1);
- }
-}
-
-template <typename P>
-inline void btree_node<P>::remove_values(const field_type i,
- const field_type to_erase,
- allocator_type *alloc) {
- // Transfer values after the removed range into their new places.
- value_destroy_n(i, to_erase, alloc);
- const field_type orig_finish = finish();
- const field_type src_i = i + to_erase;
- transfer_n(orig_finish - src_i, i, src_i, this, alloc);
-
- if (is_internal()) {
- // Delete all children between begin and end.
- for (field_type j = 0; j < to_erase; ++j) {
- clear_and_delete(child(i + j + 1), alloc);
- }
- // Rotate children after end into new positions.
- for (field_type j = i + to_erase + 1; j <= orig_finish; ++j) {
- set_child(j - to_erase, child(j));
- clear_child(j);
- }
- }
- set_finish(orig_finish - to_erase);
-}
-
-template <typename P>
-void btree_node<P>::rebalance_right_to_left(field_type to_move,
- btree_node *right,
- allocator_type *alloc) {
- assert(parent() == right->parent());
- assert(position() + 1 == right->position());
- assert(right->count() >= count());
- assert(to_move >= 1);
- assert(to_move <= right->count());
-
- // 1) Move the delimiting value in the parent to the left node.
- transfer(finish(), position(), parent(), alloc);
-
- // 2) Move the (to_move - 1) values from the right node to the left node.
- transfer_n(to_move - 1, finish() + 1, right->start(), right, alloc);
-
- // 3) Move the new delimiting value to the parent from the right node.
- parent()->transfer(position(), right->start() + to_move - 1, right, alloc);
-
- // 4) Shift the values in the right node to their correct positions.
- right->transfer_n(right->count() - to_move, right->start(),
- right->start() + to_move, right, alloc);
-
- if (is_internal()) {
- // Move the child pointers from the right to the left node.
- for (field_type i = 0; i < to_move; ++i) {
- init_child(finish() + i + 1, right->child(i));
- }
- for (field_type i = right->start(); i <= right->finish() - to_move; ++i) {
- assert(i + to_move <= right->max_count());
- right->init_child(i, right->child(i + to_move));
- right->clear_child(i + to_move);
- }
- }
-
- // Fixup `finish` on the left and right nodes.
- set_finish(finish() + to_move);
- right->set_finish(right->finish() - to_move);
-}
-
-template <typename P>
-void btree_node<P>::rebalance_left_to_right(field_type to_move,
- btree_node *right,
- allocator_type *alloc) {
- assert(parent() == right->parent());
- assert(position() + 1 == right->position());
- assert(count() >= right->count());
- assert(to_move >= 1);
- assert(to_move <= count());
-
- // Values in the right node are shifted to the right to make room for the
- // new to_move values. Then, the delimiting value in the parent and the
- // other (to_move - 1) values in the left node are moved into the right node.
- // Lastly, a new delimiting value is moved from the left node into the
- // parent, and the remaining empty left node entries are destroyed.
-
- // 1) Shift existing values in the right node to their correct positions.
- right->transfer_n_backward(right->count(), right->start() + to_move,
- right->start(), right, alloc);
-
- // 2) Move the delimiting value in the parent to the right node.
- right->transfer(right->start() + to_move - 1, position(), parent(), alloc);
-
- // 3) Move the (to_move - 1) values from the left node to the right node.
- right->transfer_n(to_move - 1, right->start(), finish() - (to_move - 1), this,
- alloc);
-
- // 4) Move the new delimiting value to the parent from the left node.
- parent()->transfer(position(), finish() - to_move, this, alloc);
-
- if (is_internal()) {
- // Move the child pointers from the left to the right node.
- for (field_type i = right->finish() + 1; i > right->start(); --i) {
- right->init_child(i - 1 + to_move, right->child(i - 1));
- right->clear_child(i - 1);
- }
- for (field_type i = 1; i <= to_move; ++i) {
- right->init_child(i - 1, child(finish() - to_move + i));
- clear_child(finish() - to_move + i);
- }
- }
-
- // Fixup the counts on the left and right nodes.
- set_finish(finish() - to_move);
- right->set_finish(right->finish() + to_move);
-}
-
-template <typename P>
-void btree_node<P>::split(const int insert_position, btree_node *dest,
- allocator_type *alloc) {
- assert(dest->count() == 0);
- assert(max_count() == kNodeSlots);
-
- // We bias the split based on the position being inserted. If we're
- // inserting at the beginning of the left node then bias the split to put
- // more values on the right node. If we're inserting at the end of the
- // right node then bias the split to put more values on the left node.
- if (insert_position == start()) {
- dest->set_finish(dest->start() + finish() - 1);
- } else if (insert_position == kNodeSlots) {
- dest->set_finish(dest->start());
- } else {
- dest->set_finish(dest->start() + count() / 2);
- }
- set_finish(finish() - dest->count());
- assert(count() >= 1);
-
- // Move values from the left sibling to the right sibling.
- dest->transfer_n(dest->count(), dest->start(), finish(), this, alloc);
-
- // The split key is the largest value in the left sibling.
- --mutable_finish();
- parent()->emplace_value(position(), alloc, finish_slot());
- value_destroy(finish(), alloc);
- parent()->init_child(position() + 1, dest);
-
- if (is_internal()) {
- for (field_type i = dest->start(), j = finish() + 1; i <= dest->finish();
- ++i, ++j) {
- assert(child(j) != nullptr);
- dest->init_child(i, child(j));
- clear_child(j);
- }
- }
-}
-
-template <typename P>
-void btree_node<P>::merge(btree_node *src, allocator_type *alloc) {
- assert(parent() == src->parent());
- assert(position() + 1 == src->position());
-
- // Move the delimiting value to the left node.
- value_init(finish(), alloc, parent()->slot(position()));
-
- // Move the values from the right to the left node.
- transfer_n(src->count(), finish() + 1, src->start(), src, alloc);
-
- if (is_internal()) {
- // Move the child pointers from the right to the left node.
- for (field_type i = src->start(), j = finish() + 1; i <= src->finish();
- ++i, ++j) {
- init_child(j, src->child(i));
- src->clear_child(i);
- }
- }
-
- // Fixup `finish` on the src and dest nodes.
- set_finish(start() + 1 + count() + src->count());
- src->set_finish(src->start());
-
- // Remove the value on the parent node and delete the src node.
- parent()->remove_values(position(), /*to_erase=*/1, alloc);
-}
-
-template <typename P>
-void btree_node<P>::clear_and_delete(btree_node *node, allocator_type *alloc) {
- if (node->is_leaf()) {
- node->value_destroy_n(node->start(), node->count(), alloc);
- deallocate(LeafSize(node->max_count()), node, alloc);
- return;
- }
- if (node->count() == 0) {
- deallocate(InternalSize(), node, alloc);
- return;
- }
-
- // The parent of the root of the subtree we are deleting.
- btree_node *delete_root_parent = node->parent();
-
- // Navigate to the leftmost leaf under node, and then delete upwards.
- while (node->is_internal()) node = node->start_child();
-#ifdef ABSL_BTREE_ENABLE_GENERATIONS
- // When generations are enabled, we delete the leftmost leaf last in case it's
- // the parent of the root and we need to check whether it's a leaf before we
- // can update the root's generation.
- // TODO(ezb): if we change btree_node::is_root to check a bool inside the node
- // instead of checking whether the parent is a leaf, we can remove this logic.
- btree_node *leftmost_leaf = node;
-#endif
- // Use `size_type` because `pos` needs to be able to hold `kNodeSlots+1`,
- // which isn't guaranteed to be a valid `field_type`.
- size_type pos = node->position();
- btree_node *parent = node->parent();
- for (;;) {
- // In each iteration of the next loop, we delete one leaf node and go right.
- assert(pos <= parent->finish());
- do {
- node = parent->child(static_cast<field_type>(pos));
- if (node->is_internal()) {
- // Navigate to the leftmost leaf under node.
- while (node->is_internal()) node = node->start_child();
- pos = node->position();
- parent = node->parent();
- }
- node->value_destroy_n(node->start(), node->count(), alloc);
-#ifdef ABSL_BTREE_ENABLE_GENERATIONS
- if (leftmost_leaf != node)
-#endif
- deallocate(LeafSize(node->max_count()), node, alloc);
- ++pos;
- } while (pos <= parent->finish());
-
- // Once we've deleted all children of parent, delete parent and go up/right.
- assert(pos > parent->finish());
- do {
- node = parent;
- pos = node->position();
- parent = node->parent();
- node->value_destroy_n(node->start(), node->count(), alloc);
- deallocate(InternalSize(), node, alloc);
- if (parent == delete_root_parent) {
-#ifdef ABSL_BTREE_ENABLE_GENERATIONS
- deallocate(LeafSize(leftmost_leaf->max_count()), leftmost_leaf, alloc);
-#endif
- return;
- }
- ++pos;
- } while (pos > parent->finish());
- }
-}
-
-////
-// btree_iterator methods
-
-// Note: the implementation here is based on btree_node::clear_and_delete.
-template <typename N, typename R, typename P>
-auto btree_iterator<N, R, P>::distance_slow(const_iterator other) const
- -> difference_type {
- const_iterator begin = other;
- const_iterator end = *this;
- assert(begin.node_ != end.node_ || !begin.node_->is_leaf() ||
- begin.position_ != end.position_);
-
- const node_type *node = begin.node_;
- // We need to compensate for double counting if begin.node_ is a leaf node.
- difference_type count = node->is_leaf() ? -begin.position_ : 0;
-
- // First navigate to the leftmost leaf node past begin.
- if (node->is_internal()) {
- ++count;
- node = node->child(begin.position_ + 1);
- }
- while (node->is_internal()) node = node->start_child();
-
- // Use `size_type` because `pos` needs to be able to hold `kNodeSlots+1`,
- // which isn't guaranteed to be a valid `field_type`.
- size_type pos = node->position();
- const node_type *parent = node->parent();
- for (;;) {
- // In each iteration of the next loop, we count one leaf node and go right.
- assert(pos <= parent->finish());
- do {
- node = parent->child(static_cast<field_type>(pos));
- if (node->is_internal()) {
- // Navigate to the leftmost leaf under node.
- while (node->is_internal()) node = node->start_child();
- pos = node->position();
- parent = node->parent();
- }
- if (node == end.node_) return count + end.position_;
- if (parent == end.node_ && pos == static_cast<size_type>(end.position_))
- return count + node->count();
- // +1 is for the next internal node value.
- count += node->count() + 1;
- ++pos;
- } while (pos <= parent->finish());
-
- // Once we've counted all children of parent, go up/right.
- assert(pos > parent->finish());
- do {
- node = parent;
- pos = node->position();
- parent = node->parent();
- // -1 because we counted the value at end and shouldn't.
- if (parent == end.node_ && pos == static_cast<size_type>(end.position_))
- return count - 1;
- ++pos;
- } while (pos > parent->finish());
- }
-}
-
-template <typename N, typename R, typename P>
-void btree_iterator<N, R, P>::increment_slow() {
- if (node_->is_leaf()) {
- assert(position_ >= node_->finish());
- btree_iterator save(*this);
- while (position_ == node_->finish() && !node_->is_root()) {
- assert(node_->parent()->child(node_->position()) == node_);
- position_ = node_->position();
- node_ = node_->parent();
- }
- // TODO(ezb): assert we aren't incrementing end() instead of handling.
- if (position_ == node_->finish()) {
- *this = save;
- }
- } else {
- assert(position_ < node_->finish());
- node_ = node_->child(static_cast<field_type>(position_ + 1));
- while (node_->is_internal()) {
- node_ = node_->start_child();
- }
- position_ = node_->start();
- }
-}
-
-template <typename N, typename R, typename P>
-void btree_iterator<N, R, P>::decrement_slow() {
- if (node_->is_leaf()) {
- assert(position_ <= -1);
- btree_iterator save(*this);
- while (position_ < node_->start() && !node_->is_root()) {
- assert(node_->parent()->child(node_->position()) == node_);
- position_ = node_->position() - 1;
- node_ = node_->parent();
- }
- // TODO(ezb): assert we aren't decrementing begin() instead of handling.
- if (position_ < node_->start()) {
- *this = save;
- }
- } else {
- assert(position_ >= node_->start());
- node_ = node_->child(static_cast<field_type>(position_));
- while (node_->is_internal()) {
- node_ = node_->child(node_->finish());
- }
- position_ = node_->finish() - 1;
- }
-}
-
-////
-// btree methods
-template <typename P>
-template <typename Btree>
-void btree<P>::copy_or_move_values_in_order(Btree &other) {
- static_assert(std::is_same<btree, Btree>::value ||
- std::is_same<const btree, Btree>::value,
- "Btree type must be same or const.");
- assert(empty());
-
- // We can avoid key comparisons because we know the order of the
- // values is the same order we'll store them in.
- auto iter = other.begin();
- if (iter == other.end()) return;
- insert_multi(iter.slot());
- ++iter;
- for (; iter != other.end(); ++iter) {
- // If the btree is not empty, we can just insert the new value at the end
- // of the tree.
- internal_emplace(end(), iter.slot());
- }
-}
-
-template <typename P>
-constexpr bool btree<P>::static_assert_validation() {
- static_assert(std::is_nothrow_copy_constructible<key_compare>::value,
- "Key comparison must be nothrow copy constructible");
- static_assert(std::is_nothrow_copy_constructible<allocator_type>::value,
- "Allocator must be nothrow copy constructible");
- static_assert(type_traits_internal::is_trivially_copyable<iterator>::value,
- "iterator not trivially copyable.");
-
- // Note: We assert that kTargetValues, which is computed from
- // Params::kTargetNodeSize, must fit the node_type::field_type.
- static_assert(
- kNodeSlots < (1 << (8 * sizeof(typename node_type::field_type))),
- "target node size too large");
-
- // Verify that key_compare returns an absl::{weak,strong}_ordering or bool.
- static_assert(
- compare_has_valid_result_type<key_compare, key_type>(),
- "key comparison function must return absl::{weak,strong}_ordering or "
- "bool.");
-
- // Test the assumption made in setting kNodeSlotSpace.
- static_assert(node_type::MinimumOverhead() >= sizeof(void *) + 4,
- "node space assumption incorrect");
-
- return true;
-}
-
-template <typename P>
-template <typename K>
-auto btree<P>::lower_bound_equal(const K &key) const
- -> std::pair<iterator, bool> {
- const SearchResult<iterator, is_key_compare_to::value> res =
- internal_lower_bound(key);
- const iterator lower = iterator(internal_end(res.value));
- const bool equal = res.HasMatch()
- ? res.IsEq()
- : lower != end() && !compare_keys(key, lower.key());
- return {lower, equal};
-}
-
-template <typename P>
-template <typename K>
-auto btree<P>::equal_range(const K &key) -> std::pair<iterator, iterator> {
- const std::pair<iterator, bool> lower_and_equal = lower_bound_equal(key);
- const iterator lower = lower_and_equal.first;
- if (!lower_and_equal.second) {
- return {lower, lower};
- }
-
- const iterator next = std::next(lower);
- if (!params_type::template can_have_multiple_equivalent_keys<K>()) {
- // The next iterator after lower must point to a key greater than `key`.
- // Note: if this assert fails, then it may indicate that the comparator does
- // not meet the equivalence requirements for Compare
- // (see https://en.cppreference.com/w/cpp/named_req/Compare).
- assert(next == end() || compare_keys(key, next.key()));
- return {lower, next};
- }
- // Try once more to avoid the call to upper_bound() if there's only one
- // equivalent key. This should prevent all calls to upper_bound() in cases of
- // unique-containers with heterogeneous comparators in which all comparison
- // operators have the same equivalence classes.
- if (next == end() || compare_keys(key, next.key())) return {lower, next};
-
- // In this case, we need to call upper_bound() to avoid worst case O(N)
- // behavior if we were to iterate over equal keys.
- return {lower, upper_bound(key)};
-}
-
-template <typename P>
-template <typename K, typename... Args>
-auto btree<P>::insert_unique(const K &key, Args &&...args)
- -> std::pair<iterator, bool> {
- if (empty()) {
- mutable_root() = mutable_rightmost() = new_leaf_root_node(1);
- }
-
- SearchResult<iterator, is_key_compare_to::value> res = internal_locate(key);
- iterator iter = res.value;
-
- if (res.HasMatch()) {
- if (res.IsEq()) {
- // The key already exists in the tree, do nothing.
- return {iter, false};
- }
- } else {
- iterator last = internal_last(iter);
- if (last.node_ && !compare_keys(key, last.key())) {
- // The key already exists in the tree, do nothing.
- return {last, false};
- }
- }
- return {internal_emplace(iter, std::forward<Args>(args)...), true};
-}
-
-template <typename P>
-template <typename K, typename... Args>
-inline auto btree<P>::insert_hint_unique(iterator position, const K &key,
- Args &&...args)
- -> std::pair<iterator, bool> {
- if (!empty()) {
- if (position == end() || compare_keys(key, position.key())) {
- if (position == begin() || compare_keys(std::prev(position).key(), key)) {
- // prev.key() < key < position.key()
- return {internal_emplace(position, std::forward<Args>(args)...), true};
- }
- } else if (compare_keys(position.key(), key)) {
- ++position;
- if (position == end() || compare_keys(key, position.key())) {
- // {original `position`}.key() < key < {current `position`}.key()
- return {internal_emplace(position, std::forward<Args>(args)...), true};
- }
- } else {
- // position.key() == key
- return {position, false};
- }
- }
- return insert_unique(key, std::forward<Args>(args)...);
-}
-
-template <typename P>
-template <typename InputIterator, typename>
-void btree<P>::insert_iterator_unique(InputIterator b, InputIterator e, int) {
- for (; b != e; ++b) {
- insert_hint_unique(end(), params_type::key(*b), *b);
- }
-}
-
-template <typename P>
-template <typename InputIterator>
-void btree<P>::insert_iterator_unique(InputIterator b, InputIterator e, char) {
- for (; b != e; ++b) {
- // Use a node handle to manage a temp slot.
- auto node_handle =
- CommonAccess::Construct<node_handle_type>(get_allocator(), *b);
- slot_type *slot = CommonAccess::GetSlot(node_handle);
- insert_hint_unique(end(), params_type::key(slot), slot);
- }
-}
-
-template <typename P>
-template <typename ValueType>
-auto btree<P>::insert_multi(const key_type &key, ValueType &&v) -> iterator {
- if (empty()) {
- mutable_root() = mutable_rightmost() = new_leaf_root_node(1);
- }
-
- iterator iter = internal_upper_bound(key);
- if (iter.node_ == nullptr) {
- iter = end();
- }
- return internal_emplace(iter, std::forward<ValueType>(v));
-}
-
-template <typename P>
-template <typename ValueType>
-auto btree<P>::insert_hint_multi(iterator position, ValueType &&v) -> iterator {
- if (!empty()) {
- const key_type &key = params_type::key(v);
- if (position == end() || !compare_keys(position.key(), key)) {
- if (position == begin() ||
- !compare_keys(key, std::prev(position).key())) {
- // prev.key() <= key <= position.key()
- return internal_emplace(position, std::forward<ValueType>(v));
- }
- } else {
- ++position;
- if (position == end() || !compare_keys(position.key(), key)) {
- // {original `position`}.key() < key < {current `position`}.key()
- return internal_emplace(position, std::forward<ValueType>(v));
- }
- }
- }
- return insert_multi(std::forward<ValueType>(v));
-}
-
-template <typename P>
-template <typename InputIterator>
-void btree<P>::insert_iterator_multi(InputIterator b, InputIterator e) {
- for (; b != e; ++b) {
- insert_hint_multi(end(), *b);
- }
-}
-
-template <typename P>
-auto btree<P>::operator=(const btree &other) -> btree & {
- if (this != &other) {
- clear();
-
- *mutable_key_comp() = other.key_comp();
- if (absl::allocator_traits<
- allocator_type>::propagate_on_container_copy_assignment::value) {
- *mutable_allocator() = other.allocator();
- }
-
- copy_or_move_values_in_order(other);
- }
- return *this;
-}
-
-template <typename P>
-auto btree<P>::operator=(btree &&other) noexcept -> btree & {
- if (this != &other) {
- clear();
-
- using std::swap;
- if (absl::allocator_traits<
- allocator_type>::propagate_on_container_copy_assignment::value) {
- swap(root_, other.root_);
- // Note: `rightmost_` also contains the allocator and the key comparator.
- swap(rightmost_, other.rightmost_);
- swap(size_, other.size_);
- } else {
- if (allocator() == other.allocator()) {
- swap(mutable_root(), other.mutable_root());
- swap(*mutable_key_comp(), *other.mutable_key_comp());
- swap(mutable_rightmost(), other.mutable_rightmost());
- swap(size_, other.size_);
- } else {
- // We aren't allowed to propagate the allocator and the allocator is
- // different so we can't take over its memory. We must move each element
- // individually. We need both `other` and `this` to have `other`s key
- // comparator while moving the values so we can't swap the key
- // comparators.
- *mutable_key_comp() = other.key_comp();
- copy_or_move_values_in_order(other);
- }
- }
- }
- return *this;
-}
-
-template <typename P>
-auto btree<P>::erase(iterator iter) -> iterator {
- iter.node_->value_destroy(static_cast<field_type>(iter.position_),
- mutable_allocator());
- iter.update_generation();
-
- const bool internal_delete = iter.node_->is_internal();
- if (internal_delete) {
- // Deletion of a value on an internal node. First, transfer the largest
- // value from our left child here, then erase/rebalance from that position.
- // We can get to the largest value from our left child by decrementing iter.
- iterator internal_iter(iter);
- --iter;
- assert(iter.node_->is_leaf());
- internal_iter.node_->transfer(
- static_cast<size_type>(internal_iter.position_),
- static_cast<size_type>(iter.position_), iter.node_,
- mutable_allocator());
- } else {
- // Shift values after erased position in leaf. In the internal case, we
- // don't need to do this because the leaf position is the end of the node.
- const field_type transfer_from =
- static_cast<field_type>(iter.position_ + 1);
- const field_type num_to_transfer = iter.node_->finish() - transfer_from;
- iter.node_->transfer_n(num_to_transfer,
- static_cast<size_type>(iter.position_),
- transfer_from, iter.node_, mutable_allocator());
- }
- // Update node finish and container size.
- iter.node_->set_finish(iter.node_->finish() - 1);
- --size_;
-
- // We want to return the next value after the one we just erased. If we
- // erased from an internal node (internal_delete == true), then the next
- // value is ++(++iter). If we erased from a leaf node (internal_delete ==
- // false) then the next value is ++iter. Note that ++iter may point to an
- // internal node and the value in the internal node may move to a leaf node
- // (iter.node_) when rebalancing is performed at the leaf level.
-
- iterator res = rebalance_after_delete(iter);
-
- // If we erased from an internal node, advance the iterator.
- if (internal_delete) {
- ++res;
- }
- return res;
-}
-
-template <typename P>
-auto btree<P>::rebalance_after_delete(iterator iter) -> iterator {
- // Merge/rebalance as we walk back up the tree.
- iterator res(iter);
- bool first_iteration = true;
- for (;;) {
- if (iter.node_ == root()) {
- try_shrink();
- if (empty()) {
- return end();
- }
- break;
- }
- if (iter.node_->count() >= kMinNodeValues) {
- break;
- }
- bool merged = try_merge_or_rebalance(&iter);
- // On the first iteration, we should update `res` with `iter` because `res`
- // may have been invalidated.
- if (first_iteration) {
- res = iter;
- first_iteration = false;
- }
- if (!merged) {
- break;
- }
- iter.position_ = iter.node_->position();
- iter.node_ = iter.node_->parent();
- }
- res.update_generation();
-
- // Adjust our return value. If we're pointing at the end of a node, advance
- // the iterator.
- if (res.position_ == res.node_->finish()) {
- res.position_ = res.node_->finish() - 1;
- ++res;
- }
-
- return res;
-}
-
-template <typename P>
-auto btree<P>::erase_range(iterator begin, iterator end)
- -> std::pair<size_type, iterator> {
- size_type count = static_cast<size_type>(end - begin);
- assert(count >= 0);
-
- if (count == 0) {
- return {0, begin};
- }
-
- if (static_cast<size_type>(count) == size_) {
- clear();
- return {count, this->end()};
- }
-
- if (begin.node_ == end.node_) {
- assert(end.position_ > begin.position_);
- begin.node_->remove_values(
- static_cast<field_type>(begin.position_),
- static_cast<field_type>(end.position_ - begin.position_),
- mutable_allocator());
- size_ -= count;
- return {count, rebalance_after_delete(begin)};
- }
-
- const size_type target_size = size_ - count;
- while (size_ > target_size) {
- if (begin.node_->is_leaf()) {
- const size_type remaining_to_erase = size_ - target_size;
- const size_type remaining_in_node =
- static_cast<size_type>(begin.node_->finish() - begin.position_);
- const field_type to_erase = static_cast<field_type>(
- (std::min)(remaining_to_erase, remaining_in_node));
- begin.node_->remove_values(static_cast<field_type>(begin.position_),
- to_erase, mutable_allocator());
- size_ -= to_erase;
- begin = rebalance_after_delete(begin);
- } else {
- begin = erase(begin);
- }
- }
- begin.update_generation();
- return {count, begin};
-}
-
-template <typename P>
-void btree<P>::clear() {
- if (!empty()) {
- node_type::clear_and_delete(root(), mutable_allocator());
- }
- mutable_root() = mutable_rightmost() = EmptyNode();
- size_ = 0;
-}
-
-template <typename P>
-void btree<P>::swap(btree &other) {
- using std::swap;
- if (absl::allocator_traits<
- allocator_type>::propagate_on_container_swap::value) {
- // Note: `rightmost_` also contains the allocator and the key comparator.
- swap(rightmost_, other.rightmost_);
- } else {
- // It's undefined behavior if the allocators are unequal here.
- assert(allocator() == other.allocator());
- swap(mutable_rightmost(), other.mutable_rightmost());
- swap(*mutable_key_comp(), *other.mutable_key_comp());
- }
- swap(mutable_root(), other.mutable_root());
- swap(size_, other.size_);
-}
-
-template <typename P>
-void btree<P>::verify() const {
- assert(root() != nullptr);
- assert(leftmost() != nullptr);
- assert(rightmost() != nullptr);
- assert(empty() || size() == internal_verify(root(), nullptr, nullptr));
- assert(leftmost() == (++const_iterator(root(), -1)).node_);
- assert(rightmost() == (--const_iterator(root(), root()->finish())).node_);
- assert(leftmost()->is_leaf());
- assert(rightmost()->is_leaf());
-}
-
-template <typename P>
-void btree<P>::rebalance_or_split(iterator *iter) {
- node_type *&node = iter->node_;
- int &insert_position = iter->position_;
- assert(node->count() == node->max_count());
- assert(kNodeSlots == node->max_count());
-
- // First try to make room on the node by rebalancing.
- node_type *parent = node->parent();
- if (node != root()) {
- if (node->position() > parent->start()) {
- // Try rebalancing with our left sibling.
- node_type *left = parent->child(node->position() - 1);
- assert(left->max_count() == kNodeSlots);
- if (left->count() < kNodeSlots) {
- // We bias rebalancing based on the position being inserted. If we're
- // inserting at the end of the right node then we bias rebalancing to
- // fill up the left node.
- field_type to_move =
- (kNodeSlots - left->count()) /
- (1 + (static_cast<field_type>(insert_position) < kNodeSlots));
- to_move = (std::max)(field_type{1}, to_move);
-
- if (static_cast<field_type>(insert_position) - to_move >=
- node->start() ||
- left->count() + to_move < kNodeSlots) {
- left->rebalance_right_to_left(to_move, node, mutable_allocator());
-
- assert(node->max_count() - node->count() == to_move);
- insert_position = static_cast<int>(
- static_cast<field_type>(insert_position) - to_move);
- if (insert_position < node->start()) {
- insert_position = insert_position + left->count() + 1;
- node = left;
- }
-
- assert(node->count() < node->max_count());
- return;
- }
- }
- }
-
- if (node->position() < parent->finish()) {
- // Try rebalancing with our right sibling.
- node_type *right = parent->child(node->position() + 1);
- assert(right->max_count() == kNodeSlots);
- if (right->count() < kNodeSlots) {
- // We bias rebalancing based on the position being inserted. If we're
- // inserting at the beginning of the left node then we bias rebalancing
- // to fill up the right node.
- field_type to_move = (kNodeSlots - right->count()) /
- (1 + (insert_position > node->start()));
- to_move = (std::max)(field_type{1}, to_move);
-
- if (static_cast<field_type>(insert_position) <=
- node->finish() - to_move ||
- right->count() + to_move < kNodeSlots) {
- node->rebalance_left_to_right(to_move, right, mutable_allocator());
-
- if (insert_position > node->finish()) {
- insert_position = insert_position - node->count() - 1;
- node = right;
- }
-
- assert(node->count() < node->max_count());
- return;
- }
- }
- }
-
- // Rebalancing failed, make sure there is room on the parent node for a new
- // value.
- assert(parent->max_count() == kNodeSlots);
- if (parent->count() == kNodeSlots) {
- iterator parent_iter(node->parent(), node->position());
- rebalance_or_split(&parent_iter);
- }
- } else {
- // Rebalancing not possible because this is the root node.
- // Create a new root node and set the current root node as the child of the
- // new root.
- parent = new_internal_node(parent);
- parent->set_generation(root()->generation());
- parent->init_child(parent->start(), root());
- mutable_root() = parent;
- // If the former root was a leaf node, then it's now the rightmost node.
- assert(parent->start_child()->is_internal() ||
- parent->start_child() == rightmost());
- }
-
- // Split the node.
- node_type *split_node;
- if (node->is_leaf()) {
- split_node = new_leaf_node(parent);
- node->split(insert_position, split_node, mutable_allocator());
- if (rightmost() == node) mutable_rightmost() = split_node;
- } else {
- split_node = new_internal_node(parent);
- node->split(insert_position, split_node, mutable_allocator());
- }
-
- if (insert_position > node->finish()) {
- insert_position = insert_position - node->count() - 1;
- node = split_node;
- }
-}
-
-template <typename P>
-void btree<P>::merge_nodes(node_type *left, node_type *right) {
- left->merge(right, mutable_allocator());
- if (rightmost() == right) mutable_rightmost() = left;
-}
-
-template <typename P>
-bool btree<P>::try_merge_or_rebalance(iterator *iter) {
- node_type *parent = iter->node_->parent();
- if (iter->node_->position() > parent->start()) {
- // Try merging with our left sibling.
- node_type *left = parent->child(iter->node_->position() - 1);
- assert(left->max_count() == kNodeSlots);
- if (1U + left->count() + iter->node_->count() <= kNodeSlots) {
- iter->position_ += 1 + left->count();
- merge_nodes(left, iter->node_);
- iter->node_ = left;
- return true;
- }
- }
- if (iter->node_->position() < parent->finish()) {
- // Try merging with our right sibling.
- node_type *right = parent->child(iter->node_->position() + 1);
- assert(right->max_count() == kNodeSlots);
- if (1U + iter->node_->count() + right->count() <= kNodeSlots) {
- merge_nodes(iter->node_, right);
- return true;
- }
- // Try rebalancing with our right sibling. We don't perform rebalancing if
- // we deleted the first element from iter->node_ and the node is not
- // empty. This is a small optimization for the common pattern of deleting
- // from the front of the tree.
- if (right->count() > kMinNodeValues &&
- (iter->node_->count() == 0 || iter->position_ > iter->node_->start())) {
- field_type to_move = (right->count() - iter->node_->count()) / 2;
- to_move =
- (std::min)(to_move, static_cast<field_type>(right->count() - 1));
- iter->node_->rebalance_right_to_left(to_move, right, mutable_allocator());
- return false;
- }
- }
- if (iter->node_->position() > parent->start()) {
- // Try rebalancing with our left sibling. We don't perform rebalancing if
- // we deleted the last element from iter->node_ and the node is not
- // empty. This is a small optimization for the common pattern of deleting
- // from the back of the tree.
- node_type *left = parent->child(iter->node_->position() - 1);
- if (left->count() > kMinNodeValues &&
- (iter->node_->count() == 0 ||
- iter->position_ < iter->node_->finish())) {
- field_type to_move = (left->count() - iter->node_->count()) / 2;
- to_move = (std::min)(to_move, static_cast<field_type>(left->count() - 1));
- left->rebalance_left_to_right(to_move, iter->node_, mutable_allocator());
- iter->position_ += to_move;
- return false;
- }
- }
- return false;
-}
-
-template <typename P>
-void btree<P>::try_shrink() {
- node_type *orig_root = root();
- if (orig_root->count() > 0) {
- return;
- }
- // Deleted the last item on the root node, shrink the height of the tree.
- if (orig_root->is_leaf()) {
- assert(size() == 0);
- mutable_root() = mutable_rightmost() = EmptyNode();
- } else {
- node_type *child = orig_root->start_child();
- child->make_root();
- mutable_root() = child;
- }
- node_type::clear_and_delete(orig_root, mutable_allocator());
-}
-
-template <typename P>
-template <typename IterType>
-inline IterType btree<P>::internal_last(IterType iter) {
- assert(iter.node_ != nullptr);
- while (iter.position_ == iter.node_->finish()) {
- iter.position_ = iter.node_->position();
- iter.node_ = iter.node_->parent();
- if (iter.node_->is_leaf()) {
- iter.node_ = nullptr;
- break;
- }
- }
- iter.update_generation();
- return iter;
-}
-
-template <typename P>
-template <typename... Args>
-inline auto btree<P>::internal_emplace(iterator iter, Args &&...args)
- -> iterator {
- if (iter.node_->is_internal()) {
- // We can't insert on an internal node. Instead, we'll insert after the
- // previous value which is guaranteed to be on a leaf node.
- --iter;
- ++iter.position_;
- }
- const field_type max_count = iter.node_->max_count();
- allocator_type *alloc = mutable_allocator();
- if (iter.node_->count() == max_count) {
- // Make room in the leaf for the new item.
- if (max_count < kNodeSlots) {
- // Insertion into the root where the root is smaller than the full node
- // size. Simply grow the size of the root node.
- assert(iter.node_ == root());
- iter.node_ = new_leaf_root_node(static_cast<field_type>(
- (std::min)(static_cast<int>(kNodeSlots), 2 * max_count)));
- // Transfer the values from the old root to the new root.
- node_type *old_root = root();
- node_type *new_root = iter.node_;
- new_root->transfer_n(old_root->count(), new_root->start(),
- old_root->start(), old_root, alloc);
- new_root->set_finish(old_root->finish());
- old_root->set_finish(old_root->start());
- new_root->set_generation(old_root->generation());
- node_type::clear_and_delete(old_root, alloc);
- mutable_root() = mutable_rightmost() = new_root;
- } else {
- rebalance_or_split(&iter);
- }
- }
- iter.node_->emplace_value(static_cast<field_type>(iter.position_), alloc,
- std::forward<Args>(args)...);
- ++size_;
- iter.update_generation();
- return iter;
-}
-
-template <typename P>
-template <typename K>
-inline auto btree<P>::internal_locate(const K &key) const
- -> SearchResult<iterator, is_key_compare_to::value> {
- iterator iter(const_cast<node_type *>(root()));
- for (;;) {
- SearchResult<size_type, is_key_compare_to::value> res =
- iter.node_->lower_bound(key, key_comp());
- iter.position_ = static_cast<int>(res.value);
- if (res.IsEq()) {
- return {iter, MatchKind::kEq};
- }
- // Note: in the non-key-compare-to case, we don't need to walk all the way
- // down the tree if the keys are equal, but determining equality would
- // require doing an extra comparison on each node on the way down, and we
- // will need to go all the way to the leaf node in the expected case.
- if (iter.node_->is_leaf()) {
- break;
- }
- iter.node_ = iter.node_->child(static_cast<field_type>(iter.position_));
- }
- // Note: in the non-key-compare-to case, the key may actually be equivalent
- // here (and the MatchKind::kNe is ignored).
- return {iter, MatchKind::kNe};
-}
-
-template <typename P>
-template <typename K>
-auto btree<P>::internal_lower_bound(const K &key) const
- -> SearchResult<iterator, is_key_compare_to::value> {
- if (!params_type::template can_have_multiple_equivalent_keys<K>()) {
- SearchResult<iterator, is_key_compare_to::value> ret = internal_locate(key);
- ret.value = internal_last(ret.value);
- return ret;
- }
- iterator iter(const_cast<node_type *>(root()));
- SearchResult<size_type, is_key_compare_to::value> res;
- bool seen_eq = false;
- for (;;) {
- res = iter.node_->lower_bound(key, key_comp());
- iter.position_ = static_cast<int>(res.value);
- if (iter.node_->is_leaf()) {
- break;
- }
- seen_eq = seen_eq || res.IsEq();
- iter.node_ = iter.node_->child(static_cast<field_type>(iter.position_));
- }
- if (res.IsEq()) return {iter, MatchKind::kEq};
- return {internal_last(iter), seen_eq ? MatchKind::kEq : MatchKind::kNe};
-}
-
-template <typename P>
-template <typename K>
-auto btree<P>::internal_upper_bound(const K &key) const -> iterator {
- iterator iter(const_cast<node_type *>(root()));
- for (;;) {
- iter.position_ = static_cast<int>(iter.node_->upper_bound(key, key_comp()));
- if (iter.node_->is_leaf()) {
- break;
- }
- iter.node_ = iter.node_->child(static_cast<field_type>(iter.position_));
- }
- return internal_last(iter);
-}
-
-template <typename P>
-template <typename K>
-auto btree<P>::internal_find(const K &key) const -> iterator {
- SearchResult<iterator, is_key_compare_to::value> res = internal_locate(key);
- if (res.HasMatch()) {
- if (res.IsEq()) {
- return res.value;
- }
- } else {
- const iterator iter = internal_last(res.value);
- if (iter.node_ != nullptr && !compare_keys(key, iter.key())) {
- return iter;
- }
- }
- return {nullptr, 0};
-}
-
-template <typename P>
-typename btree<P>::size_type btree<P>::internal_verify(
- const node_type *node, const key_type *lo, const key_type *hi) const {
- assert(node->count() > 0);
- assert(node->count() <= node->max_count());
- if (lo) {
- assert(!compare_keys(node->key(node->start()), *lo));
- }
- if (hi) {
- assert(!compare_keys(*hi, node->key(node->finish() - 1)));
- }
- for (int i = node->start() + 1; i < node->finish(); ++i) {
- assert(!compare_keys(node->key(i), node->key(i - 1)));
- }
- size_type count = node->count();
- if (node->is_internal()) {
- for (field_type i = node->start(); i <= node->finish(); ++i) {
- assert(node->child(i) != nullptr);
- assert(node->child(i)->parent() == node);
- assert(node->child(i)->position() == i);
- count += internal_verify(node->child(i),
- i == node->start() ? lo : &node->key(i - 1),
- i == node->finish() ? hi : &node->key(i));
- }
- }
- return count;
-}
-
-struct btree_access {
- template <typename BtreeContainer, typename Pred>
- static auto erase_if(BtreeContainer &container, Pred pred) ->
- typename BtreeContainer::size_type {
- const auto initial_size = container.size();
- auto &tree = container.tree_;
- auto *alloc = tree.mutable_allocator();
- for (auto it = container.begin(); it != container.end();) {
- if (!pred(*it)) {
- ++it;
- continue;
- }
- auto *node = it.node_;
- if (node->is_internal()) {
- // Handle internal nodes normally.
- it = container.erase(it);
- continue;
- }
- // If this is a leaf node, then we do all the erases from this node
- // at once before doing rebalancing.
-
- // The current position to transfer slots to.
- int to_pos = it.position_;
- node->value_destroy(it.position_, alloc);
- while (++it.position_ < node->finish()) {
- it.update_generation();
- if (pred(*it)) {
- node->value_destroy(it.position_, alloc);
- } else {
- node->transfer(node->slot(to_pos++), node->slot(it.position_), alloc);
- }
- }
- const int num_deleted = node->finish() - to_pos;
- tree.size_ -= num_deleted;
- node->set_finish(to_pos);
- it.position_ = to_pos;
- it = tree.rebalance_after_delete(it);
- }
- return initial_size - container.size();
- }
-};
-
-#undef ABSL_BTREE_ENABLE_GENERATIONS
-
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_INTERNAL_BTREE_H_
diff --git a/third_party/abseil-cpp/absl/container/internal/btree_container.h b/third_party/abseil-cpp/absl/container/internal/btree_container.h
deleted file mode 100644
index 3e25986..0000000
--- a/third_party/abseil-cpp/absl/container/internal/btree_container.h
+++ /dev/null
@@ -1,699 +0,0 @@
-// Copyright 2018 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_CONTAINER_INTERNAL_BTREE_CONTAINER_H_
-#define ABSL_CONTAINER_INTERNAL_BTREE_CONTAINER_H_
-
-#include <algorithm>
-#include <initializer_list>
-#include <iterator>
-#include <utility>
-
-#include "absl/base/attributes.h"
-#include "absl/base/internal/throw_delegate.h"
-#include "absl/container/internal/btree.h" // IWYU pragma: export
-#include "absl/container/internal/common.h"
-#include "absl/memory/memory.h"
-#include "absl/meta/type_traits.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-
-// A common base class for btree_set, btree_map, btree_multiset, and
-// btree_multimap.
-template <typename Tree>
-class btree_container {
- using params_type = typename Tree::params_type;
-
- protected:
- // Alias used for heterogeneous lookup functions.
- // `key_arg<K>` evaluates to `K` when the functors are transparent and to
- // `key_type` otherwise. It permits template argument deduction on `K` for the
- // transparent case.
- template <class K>
- using key_arg =
- typename KeyArg<params_type::kIsKeyCompareTransparent>::template type<
- K, typename Tree::key_type>;
-
- public:
- using key_type = typename Tree::key_type;
- using value_type = typename Tree::value_type;
- using size_type = typename Tree::size_type;
- using difference_type = typename Tree::difference_type;
- using key_compare = typename Tree::original_key_compare;
- using value_compare = typename Tree::value_compare;
- using allocator_type = typename Tree::allocator_type;
- using reference = typename Tree::reference;
- using const_reference = typename Tree::const_reference;
- using pointer = typename Tree::pointer;
- using const_pointer = typename Tree::const_pointer;
- using iterator = typename Tree::iterator;
- using const_iterator = typename Tree::const_iterator;
- using reverse_iterator = typename Tree::reverse_iterator;
- using const_reverse_iterator = typename Tree::const_reverse_iterator;
- using node_type = typename Tree::node_handle_type;
-
- // Constructors/assignments.
- btree_container() : tree_(key_compare(), allocator_type()) {}
- explicit btree_container(const key_compare &comp,
- const allocator_type &alloc = allocator_type())
- : tree_(comp, alloc) {}
- explicit btree_container(const allocator_type &alloc)
- : tree_(key_compare(), alloc) {}
-
- btree_container(const btree_container &other)
- : btree_container(other, absl::allocator_traits<allocator_type>::
- select_on_container_copy_construction(
- other.get_allocator())) {}
- btree_container(const btree_container &other, const allocator_type &alloc)
- : tree_(other.tree_, alloc) {}
-
- btree_container(btree_container &&other) noexcept(
- std::is_nothrow_move_constructible<Tree>::value) = default;
- btree_container(btree_container &&other, const allocator_type &alloc)
- : tree_(std::move(other.tree_), alloc) {}
-
- btree_container &operator=(const btree_container &other) = default;
- btree_container &operator=(btree_container &&other) noexcept(
- std::is_nothrow_move_assignable<Tree>::value) = default;
-
- // Iterator routines.
- iterator begin() { return tree_.begin(); }
- const_iterator begin() const { return tree_.begin(); }
- const_iterator cbegin() const { return tree_.begin(); }
- iterator end() { return tree_.end(); }
- const_iterator end() const { return tree_.end(); }
- const_iterator cend() const { return tree_.end(); }
- reverse_iterator rbegin() { return tree_.rbegin(); }
- const_reverse_iterator rbegin() const { return tree_.rbegin(); }
- const_reverse_iterator crbegin() const { return tree_.rbegin(); }
- reverse_iterator rend() { return tree_.rend(); }
- const_reverse_iterator rend() const { return tree_.rend(); }
- const_reverse_iterator crend() const { return tree_.rend(); }
-
- // Lookup routines.
- template <typename K = key_type>
- size_type count(const key_arg<K> &key) const {
- auto equal_range = this->equal_range(key);
- return equal_range.second - equal_range.first;
- }
- template <typename K = key_type>
- iterator find(const key_arg<K> &key) {
- return tree_.find(key);
- }
- template <typename K = key_type>
- const_iterator find(const key_arg<K> &key) const {
- return tree_.find(key);
- }
- template <typename K = key_type>
- bool contains(const key_arg<K> &key) const {
- return find(key) != end();
- }
- template <typename K = key_type>
- iterator lower_bound(const key_arg<K> &key) {
- return tree_.lower_bound(key);
- }
- template <typename K = key_type>
- const_iterator lower_bound(const key_arg<K> &key) const {
- return tree_.lower_bound(key);
- }
- template <typename K = key_type>
- iterator upper_bound(const key_arg<K> &key) {
- return tree_.upper_bound(key);
- }
- template <typename K = key_type>
- const_iterator upper_bound(const key_arg<K> &key) const {
- return tree_.upper_bound(key);
- }
- template <typename K = key_type>
- std::pair<iterator, iterator> equal_range(const key_arg<K> &key) {
- return tree_.equal_range(key);
- }
- template <typename K = key_type>
- std::pair<const_iterator, const_iterator> equal_range(
- const key_arg<K> &key) const {
- return tree_.equal_range(key);
- }
-
- // Deletion routines. Note that there is also a deletion routine that is
- // specific to btree_set_container/btree_multiset_container.
-
- // Erase the specified iterator from the btree. The iterator must be valid
- // (i.e. not equal to end()). Return an iterator pointing to the node after
- // the one that was erased (or end() if none exists).
- iterator erase(const_iterator iter) { return tree_.erase(iterator(iter)); }
- iterator erase(iterator iter) { return tree_.erase(iter); }
- iterator erase(const_iterator first, const_iterator last) {
- return tree_.erase_range(iterator(first), iterator(last)).second;
- }
- template <typename K = key_type>
- size_type erase(const key_arg<K> &key) {
- auto equal_range = this->equal_range(key);
- return tree_.erase_range(equal_range.first, equal_range.second).first;
- }
-
- // Extract routines.
- node_type extract(iterator position) {
- // Use Construct instead of Transfer because the rebalancing code will
- // destroy the slot later.
- auto node =
- CommonAccess::Construct<node_type>(get_allocator(), position.slot());
- erase(position);
- return node;
- }
- node_type extract(const_iterator position) {
- return extract(iterator(position));
- }
-
- // Utility routines.
- ABSL_ATTRIBUTE_REINITIALIZES void clear() { tree_.clear(); }
- void swap(btree_container &other) { tree_.swap(other.tree_); }
- void verify() const { tree_.verify(); }
-
- // Size routines.
- size_type size() const { return tree_.size(); }
- size_type max_size() const { return tree_.max_size(); }
- bool empty() const { return tree_.empty(); }
-
- friend bool operator==(const btree_container &x, const btree_container &y) {
- if (x.size() != y.size()) return false;
- return std::equal(x.begin(), x.end(), y.begin());
- }
-
- friend bool operator!=(const btree_container &x, const btree_container &y) {
- return !(x == y);
- }
-
- friend bool operator<(const btree_container &x, const btree_container &y) {
- return std::lexicographical_compare(x.begin(), x.end(), y.begin(), y.end());
- }
-
- friend bool operator>(const btree_container &x, const btree_container &y) {
- return y < x;
- }
-
- friend bool operator<=(const btree_container &x, const btree_container &y) {
- return !(y < x);
- }
-
- friend bool operator>=(const btree_container &x, const btree_container &y) {
- return !(x < y);
- }
-
- // The allocator used by the btree.
- allocator_type get_allocator() const { return tree_.get_allocator(); }
-
- // The key comparator used by the btree.
- key_compare key_comp() const { return key_compare(tree_.key_comp()); }
- value_compare value_comp() const { return tree_.value_comp(); }
-
- // Support absl::Hash.
- template <typename State>
- friend State AbslHashValue(State h, const btree_container &b) {
- for (const auto &v : b) {
- h = State::combine(std::move(h), v);
- }
- return State::combine(std::move(h), b.size());
- }
-
- protected:
- friend struct btree_access;
- Tree tree_;
-};
-
-// A common base class for btree_set and btree_map.
-template <typename Tree>
-class btree_set_container : public btree_container<Tree> {
- using super_type = btree_container<Tree>;
- using params_type = typename Tree::params_type;
- using init_type = typename params_type::init_type;
- using is_key_compare_to = typename params_type::is_key_compare_to;
- friend class BtreeNodePeer;
-
- protected:
- template <class K>
- using key_arg = typename super_type::template key_arg<K>;
-
- public:
- using key_type = typename Tree::key_type;
- using value_type = typename Tree::value_type;
- using size_type = typename Tree::size_type;
- using key_compare = typename Tree::original_key_compare;
- using allocator_type = typename Tree::allocator_type;
- using iterator = typename Tree::iterator;
- using const_iterator = typename Tree::const_iterator;
- using node_type = typename super_type::node_type;
- using insert_return_type = InsertReturnType<iterator, node_type>;
-
- // Inherit constructors.
- using super_type::super_type;
- btree_set_container() {}
-
- // Range constructors.
- template <class InputIterator>
- btree_set_container(InputIterator b, InputIterator e,
- const key_compare &comp = key_compare(),
- const allocator_type &alloc = allocator_type())
- : super_type(comp, alloc) {
- insert(b, e);
- }
- template <class InputIterator>
- btree_set_container(InputIterator b, InputIterator e,
- const allocator_type &alloc)
- : btree_set_container(b, e, key_compare(), alloc) {}
-
- // Initializer list constructors.
- btree_set_container(std::initializer_list<init_type> init,
- const key_compare &comp = key_compare(),
- const allocator_type &alloc = allocator_type())
- : btree_set_container(init.begin(), init.end(), comp, alloc) {}
- btree_set_container(std::initializer_list<init_type> init,
- const allocator_type &alloc)
- : btree_set_container(init.begin(), init.end(), alloc) {}
-
- // Insertion routines.
- std::pair<iterator, bool> insert(const value_type &v) {
- return this->tree_.insert_unique(params_type::key(v), v);
- }
- std::pair<iterator, bool> insert(value_type &&v) {
- return this->tree_.insert_unique(params_type::key(v), std::move(v));
- }
- template <typename... Args>
- std::pair<iterator, bool> emplace(Args &&... args) {
- // Use a node handle to manage a temp slot.
- auto node = CommonAccess::Construct<node_type>(this->get_allocator(),
- std::forward<Args>(args)...);
- auto *slot = CommonAccess::GetSlot(node);
- return this->tree_.insert_unique(params_type::key(slot), slot);
- }
- iterator insert(const_iterator hint, const value_type &v) {
- return this->tree_
- .insert_hint_unique(iterator(hint), params_type::key(v), v)
- .first;
- }
- iterator insert(const_iterator hint, value_type &&v) {
- return this->tree_
- .insert_hint_unique(iterator(hint), params_type::key(v), std::move(v))
- .first;
- }
- template <typename... Args>
- iterator emplace_hint(const_iterator hint, Args &&... args) {
- // Use a node handle to manage a temp slot.
- auto node = CommonAccess::Construct<node_type>(this->get_allocator(),
- std::forward<Args>(args)...);
- auto *slot = CommonAccess::GetSlot(node);
- return this->tree_
- .insert_hint_unique(iterator(hint), params_type::key(slot), slot)
- .first;
- }
- template <typename InputIterator>
- void insert(InputIterator b, InputIterator e) {
- this->tree_.insert_iterator_unique(b, e, 0);
- }
- void insert(std::initializer_list<init_type> init) {
- this->tree_.insert_iterator_unique(init.begin(), init.end(), 0);
- }
- insert_return_type insert(node_type &&node) {
- if (!node) return {this->end(), false, node_type()};
- std::pair<iterator, bool> res =
- this->tree_.insert_unique(params_type::key(CommonAccess::GetSlot(node)),
- CommonAccess::GetSlot(node));
- if (res.second) {
- CommonAccess::Destroy(&node);
- return {res.first, true, node_type()};
- } else {
- return {res.first, false, std::move(node)};
- }
- }
- iterator insert(const_iterator hint, node_type &&node) {
- if (!node) return this->end();
- std::pair<iterator, bool> res = this->tree_.insert_hint_unique(
- iterator(hint), params_type::key(CommonAccess::GetSlot(node)),
- CommonAccess::GetSlot(node));
- if (res.second) CommonAccess::Destroy(&node);
- return res.first;
- }
-
- // Node extraction routines.
- template <typename K = key_type>
- node_type extract(const key_arg<K> &key) {
- const std::pair<iterator, bool> lower_and_equal =
- this->tree_.lower_bound_equal(key);
- return lower_and_equal.second ? extract(lower_and_equal.first)
- : node_type();
- }
- using super_type::extract;
-
- // Merge routines.
- // Moves elements from `src` into `this`. If the element already exists in
- // `this`, it is left unmodified in `src`.
- template <
- typename T,
- typename absl::enable_if_t<
- absl::conjunction<
- std::is_same<value_type, typename T::value_type>,
- std::is_same<allocator_type, typename T::allocator_type>,
- std::is_same<typename params_type::is_map_container,
- typename T::params_type::is_map_container>>::value,
- int> = 0>
- void merge(btree_container<T> &src) { // NOLINT
- for (auto src_it = src.begin(); src_it != src.end();) {
- if (insert(std::move(params_type::element(src_it.slot()))).second) {
- src_it = src.erase(src_it);
- } else {
- ++src_it;
- }
- }
- }
-
- template <
- typename T,
- typename absl::enable_if_t<
- absl::conjunction<
- std::is_same<value_type, typename T::value_type>,
- std::is_same<allocator_type, typename T::allocator_type>,
- std::is_same<typename params_type::is_map_container,
- typename T::params_type::is_map_container>>::value,
- int> = 0>
- void merge(btree_container<T> &&src) {
- merge(src);
- }
-};
-
-// Base class for btree_map.
-template <typename Tree>
-class btree_map_container : public btree_set_container<Tree> {
- using super_type = btree_set_container<Tree>;
- using params_type = typename Tree::params_type;
- friend class BtreeNodePeer;
-
- private:
- template <class K>
- using key_arg = typename super_type::template key_arg<K>;
-
- public:
- using key_type = typename Tree::key_type;
- using mapped_type = typename params_type::mapped_type;
- using value_type = typename Tree::value_type;
- using key_compare = typename Tree::original_key_compare;
- using allocator_type = typename Tree::allocator_type;
- using iterator = typename Tree::iterator;
- using const_iterator = typename Tree::const_iterator;
-
- // Inherit constructors.
- using super_type::super_type;
- btree_map_container() {}
-
- // Insertion routines.
- // Note: the nullptr template arguments and extra `const M&` overloads allow
- // for supporting bitfield arguments.
- template <typename K = key_type, class M>
- std::pair<iterator, bool> insert_or_assign(const key_arg<K> &k,
- const M &obj) {
- return insert_or_assign_impl(k, obj);
- }
- template <typename K = key_type, class M, K * = nullptr>
- std::pair<iterator, bool> insert_or_assign(key_arg<K> &&k, const M &obj) {
- return insert_or_assign_impl(std::forward<K>(k), obj);
- }
- template <typename K = key_type, class M, M * = nullptr>
- std::pair<iterator, bool> insert_or_assign(const key_arg<K> &k, M &&obj) {
- return insert_or_assign_impl(k, std::forward<M>(obj));
- }
- template <typename K = key_type, class M, K * = nullptr, M * = nullptr>
- std::pair<iterator, bool> insert_or_assign(key_arg<K> &&k, M &&obj) {
- return insert_or_assign_impl(std::forward<K>(k), std::forward<M>(obj));
- }
- template <typename K = key_type, class M>
- iterator insert_or_assign(const_iterator hint, const key_arg<K> &k,
- const M &obj) {
- return insert_or_assign_hint_impl(hint, k, obj);
- }
- template <typename K = key_type, class M, K * = nullptr>
- iterator insert_or_assign(const_iterator hint, key_arg<K> &&k, const M &obj) {
- return insert_or_assign_hint_impl(hint, std::forward<K>(k), obj);
- }
- template <typename K = key_type, class M, M * = nullptr>
- iterator insert_or_assign(const_iterator hint, const key_arg<K> &k, M &&obj) {
- return insert_or_assign_hint_impl(hint, k, std::forward<M>(obj));
- }
- template <typename K = key_type, class M, K * = nullptr, M * = nullptr>
- iterator insert_or_assign(const_iterator hint, key_arg<K> &&k, M &&obj) {
- return insert_or_assign_hint_impl(hint, std::forward<K>(k),
- std::forward<M>(obj));
- }
-
- template <typename K = key_type, typename... Args,
- typename absl::enable_if_t<
- !std::is_convertible<K, const_iterator>::value, int> = 0>
- std::pair<iterator, bool> try_emplace(const key_arg<K> &k, Args &&... args) {
- return try_emplace_impl(k, std::forward<Args>(args)...);
- }
- template <typename K = key_type, typename... Args,
- typename absl::enable_if_t<
- !std::is_convertible<K, const_iterator>::value, int> = 0>
- std::pair<iterator, bool> try_emplace(key_arg<K> &&k, Args &&... args) {
- return try_emplace_impl(std::forward<K>(k), std::forward<Args>(args)...);
- }
- template <typename K = key_type, typename... Args>
- iterator try_emplace(const_iterator hint, const key_arg<K> &k,
- Args &&... args) {
- return try_emplace_hint_impl(hint, k, std::forward<Args>(args)...);
- }
- template <typename K = key_type, typename... Args>
- iterator try_emplace(const_iterator hint, key_arg<K> &&k, Args &&... args) {
- return try_emplace_hint_impl(hint, std::forward<K>(k),
- std::forward<Args>(args)...);
- }
-
- template <typename K = key_type>
- mapped_type &operator[](const key_arg<K> &k) {
- return try_emplace(k).first->second;
- }
- template <typename K = key_type>
- mapped_type &operator[](key_arg<K> &&k) {
- return try_emplace(std::forward<K>(k)).first->second;
- }
-
- template <typename K = key_type>
- mapped_type &at(const key_arg<K> &key) {
- auto it = this->find(key);
- if (it == this->end())
- base_internal::ThrowStdOutOfRange("absl::btree_map::at");
- return it->second;
- }
- template <typename K = key_type>
- const mapped_type &at(const key_arg<K> &key) const {
- auto it = this->find(key);
- if (it == this->end())
- base_internal::ThrowStdOutOfRange("absl::btree_map::at");
- return it->second;
- }
-
- private:
- // Note: when we call `std::forward<M>(obj)` twice, it's safe because
- // insert_unique/insert_hint_unique are guaranteed to not consume `obj` when
- // `ret.second` is false.
- template <class K, class M>
- std::pair<iterator, bool> insert_or_assign_impl(K &&k, M &&obj) {
- const std::pair<iterator, bool> ret =
- this->tree_.insert_unique(k, std::forward<K>(k), std::forward<M>(obj));
- if (!ret.second) ret.first->second = std::forward<M>(obj);
- return ret;
- }
- template <class K, class M>
- iterator insert_or_assign_hint_impl(const_iterator hint, K &&k, M &&obj) {
- const std::pair<iterator, bool> ret = this->tree_.insert_hint_unique(
- iterator(hint), k, std::forward<K>(k), std::forward<M>(obj));
- if (!ret.second) ret.first->second = std::forward<M>(obj);
- return ret.first;
- }
-
- template <class K, class... Args>
- std::pair<iterator, bool> try_emplace_impl(K &&k, Args &&... args) {
- return this->tree_.insert_unique(
- k, std::piecewise_construct, std::forward_as_tuple(std::forward<K>(k)),
- std::forward_as_tuple(std::forward<Args>(args)...));
- }
- template <class K, class... Args>
- iterator try_emplace_hint_impl(const_iterator hint, K &&k, Args &&... args) {
- return this->tree_
- .insert_hint_unique(iterator(hint), k, std::piecewise_construct,
- std::forward_as_tuple(std::forward<K>(k)),
- std::forward_as_tuple(std::forward<Args>(args)...))
- .first;
- }
-};
-
-// A common base class for btree_multiset and btree_multimap.
-template <typename Tree>
-class btree_multiset_container : public btree_container<Tree> {
- using super_type = btree_container<Tree>;
- using params_type = typename Tree::params_type;
- using init_type = typename params_type::init_type;
- using is_key_compare_to = typename params_type::is_key_compare_to;
- friend class BtreeNodePeer;
-
- template <class K>
- using key_arg = typename super_type::template key_arg<K>;
-
- public:
- using key_type = typename Tree::key_type;
- using value_type = typename Tree::value_type;
- using size_type = typename Tree::size_type;
- using key_compare = typename Tree::original_key_compare;
- using allocator_type = typename Tree::allocator_type;
- using iterator = typename Tree::iterator;
- using const_iterator = typename Tree::const_iterator;
- using node_type = typename super_type::node_type;
-
- // Inherit constructors.
- using super_type::super_type;
- btree_multiset_container() {}
-
- // Range constructors.
- template <class InputIterator>
- btree_multiset_container(InputIterator b, InputIterator e,
- const key_compare &comp = key_compare(),
- const allocator_type &alloc = allocator_type())
- : super_type(comp, alloc) {
- insert(b, e);
- }
- template <class InputIterator>
- btree_multiset_container(InputIterator b, InputIterator e,
- const allocator_type &alloc)
- : btree_multiset_container(b, e, key_compare(), alloc) {}
-
- // Initializer list constructors.
- btree_multiset_container(std::initializer_list<init_type> init,
- const key_compare &comp = key_compare(),
- const allocator_type &alloc = allocator_type())
- : btree_multiset_container(init.begin(), init.end(), comp, alloc) {}
- btree_multiset_container(std::initializer_list<init_type> init,
- const allocator_type &alloc)
- : btree_multiset_container(init.begin(), init.end(), alloc) {}
-
- // Insertion routines.
- iterator insert(const value_type &v) { return this->tree_.insert_multi(v); }
- iterator insert(value_type &&v) {
- return this->tree_.insert_multi(std::move(v));
- }
- iterator insert(const_iterator hint, const value_type &v) {
- return this->tree_.insert_hint_multi(iterator(hint), v);
- }
- iterator insert(const_iterator hint, value_type &&v) {
- return this->tree_.insert_hint_multi(iterator(hint), std::move(v));
- }
- template <typename InputIterator>
- void insert(InputIterator b, InputIterator e) {
- this->tree_.insert_iterator_multi(b, e);
- }
- void insert(std::initializer_list<init_type> init) {
- this->tree_.insert_iterator_multi(init.begin(), init.end());
- }
- template <typename... Args>
- iterator emplace(Args &&... args) {
- // Use a node handle to manage a temp slot.
- auto node = CommonAccess::Construct<node_type>(this->get_allocator(),
- std::forward<Args>(args)...);
- return this->tree_.insert_multi(CommonAccess::GetSlot(node));
- }
- template <typename... Args>
- iterator emplace_hint(const_iterator hint, Args &&... args) {
- // Use a node handle to manage a temp slot.
- auto node = CommonAccess::Construct<node_type>(this->get_allocator(),
- std::forward<Args>(args)...);
- return this->tree_.insert_hint_multi(iterator(hint),
- CommonAccess::GetSlot(node));
- }
- iterator insert(node_type &&node) {
- if (!node) return this->end();
- iterator res =
- this->tree_.insert_multi(params_type::key(CommonAccess::GetSlot(node)),
- CommonAccess::GetSlot(node));
- CommonAccess::Destroy(&node);
- return res;
- }
- iterator insert(const_iterator hint, node_type &&node) {
- if (!node) return this->end();
- iterator res = this->tree_.insert_hint_multi(
- iterator(hint),
- std::move(params_type::element(CommonAccess::GetSlot(node))));
- CommonAccess::Destroy(&node);
- return res;
- }
-
- // Node extraction routines.
- template <typename K = key_type>
- node_type extract(const key_arg<K> &key) {
- const std::pair<iterator, bool> lower_and_equal =
- this->tree_.lower_bound_equal(key);
- return lower_and_equal.second ? extract(lower_and_equal.first)
- : node_type();
- }
- using super_type::extract;
-
- // Merge routines.
- // Moves all elements from `src` into `this`.
- template <
- typename T,
- typename absl::enable_if_t<
- absl::conjunction<
- std::is_same<value_type, typename T::value_type>,
- std::is_same<allocator_type, typename T::allocator_type>,
- std::is_same<typename params_type::is_map_container,
- typename T::params_type::is_map_container>>::value,
- int> = 0>
- void merge(btree_container<T> &src) { // NOLINT
- for (auto src_it = src.begin(), end = src.end(); src_it != end; ++src_it) {
- insert(std::move(params_type::element(src_it.slot())));
- }
- src.clear();
- }
-
- template <
- typename T,
- typename absl::enable_if_t<
- absl::conjunction<
- std::is_same<value_type, typename T::value_type>,
- std::is_same<allocator_type, typename T::allocator_type>,
- std::is_same<typename params_type::is_map_container,
- typename T::params_type::is_map_container>>::value,
- int> = 0>
- void merge(btree_container<T> &&src) {
- merge(src);
- }
-};
-
-// A base class for btree_multimap.
-template <typename Tree>
-class btree_multimap_container : public btree_multiset_container<Tree> {
- using super_type = btree_multiset_container<Tree>;
- using params_type = typename Tree::params_type;
- friend class BtreeNodePeer;
-
- public:
- using mapped_type = typename params_type::mapped_type;
-
- // Inherit constructors.
- using super_type::super_type;
- btree_multimap_container() {}
-};
-
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_INTERNAL_BTREE_CONTAINER_H_
diff --git a/third_party/abseil-cpp/absl/container/internal/common.h b/third_party/abseil-cpp/absl/container/internal/common.h
deleted file mode 100644
index 9239bb4..0000000
--- a/third_party/abseil-cpp/absl/container/internal/common.h
+++ /dev/null
@@ -1,207 +0,0 @@
-// Copyright 2018 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_CONTAINER_INTERNAL_COMMON_H_
-#define ABSL_CONTAINER_INTERNAL_COMMON_H_
-
-#include <cassert>
-#include <type_traits>
-
-#include "absl/meta/type_traits.h"
-#include "absl/types/optional.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-
-template <class, class = void>
-struct IsTransparent : std::false_type {};
-template <class T>
-struct IsTransparent<T, absl::void_t<typename T::is_transparent>>
- : std::true_type {};
-
-template <bool is_transparent>
-struct KeyArg {
- // Transparent. Forward `K`.
- template <typename K, typename key_type>
- using type = K;
-};
-
-template <>
-struct KeyArg<false> {
- // Not transparent. Always use `key_type`.
- template <typename K, typename key_type>
- using type = key_type;
-};
-
-// The node_handle concept from C++17.
-// We specialize node_handle for sets and maps. node_handle_base holds the
-// common API of both.
-template <typename PolicyTraits, typename Alloc>
-class node_handle_base {
- protected:
- using slot_type = typename PolicyTraits::slot_type;
-
- public:
- using allocator_type = Alloc;
-
- constexpr node_handle_base() = default;
- node_handle_base(node_handle_base&& other) noexcept {
- *this = std::move(other);
- }
- ~node_handle_base() { destroy(); }
- node_handle_base& operator=(node_handle_base&& other) noexcept {
- destroy();
- if (!other.empty()) {
- alloc_ = other.alloc_;
- PolicyTraits::transfer(alloc(), slot(), other.slot());
- other.reset();
- }
- return *this;
- }
-
- bool empty() const noexcept { return !alloc_; }
- explicit operator bool() const noexcept { return !empty(); }
- allocator_type get_allocator() const { return *alloc_; }
-
- protected:
- friend struct CommonAccess;
-
- struct transfer_tag_t {};
- node_handle_base(transfer_tag_t, const allocator_type& a, slot_type* s)
- : alloc_(a) {
- PolicyTraits::transfer(alloc(), slot(), s);
- }
-
- struct construct_tag_t {};
- template <typename... Args>
- node_handle_base(construct_tag_t, const allocator_type& a, Args&&... args)
- : alloc_(a) {
- PolicyTraits::construct(alloc(), slot(), std::forward<Args>(args)...);
- }
-
- void destroy() {
- if (!empty()) {
- PolicyTraits::destroy(alloc(), slot());
- reset();
- }
- }
-
- void reset() {
- assert(alloc_.has_value());
- alloc_ = absl::nullopt;
- }
-
- slot_type* slot() const {
- assert(!empty());
- return reinterpret_cast<slot_type*>(std::addressof(slot_space_));
- }
- allocator_type* alloc() { return std::addressof(*alloc_); }
-
- private:
- absl::optional<allocator_type> alloc_ = {};
- alignas(slot_type) mutable unsigned char slot_space_[sizeof(slot_type)] = {};
-};
-
-// For sets.
-template <typename Policy, typename PolicyTraits, typename Alloc,
- typename = void>
-class node_handle : public node_handle_base<PolicyTraits, Alloc> {
- using Base = node_handle_base<PolicyTraits, Alloc>;
-
- public:
- using value_type = typename PolicyTraits::value_type;
-
- constexpr node_handle() {}
-
- value_type& value() const { return PolicyTraits::element(this->slot()); }
-
- private:
- friend struct CommonAccess;
-
- using Base::Base;
-};
-
-// For maps.
-template <typename Policy, typename PolicyTraits, typename Alloc>
-class node_handle<Policy, PolicyTraits, Alloc,
- absl::void_t<typename Policy::mapped_type>>
- : public node_handle_base<PolicyTraits, Alloc> {
- using Base = node_handle_base<PolicyTraits, Alloc>;
- using slot_type = typename PolicyTraits::slot_type;
-
- public:
- using key_type = typename Policy::key_type;
- using mapped_type = typename Policy::mapped_type;
-
- constexpr node_handle() {}
-
- // When C++17 is available, we can use std::launder to provide mutable
- // access to the key. Otherwise, we provide const access.
- auto key() const
- -> decltype(PolicyTraits::mutable_key(std::declval<slot_type*>())) {
- return PolicyTraits::mutable_key(this->slot());
- }
-
- mapped_type& mapped() const {
- return PolicyTraits::value(&PolicyTraits::element(this->slot()));
- }
-
- private:
- friend struct CommonAccess;
-
- using Base::Base;
-};
-
-// Provide access to non-public node-handle functions.
-struct CommonAccess {
- template <typename Node>
- static auto GetSlot(const Node& node) -> decltype(node.slot()) {
- return node.slot();
- }
-
- template <typename Node>
- static void Destroy(Node* node) {
- node->destroy();
- }
-
- template <typename Node>
- static void Reset(Node* node) {
- node->reset();
- }
-
- template <typename T, typename... Args>
- static T Transfer(Args&&... args) {
- return T(typename T::transfer_tag_t{}, std::forward<Args>(args)...);
- }
-
- template <typename T, typename... Args>
- static T Construct(Args&&... args) {
- return T(typename T::construct_tag_t{}, std::forward<Args>(args)...);
- }
-};
-
-// Implement the insert_return_type<> concept of C++17.
-template <class Iterator, class NodeType>
-struct InsertReturnType {
- Iterator position;
- bool inserted;
- NodeType node;
-};
-
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_INTERNAL_COMMON_H_
diff --git a/third_party/abseil-cpp/absl/container/internal/common_policy_traits.h b/third_party/abseil-cpp/absl/container/internal/common_policy_traits.h
deleted file mode 100644
index 0fd4866..0000000
--- a/third_party/abseil-cpp/absl/container/internal/common_policy_traits.h
+++ /dev/null
@@ -1,115 +0,0 @@
-// Copyright 2022 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_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 {
-
-// Defines how slots are initialized/destroyed/moved.
-template <class Policy, class = void>
-struct common_policy_traits {
- // The actual object stored in the container.
- 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;
-
- // PRECONDITION: `slot` is UNINITIALIZED
- // POSTCONDITION: `slot` is INITIALIZED
- template <class Alloc, class... Args>
- static void construct(Alloc* alloc, slot_type* slot, Args&&... args) {
- Policy::construct(alloc, slot, std::forward<Args>(args)...);
- }
-
- // PRECONDITION: `slot` is INITIALIZED
- // POSTCONDITION: `slot` is UNINITIALIZED
- template <class Alloc>
- static void destroy(Alloc* alloc, slot_type* slot) {
- Policy::destroy(alloc, slot);
- }
-
- // Transfers the `old_slot` to `new_slot`. Any memory allocated by the
- // allocator inside `old_slot` to `new_slot` can be transferred.
- //
- // OPTIONAL: defaults to:
- //
- // clone(new_slot, std::move(*old_slot));
- // destroy(old_slot);
- //
- // PRECONDITION: `new_slot` is UNINITIALIZED and `old_slot` is INITIALIZED
- // POSTCONDITION: `new_slot` is INITIALIZED and `old_slot` is
- // UNINITIALIZED
- template <class Alloc>
- static void transfer(Alloc* alloc, slot_type* new_slot, slot_type* old_slot) {
- transfer_impl(alloc, new_slot, old_slot, 0);
- }
-
- // PRECONDITION: `slot` is INITIALIZED
- // POSTCONDITION: `slot` is INITIALIZED
- // Note: we use remove_const_t so that the two overloads have different args
- // in the case of sets with explicitly const value_types.
- 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);
- }
-
- private:
- // Use auto -> decltype as an enabler.
- template <class Alloc, class P = Policy>
- static auto transfer_impl(Alloc* alloc, slot_type* new_slot,
- slot_type* old_slot, int)
- -> decltype((void)P::transfer(alloc, new_slot, old_slot)) {
- P::transfer(alloc, new_slot, old_slot);
- }
- template <class Alloc>
- static void transfer_impl(Alloc* alloc, slot_type* new_slot,
- slot_type* old_slot, char) {
-#if defined(__cpp_lib_launder) && __cpp_lib_launder >= 201606
- if (absl::is_trivially_relocatable<value_type>()) {
- // TODO(b/247130232,b/251814870): remove casts after fixing warnings.
- 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
-
- construct(alloc, new_slot, std::move(element(old_slot)));
- destroy(alloc, old_slot);
- }
-};
-
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_INTERNAL_COMMON_POLICY_TRAITS_H_
diff --git a/third_party/abseil-cpp/absl/container/internal/common_policy_traits_test.cc b/third_party/abseil-cpp/absl/container/internal/common_policy_traits_test.cc
deleted file mode 100644
index 5eaa4aa..0000000
--- a/third_party/abseil-cpp/absl/container/internal/common_policy_traits_test.cc
+++ /dev/null
@@ -1,120 +0,0 @@
-// Copyright 2022 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/container/internal/common_policy_traits.h"
-
-#include <functional>
-#include <memory>
-#include <new>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.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;
-
- static std::function<void(void*, Slot*, Slot)> construct;
- static std::function<void(void*, Slot*)> destroy;
-
- static std::function<Slot&(Slot*)> element;
-};
-
-std::function<void(void*, Slot*, Slot)> PolicyWithoutOptionalOps::construct;
-std::function<void(void*, Slot*)> PolicyWithoutOptionalOps::destroy;
-
-std::function<Slot&(Slot*)> PolicyWithoutOptionalOps::element;
-
-struct PolicyWithOptionalOps : PolicyWithoutOptionalOps {
- static std::function<void(void*, Slot*, Slot*)> transfer;
-};
-
-std::function<void(void*, Slot*, Slot*)> PolicyWithOptionalOps::transfer;
-
-struct Test : ::testing::Test {
- Test() {
- PolicyWithoutOptionalOps::construct = [&](void* a1, Slot* a2, Slot a3) {
- construct.Call(a1, a2, std::move(a3));
- };
- PolicyWithoutOptionalOps::destroy = [&](void* a1, Slot* a2) {
- destroy.Call(a1, a2);
- };
-
- PolicyWithoutOptionalOps::element = [&](Slot* a1) -> Slot& {
- return element.Call(a1);
- };
-
- PolicyWithOptionalOps::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);
-}
-
-} // namespace
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/container/internal/compressed_tuple.h b/third_party/abseil-cpp/absl/container/internal/compressed_tuple.h
deleted file mode 100644
index 5ebe164..0000000
--- a/third_party/abseil-cpp/absl/container/internal/compressed_tuple.h
+++ /dev/null
@@ -1,290 +0,0 @@
-// Copyright 2018 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.
-//
-// Helper class to perform the Empty Base Optimization.
-// Ts can contain classes and non-classes, empty or not. For the ones that
-// are empty classes, we perform the optimization. If all types in Ts are empty
-// classes, then CompressedTuple<Ts...> is itself an empty class.
-//
-// To access the members, use member get<N>() function.
-//
-// Eg:
-// absl::container_internal::CompressedTuple<int, T1, T2, T3> value(7, t1, t2,
-// t3);
-// assert(value.get<0>() == 7);
-// T1& t1 = value.get<1>();
-// const T2& t2 = value.get<2>();
-// ...
-//
-// https://en.cppreference.com/w/cpp/language/ebo
-
-#ifndef ABSL_CONTAINER_INTERNAL_COMPRESSED_TUPLE_H_
-#define ABSL_CONTAINER_INTERNAL_COMPRESSED_TUPLE_H_
-
-#include <initializer_list>
-#include <tuple>
-#include <type_traits>
-#include <utility>
-
-#include "absl/utility/utility.h"
-
-#if defined(_MSC_VER) && !defined(__NVCC__)
-// We need to mark these classes with this declspec to ensure that
-// CompressedTuple happens.
-#define ABSL_INTERNAL_COMPRESSED_TUPLE_DECLSPEC __declspec(empty_bases)
-#else
-#define ABSL_INTERNAL_COMPRESSED_TUPLE_DECLSPEC
-#endif
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-
-template <typename... Ts>
-class CompressedTuple;
-
-namespace internal_compressed_tuple {
-
-template <typename D, size_t I>
-struct Elem;
-template <typename... B, size_t I>
-struct Elem<CompressedTuple<B...>, I>
- : std::tuple_element<I, std::tuple<B...>> {};
-template <typename D, size_t I>
-using ElemT = typename Elem<D, I>::type;
-
-// Use the __is_final intrinsic if available. Where it's not available, classes
-// declared with the 'final' specifier cannot be used as CompressedTuple
-// elements.
-// TODO(sbenza): Replace this with std::is_final in C++14.
-template <typename T>
-constexpr bool IsFinal() {
-#if defined(__clang__) || defined(__GNUC__)
- return __is_final(T);
-#else
- return false;
-#endif
-}
-
-// We can't use EBCO on other CompressedTuples because that would mean that we
-// derive from multiple Storage<> instantiations with the same I parameter,
-// and potentially from multiple identical Storage<> instantiations. So anytime
-// we use type inheritance rather than encapsulation, we mark
-// CompressedTupleImpl, to make this easy to detect.
-struct uses_inheritance {};
-
-template <typename T>
-constexpr bool ShouldUseBase() {
- return std::is_class<T>::value && std::is_empty<T>::value && !IsFinal<T>() &&
- !std::is_base_of<uses_inheritance, T>::value;
-}
-
-// The storage class provides two specializations:
-// - For empty classes, it stores T as a base class.
-// - For everything else, it stores T as a member.
-template <typename T, size_t I,
-#if defined(_MSC_VER)
- bool UseBase =
- ShouldUseBase<typename std::enable_if<true, T>::type>()>
-#else
- bool UseBase = ShouldUseBase<T>()>
-#endif
-struct Storage {
- T value;
- constexpr Storage() = default;
- template <typename V>
- explicit constexpr Storage(absl::in_place_t, V&& v)
- : value(absl::forward<V>(v)) {}
- constexpr const T& get() const& { return value; }
- T& get() & { return value; }
- constexpr const T&& get() const&& { return absl::move(*this).value; }
- T&& get() && { return std::move(*this).value; }
-};
-
-template <typename T, size_t I>
-struct ABSL_INTERNAL_COMPRESSED_TUPLE_DECLSPEC Storage<T, I, true> : T {
- constexpr Storage() = default;
-
- template <typename V>
- explicit constexpr Storage(absl::in_place_t, V&& v)
- : T(absl::forward<V>(v)) {}
-
- constexpr const T& get() const& { return *this; }
- T& get() & { return *this; }
- constexpr const T&& get() const&& { return absl::move(*this); }
- T&& get() && { return std::move(*this); }
-};
-
-template <typename D, typename I, bool ShouldAnyUseBase>
-struct ABSL_INTERNAL_COMPRESSED_TUPLE_DECLSPEC CompressedTupleImpl;
-
-template <typename... Ts, size_t... I, bool ShouldAnyUseBase>
-struct ABSL_INTERNAL_COMPRESSED_TUPLE_DECLSPEC CompressedTupleImpl<
- CompressedTuple<Ts...>, absl::index_sequence<I...>, ShouldAnyUseBase>
- // We use the dummy identity function through std::integral_constant to
- // convince MSVC of accepting and expanding I in that context. Without it
- // you would get:
- // error C3548: 'I': parameter pack cannot be used in this context
- : uses_inheritance,
- Storage<Ts, std::integral_constant<size_t, I>::value>... {
- constexpr CompressedTupleImpl() = default;
- template <typename... Vs>
- explicit constexpr CompressedTupleImpl(absl::in_place_t, Vs&&... args)
- : Storage<Ts, I>(absl::in_place, absl::forward<Vs>(args))... {}
- friend CompressedTuple<Ts...>;
-};
-
-template <typename... Ts, size_t... I>
-struct ABSL_INTERNAL_COMPRESSED_TUPLE_DECLSPEC CompressedTupleImpl<
- CompressedTuple<Ts...>, absl::index_sequence<I...>, false>
- // We use the dummy identity function as above...
- : Storage<Ts, std::integral_constant<size_t, I>::value, false>... {
- constexpr CompressedTupleImpl() = default;
- template <typename... Vs>
- explicit constexpr CompressedTupleImpl(absl::in_place_t, Vs&&... args)
- : Storage<Ts, I, false>(absl::in_place, absl::forward<Vs>(args))... {}
- friend CompressedTuple<Ts...>;
-};
-
-std::false_type Or(std::initializer_list<std::false_type>);
-std::true_type Or(std::initializer_list<bool>);
-
-// MSVC requires this to be done separately rather than within the declaration
-// of CompressedTuple below.
-template <typename... Ts>
-constexpr bool ShouldAnyUseBase() {
- return decltype(
- Or({std::integral_constant<bool, ShouldUseBase<Ts>()>()...})){};
-}
-
-template <typename T, typename V>
-using TupleElementMoveConstructible =
- typename std::conditional<std::is_reference<T>::value,
- std::is_convertible<V, T>,
- std::is_constructible<T, V&&>>::type;
-
-template <bool SizeMatches, class T, class... Vs>
-struct TupleMoveConstructible : std::false_type {};
-
-template <class... Ts, class... Vs>
-struct TupleMoveConstructible<true, CompressedTuple<Ts...>, Vs...>
- : std::integral_constant<
- bool, absl::conjunction<
- TupleElementMoveConstructible<Ts, Vs&&>...>::value> {};
-
-template <typename T>
-struct compressed_tuple_size;
-
-template <typename... Es>
-struct compressed_tuple_size<CompressedTuple<Es...>>
- : public std::integral_constant<std::size_t, sizeof...(Es)> {};
-
-template <class T, class... Vs>
-struct TupleItemsMoveConstructible
- : std::integral_constant<
- bool, TupleMoveConstructible<compressed_tuple_size<T>::value ==
- sizeof...(Vs),
- T, Vs...>::value> {};
-
-} // namespace internal_compressed_tuple
-
-// Helper class to perform the Empty Base Class Optimization.
-// Ts can contain classes and non-classes, empty or not. For the ones that
-// are empty classes, we perform the CompressedTuple. If all types in Ts are
-// empty classes, then CompressedTuple<Ts...> is itself an empty class. (This
-// does not apply when one or more of those empty classes is itself an empty
-// CompressedTuple.)
-//
-// To access the members, use member .get<N>() function.
-//
-// Eg:
-// absl::container_internal::CompressedTuple<int, T1, T2, T3> value(7, t1, t2,
-// t3);
-// assert(value.get<0>() == 7);
-// T1& t1 = value.get<1>();
-// const T2& t2 = value.get<2>();
-// ...
-//
-// https://en.cppreference.com/w/cpp/language/ebo
-template <typename... Ts>
-class ABSL_INTERNAL_COMPRESSED_TUPLE_DECLSPEC CompressedTuple
- : private internal_compressed_tuple::CompressedTupleImpl<
- CompressedTuple<Ts...>, absl::index_sequence_for<Ts...>,
- internal_compressed_tuple::ShouldAnyUseBase<Ts...>()> {
- private:
- template <int I>
- using ElemT = internal_compressed_tuple::ElemT<CompressedTuple, I>;
-
- template <int I>
- using StorageT = internal_compressed_tuple::Storage<ElemT<I>, I>;
-
- public:
- // There seems to be a bug in MSVC dealing in which using '=default' here will
- // cause the compiler to ignore the body of other constructors. The work-
- // around is to explicitly implement the default constructor.
-#if defined(_MSC_VER)
- constexpr CompressedTuple() : CompressedTuple::CompressedTupleImpl() {}
-#else
- constexpr CompressedTuple() = default;
-#endif
- explicit constexpr CompressedTuple(const Ts&... base)
- : CompressedTuple::CompressedTupleImpl(absl::in_place, base...) {}
-
- template <typename First, typename... Vs,
- absl::enable_if_t<
- absl::conjunction<
- // Ensure we are not hiding default copy/move constructors.
- absl::negation<std::is_same<void(CompressedTuple),
- void(absl::decay_t<First>)>>,
- internal_compressed_tuple::TupleItemsMoveConstructible<
- CompressedTuple<Ts...>, First, Vs...>>::value,
- bool> = true>
- explicit constexpr CompressedTuple(First&& first, Vs&&... base)
- : CompressedTuple::CompressedTupleImpl(absl::in_place,
- absl::forward<First>(first),
- absl::forward<Vs>(base)...) {}
-
- template <int I>
- ElemT<I>& get() & {
- return StorageT<I>::get();
- }
-
- template <int I>
- constexpr const ElemT<I>& get() const& {
- return StorageT<I>::get();
- }
-
- template <int I>
- ElemT<I>&& get() && {
- return std::move(*this).StorageT<I>::get();
- }
-
- template <int I>
- constexpr const ElemT<I>&& get() const&& {
- return absl::move(*this).StorageT<I>::get();
- }
-};
-
-// Explicit specialization for a zero-element tuple
-// (needed to avoid ambiguous overloads for the default constructor).
-template <>
-class ABSL_INTERNAL_COMPRESSED_TUPLE_DECLSPEC CompressedTuple<> {};
-
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#undef ABSL_INTERNAL_COMPRESSED_TUPLE_DECLSPEC
-
-#endif // ABSL_CONTAINER_INTERNAL_COMPRESSED_TUPLE_H_
diff --git a/third_party/abseil-cpp/absl/container/internal/compressed_tuple_test.cc b/third_party/abseil-cpp/absl/container/internal/compressed_tuple_test.cc
deleted file mode 100644
index 74111f9..0000000
--- a/third_party/abseil-cpp/absl/container/internal/compressed_tuple_test.cc
+++ /dev/null
@@ -1,419 +0,0 @@
-// Copyright 2018 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/container/internal/compressed_tuple.h"
-
-#include <memory>
-#include <string>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/container/internal/test_instance_tracker.h"
-#include "absl/memory/memory.h"
-#include "absl/types/any.h"
-#include "absl/types/optional.h"
-#include "absl/utility/utility.h"
-
-// These are declared at global scope purely so that error messages
-// are smaller and easier to understand.
-enum class CallType { kConstRef, kConstMove };
-
-template <int>
-struct Empty {
- constexpr CallType value() const& { return CallType::kConstRef; }
- constexpr CallType value() const&& { return CallType::kConstMove; }
-};
-
-template <typename T>
-struct NotEmpty {
- T value;
-};
-
-template <typename T, typename U>
-struct TwoValues {
- T value1;
- U value2;
-};
-
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-namespace {
-
-using absl::test_internal::CopyableMovableInstance;
-using absl::test_internal::InstanceTracker;
-
-TEST(CompressedTupleTest, Sizeof) {
- EXPECT_EQ(sizeof(int), sizeof(CompressedTuple<int>));
- EXPECT_EQ(sizeof(int), sizeof(CompressedTuple<int, Empty<0>>));
- EXPECT_EQ(sizeof(int), sizeof(CompressedTuple<int, Empty<0>, Empty<1>>));
- EXPECT_EQ(sizeof(int),
- sizeof(CompressedTuple<int, Empty<0>, Empty<1>, Empty<2>>));
-
- EXPECT_EQ(sizeof(TwoValues<int, double>),
- sizeof(CompressedTuple<int, NotEmpty<double>>));
- EXPECT_EQ(sizeof(TwoValues<int, double>),
- sizeof(CompressedTuple<int, Empty<0>, NotEmpty<double>>));
- EXPECT_EQ(sizeof(TwoValues<int, double>),
- sizeof(CompressedTuple<int, Empty<0>, NotEmpty<double>, Empty<1>>));
-}
-
-TEST(CompressedTupleTest, OneMoveOnRValueConstructionTemp) {
- InstanceTracker tracker;
- CompressedTuple<CopyableMovableInstance> x1(CopyableMovableInstance(1));
- EXPECT_EQ(tracker.instances(), 1);
- EXPECT_EQ(tracker.copies(), 0);
- EXPECT_LE(tracker.moves(), 1);
- EXPECT_EQ(x1.get<0>().value(), 1);
-}
-
-TEST(CompressedTupleTest, OneMoveOnRValueConstructionMove) {
- InstanceTracker tracker;
-
- CopyableMovableInstance i1(1);
- CompressedTuple<CopyableMovableInstance> x1(std::move(i1));
- EXPECT_EQ(tracker.instances(), 2);
- EXPECT_EQ(tracker.copies(), 0);
- EXPECT_LE(tracker.moves(), 1);
- EXPECT_EQ(x1.get<0>().value(), 1);
-}
-
-TEST(CompressedTupleTest, OneMoveOnRValueConstructionMixedTypes) {
- InstanceTracker tracker;
- CopyableMovableInstance i1(1);
- CopyableMovableInstance i2(2);
- Empty<0> empty;
- CompressedTuple<CopyableMovableInstance, CopyableMovableInstance&, Empty<0>>
- x1(std::move(i1), i2, empty);
- EXPECT_EQ(x1.get<0>().value(), 1);
- EXPECT_EQ(x1.get<1>().value(), 2);
- EXPECT_EQ(tracker.copies(), 0);
- EXPECT_EQ(tracker.moves(), 1);
-}
-
-struct IncompleteType;
-CompressedTuple<CopyableMovableInstance, IncompleteType&, Empty<0>>
-MakeWithIncomplete(CopyableMovableInstance i1,
- IncompleteType& t, // NOLINT
- Empty<0> empty) {
- return CompressedTuple<CopyableMovableInstance, IncompleteType&, Empty<0>>{
- std::move(i1), t, empty};
-}
-
-struct IncompleteType {};
-TEST(CompressedTupleTest, OneMoveOnRValueConstructionWithIncompleteType) {
- InstanceTracker tracker;
- CopyableMovableInstance i1(1);
- Empty<0> empty;
- struct DerivedType : IncompleteType {int value = 0;};
- DerivedType fd;
- fd.value = 7;
-
- CompressedTuple<CopyableMovableInstance, IncompleteType&, Empty<0>> x1 =
- MakeWithIncomplete(std::move(i1), fd, empty);
-
- EXPECT_EQ(x1.get<0>().value(), 1);
- EXPECT_EQ(static_cast<DerivedType&>(x1.get<1>()).value, 7);
-
- EXPECT_EQ(tracker.copies(), 0);
- EXPECT_EQ(tracker.moves(), 2);
-}
-
-TEST(CompressedTupleTest,
- OneMoveOnRValueConstructionMixedTypes_BraceInitPoisonPillExpected) {
- InstanceTracker tracker;
- CopyableMovableInstance i1(1);
- CopyableMovableInstance i2(2);
- CompressedTuple<CopyableMovableInstance, CopyableMovableInstance&, Empty<0>>
- x1(std::move(i1), i2, {}); // NOLINT
- EXPECT_EQ(x1.get<0>().value(), 1);
- EXPECT_EQ(x1.get<1>().value(), 2);
- EXPECT_EQ(tracker.instances(), 3);
- // We are forced into the `const Ts&...` constructor (invoking copies)
- // because we need it to deduce the type of `{}`.
- // std::tuple also has this behavior.
- // Note, this test is proof that this is expected behavior, but it is not
- // _desired_ behavior.
- EXPECT_EQ(tracker.copies(), 1);
- EXPECT_EQ(tracker.moves(), 0);
-}
-
-TEST(CompressedTupleTest, OneCopyOnLValueConstruction) {
- InstanceTracker tracker;
- CopyableMovableInstance i1(1);
-
- CompressedTuple<CopyableMovableInstance> x1(i1);
- EXPECT_EQ(tracker.copies(), 1);
- EXPECT_EQ(tracker.moves(), 0);
-
- tracker.ResetCopiesMovesSwaps();
-
- CopyableMovableInstance i2(2);
- const CopyableMovableInstance& i2_ref = i2;
- CompressedTuple<CopyableMovableInstance> x2(i2_ref);
- EXPECT_EQ(tracker.copies(), 1);
- EXPECT_EQ(tracker.moves(), 0);
-}
-
-TEST(CompressedTupleTest, OneMoveOnRValueAccess) {
- InstanceTracker tracker;
- CopyableMovableInstance i1(1);
- CompressedTuple<CopyableMovableInstance> x(std::move(i1));
- tracker.ResetCopiesMovesSwaps();
-
- CopyableMovableInstance i2 = std::move(x).get<0>();
- EXPECT_EQ(tracker.copies(), 0);
- EXPECT_EQ(tracker.moves(), 1);
-}
-
-TEST(CompressedTupleTest, OneCopyOnLValueAccess) {
- InstanceTracker tracker;
-
- CompressedTuple<CopyableMovableInstance> x(CopyableMovableInstance(0));
- EXPECT_EQ(tracker.copies(), 0);
- EXPECT_EQ(tracker.moves(), 1);
-
- CopyableMovableInstance t = x.get<0>();
- EXPECT_EQ(tracker.copies(), 1);
- EXPECT_EQ(tracker.moves(), 1);
-}
-
-TEST(CompressedTupleTest, ZeroCopyOnRefAccess) {
- InstanceTracker tracker;
-
- CompressedTuple<CopyableMovableInstance> x(CopyableMovableInstance(0));
- EXPECT_EQ(tracker.copies(), 0);
- EXPECT_EQ(tracker.moves(), 1);
-
- CopyableMovableInstance& t1 = x.get<0>();
- const CopyableMovableInstance& t2 = x.get<0>();
- EXPECT_EQ(tracker.copies(), 0);
- EXPECT_EQ(tracker.moves(), 1);
- EXPECT_EQ(t1.value(), 0);
- EXPECT_EQ(t2.value(), 0);
-}
-
-TEST(CompressedTupleTest, Access) {
- struct S {
- std::string x;
- };
- CompressedTuple<int, Empty<0>, S> x(7, {}, S{"ABC"});
- EXPECT_EQ(sizeof(x), sizeof(TwoValues<int, S>));
- EXPECT_EQ(7, x.get<0>());
- EXPECT_EQ("ABC", x.get<2>().x);
-}
-
-TEST(CompressedTupleTest, NonClasses) {
- CompressedTuple<int, const char*> x(7, "ABC");
- EXPECT_EQ(7, x.get<0>());
- EXPECT_STREQ("ABC", x.get<1>());
-}
-
-TEST(CompressedTupleTest, MixClassAndNonClass) {
- CompressedTuple<int, const char*, Empty<0>, NotEmpty<double>> x(7, "ABC", {},
- {1.25});
- struct Mock {
- int v;
- const char* p;
- double d;
- };
- EXPECT_EQ(sizeof(x), sizeof(Mock));
- EXPECT_EQ(7, x.get<0>());
- EXPECT_STREQ("ABC", x.get<1>());
- EXPECT_EQ(1.25, x.get<3>().value);
-}
-
-TEST(CompressedTupleTest, Nested) {
- CompressedTuple<int, CompressedTuple<int>,
- CompressedTuple<int, CompressedTuple<int>>>
- x(1, CompressedTuple<int>(2),
- CompressedTuple<int, CompressedTuple<int>>(3, CompressedTuple<int>(4)));
- EXPECT_EQ(1, x.get<0>());
- EXPECT_EQ(2, x.get<1>().get<0>());
- EXPECT_EQ(3, x.get<2>().get<0>());
- EXPECT_EQ(4, x.get<2>().get<1>().get<0>());
-
- CompressedTuple<Empty<0>, Empty<0>,
- CompressedTuple<Empty<0>, CompressedTuple<Empty<0>>>>
- y;
- std::set<Empty<0>*> empties{&y.get<0>(), &y.get<1>(), &y.get<2>().get<0>(),
- &y.get<2>().get<1>().get<0>()};
-#ifdef _MSC_VER
- // MSVC has a bug where many instances of the same base class are layed out in
- // the same address when using __declspec(empty_bases).
- // This will be fixed in a future version of MSVC.
- int expected = 1;
-#else
- int expected = 4;
-#endif
- EXPECT_EQ(expected, sizeof(y));
- EXPECT_EQ(expected, empties.size());
- EXPECT_EQ(sizeof(y), sizeof(Empty<0>) * empties.size());
-
- EXPECT_EQ(4 * sizeof(char),
- sizeof(CompressedTuple<CompressedTuple<char, char>,
- CompressedTuple<char, char>>));
- EXPECT_TRUE((std::is_empty<CompressedTuple<Empty<0>, Empty<1>>>::value));
-
- // Make sure everything still works when things are nested.
- struct CT_Empty : CompressedTuple<Empty<0>> {};
- CompressedTuple<Empty<0>, CT_Empty> nested_empty;
- auto contained = nested_empty.get<0>();
- auto nested = nested_empty.get<1>().get<0>();
- EXPECT_TRUE((std::is_same<decltype(contained), decltype(nested)>::value));
-}
-
-TEST(CompressedTupleTest, Reference) {
- int i = 7;
- std::string s = "Very long string that goes in the heap";
- CompressedTuple<int, int&, std::string, std::string&> x(i, i, s, s);
-
- // Sanity check. We should have not moved from `s`
- EXPECT_EQ(s, "Very long string that goes in the heap");
-
- EXPECT_EQ(x.get<0>(), x.get<1>());
- EXPECT_NE(&x.get<0>(), &x.get<1>());
- EXPECT_EQ(&x.get<1>(), &i);
-
- EXPECT_EQ(x.get<2>(), x.get<3>());
- EXPECT_NE(&x.get<2>(), &x.get<3>());
- EXPECT_EQ(&x.get<3>(), &s);
-}
-
-TEST(CompressedTupleTest, NoElements) {
- CompressedTuple<> x;
- static_cast<void>(x); // Silence -Wunused-variable.
- EXPECT_TRUE(std::is_empty<CompressedTuple<>>::value);
-}
-
-TEST(CompressedTupleTest, MoveOnlyElements) {
- CompressedTuple<std::unique_ptr<std::string>> str_tup(
- absl::make_unique<std::string>("str"));
-
- CompressedTuple<CompressedTuple<std::unique_ptr<std::string>>,
- std::unique_ptr<int>>
- x(std::move(str_tup), absl::make_unique<int>(5));
-
- EXPECT_EQ(*x.get<0>().get<0>(), "str");
- EXPECT_EQ(*x.get<1>(), 5);
-
- std::unique_ptr<std::string> x0 = std::move(x.get<0>()).get<0>();
- std::unique_ptr<int> x1 = std::move(x).get<1>();
-
- EXPECT_EQ(*x0, "str");
- EXPECT_EQ(*x1, 5);
-}
-
-TEST(CompressedTupleTest, MoveConstructionMoveOnlyElements) {
- CompressedTuple<std::unique_ptr<std::string>> base(
- absl::make_unique<std::string>("str"));
- EXPECT_EQ(*base.get<0>(), "str");
-
- CompressedTuple<std::unique_ptr<std::string>> copy(std::move(base));
- EXPECT_EQ(*copy.get<0>(), "str");
-}
-
-TEST(CompressedTupleTest, AnyElements) {
- any a(std::string("str"));
- CompressedTuple<any, any&> x(any(5), a);
- EXPECT_EQ(absl::any_cast<int>(x.get<0>()), 5);
- EXPECT_EQ(absl::any_cast<std::string>(x.get<1>()), "str");
-
- a = 0.5f;
- EXPECT_EQ(absl::any_cast<float>(x.get<1>()), 0.5);
-}
-
-TEST(CompressedTupleTest, Constexpr) {
- struct NonTrivialStruct {
- constexpr NonTrivialStruct() = default;
- constexpr int value() const { return v; }
- int v = 5;
- };
- struct TrivialStruct {
- TrivialStruct() = default;
- constexpr int value() const { return v; }
- int v;
- };
- constexpr CompressedTuple<int, double, CompressedTuple<int>, Empty<0>> x(
- 7, 1.25, CompressedTuple<int>(5), {});
- constexpr int x0 = x.get<0>();
- constexpr double x1 = x.get<1>();
- constexpr int x2 = x.get<2>().get<0>();
- constexpr CallType x3 = x.get<3>().value();
-
- EXPECT_EQ(x0, 7);
- EXPECT_EQ(x1, 1.25);
- EXPECT_EQ(x2, 5);
- EXPECT_EQ(x3, CallType::kConstRef);
-
-#if !defined(__GNUC__) || defined(__clang__) || __GNUC__ > 4
- constexpr CompressedTuple<Empty<0>, TrivialStruct, int> trivial = {};
- constexpr CallType trivial0 = trivial.get<0>().value();
- constexpr int trivial1 = trivial.get<1>().value();
- constexpr int trivial2 = trivial.get<2>();
-
- EXPECT_EQ(trivial0, CallType::kConstRef);
- EXPECT_EQ(trivial1, 0);
- EXPECT_EQ(trivial2, 0);
-#endif
-
- constexpr CompressedTuple<Empty<0>, NonTrivialStruct, absl::optional<int>>
- non_trivial = {};
- constexpr CallType non_trivial0 = non_trivial.get<0>().value();
- constexpr int non_trivial1 = non_trivial.get<1>().value();
- constexpr absl::optional<int> non_trivial2 = non_trivial.get<2>();
-
- EXPECT_EQ(non_trivial0, CallType::kConstRef);
- EXPECT_EQ(non_trivial1, 5);
- EXPECT_EQ(non_trivial2, absl::nullopt);
-
- static constexpr char data[] = "DEF";
- constexpr CompressedTuple<const char*> z(data);
- constexpr const char* z1 = z.get<0>();
- EXPECT_EQ(std::string(z1), std::string(data));
-
-#if defined(__clang__)
- // An apparent bug in earlier versions of gcc claims these are ambiguous.
- constexpr int x2m = absl::move(x.get<2>()).get<0>();
- constexpr CallType x3m = absl::move(x).get<3>().value();
- EXPECT_EQ(x2m, 5);
- EXPECT_EQ(x3m, CallType::kConstMove);
-#endif
-}
-
-#if defined(__clang__) || defined(__GNUC__)
-TEST(CompressedTupleTest, EmptyFinalClass) {
- struct S final {
- int f() const { return 5; }
- };
- CompressedTuple<S> x;
- EXPECT_EQ(x.get<0>().f(), 5);
-}
-#endif
-
-// TODO(b/214288561): enable this test.
-TEST(CompressedTupleTest, DISABLED_NestedEbo) {
- struct Empty1 {};
- struct Empty2 {};
- CompressedTuple<Empty1, CompressedTuple<Empty2>, int> x;
- CompressedTuple<Empty1, Empty2, int> y;
- // Currently fails with sizeof(x) == 8, sizeof(y) == 4.
- EXPECT_EQ(sizeof(x), sizeof(y));
-}
-
-} // namespace
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/container/internal/container_memory.h b/third_party/abseil-cpp/absl/container/internal/container_memory.h
deleted file mode 100644
index bfa4ff9..0000000
--- a/third_party/abseil-cpp/absl/container/internal/container_memory.h
+++ /dev/null
@@ -1,454 +0,0 @@
-// Copyright 2018 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_CONTAINER_INTERNAL_CONTAINER_MEMORY_H_
-#define ABSL_CONTAINER_INTERNAL_CONTAINER_MEMORY_H_
-
-#include <cassert>
-#include <cstddef>
-#include <cstring>
-#include <memory>
-#include <new>
-#include <tuple>
-#include <type_traits>
-#include <utility>
-
-#include "absl/base/config.h"
-#include "absl/memory/memory.h"
-#include "absl/meta/type_traits.h"
-#include "absl/utility/utility.h"
-
-#ifdef ABSL_HAVE_ADDRESS_SANITIZER
-#include <sanitizer/asan_interface.h>
-#endif
-
-#ifdef ABSL_HAVE_MEMORY_SANITIZER
-#include <sanitizer/msan_interface.h>
-#endif
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-
-template <size_t Alignment>
-struct alignas(Alignment) AlignedType {};
-
-// Allocates at least n bytes aligned to the specified alignment.
-// Alignment must be a power of 2. It must be positive.
-//
-// Note that many allocators don't honor alignment requirements above certain
-// threshold (usually either alignof(std::max_align_t) or alignof(void*)).
-// Allocate() doesn't apply alignment corrections. If the underlying allocator
-// returns insufficiently alignment pointer, that's what you are going to get.
-template <size_t Alignment, class Alloc>
-void* Allocate(Alloc* alloc, size_t n) {
- static_assert(Alignment > 0, "");
- assert(n && "n must be positive");
- using M = AlignedType<Alignment>;
- using A = typename absl::allocator_traits<Alloc>::template rebind_alloc<M>;
- using AT = typename absl::allocator_traits<Alloc>::template rebind_traits<M>;
- // On macOS, "mem_alloc" is a #define with one argument defined in
- // rpc/types.h, so we can't name the variable "mem_alloc" and initialize it
- // with the "foo(bar)" syntax.
- A my_mem_alloc(*alloc);
- void* p = AT::allocate(my_mem_alloc, (n + sizeof(M) - 1) / sizeof(M));
- assert(reinterpret_cast<uintptr_t>(p) % Alignment == 0 &&
- "allocator does not respect alignment");
- return p;
-}
-
-// The pointer must have been previously obtained by calling
-// Allocate<Alignment>(alloc, n).
-template <size_t Alignment, class Alloc>
-void Deallocate(Alloc* alloc, void* p, size_t n) {
- static_assert(Alignment > 0, "");
- assert(n && "n must be positive");
- using M = AlignedType<Alignment>;
- using A = typename absl::allocator_traits<Alloc>::template rebind_alloc<M>;
- using AT = typename absl::allocator_traits<Alloc>::template rebind_traits<M>;
- // On macOS, "mem_alloc" is a #define with one argument defined in
- // rpc/types.h, so we can't name the variable "mem_alloc" and initialize it
- // with the "foo(bar)" syntax.
- A my_mem_alloc(*alloc);
- AT::deallocate(my_mem_alloc, static_cast<M*>(p),
- (n + sizeof(M) - 1) / sizeof(M));
-}
-
-namespace memory_internal {
-
-// Constructs T into uninitialized storage pointed by `ptr` using the args
-// specified in the tuple.
-template <class Alloc, class T, class Tuple, size_t... I>
-void ConstructFromTupleImpl(Alloc* alloc, T* ptr, Tuple&& t,
- absl::index_sequence<I...>) {
- absl::allocator_traits<Alloc>::construct(
- *alloc, ptr, std::get<I>(std::forward<Tuple>(t))...);
-}
-
-template <class T, class F>
-struct WithConstructedImplF {
- template <class... Args>
- decltype(std::declval<F>()(std::declval<T>())) operator()(
- Args&&... args) const {
- return std::forward<F>(f)(T(std::forward<Args>(args)...));
- }
- F&& f;
-};
-
-template <class T, class Tuple, size_t... Is, class F>
-decltype(std::declval<F>()(std::declval<T>())) WithConstructedImpl(
- Tuple&& t, absl::index_sequence<Is...>, F&& f) {
- return WithConstructedImplF<T, F>{std::forward<F>(f)}(
- std::get<Is>(std::forward<Tuple>(t))...);
-}
-
-template <class T, size_t... Is>
-auto TupleRefImpl(T&& t, absl::index_sequence<Is...>)
- -> decltype(std::forward_as_tuple(std::get<Is>(std::forward<T>(t))...)) {
- return std::forward_as_tuple(std::get<Is>(std::forward<T>(t))...);
-}
-
-// Returns a tuple of references to the elements of the input tuple. T must be a
-// tuple.
-template <class T>
-auto TupleRef(T&& t) -> decltype(
- TupleRefImpl(std::forward<T>(t),
- absl::make_index_sequence<
- std::tuple_size<typename std::decay<T>::type>::value>())) {
- return TupleRefImpl(
- std::forward<T>(t),
- absl::make_index_sequence<
- std::tuple_size<typename std::decay<T>::type>::value>());
-}
-
-template <class F, class K, class V>
-decltype(std::declval<F>()(std::declval<const K&>(), std::piecewise_construct,
- std::declval<std::tuple<K>>(), std::declval<V>()))
-DecomposePairImpl(F&& f, std::pair<std::tuple<K>, V> p) {
- const auto& key = std::get<0>(p.first);
- return std::forward<F>(f)(key, std::piecewise_construct, std::move(p.first),
- std::move(p.second));
-}
-
-} // namespace memory_internal
-
-// Constructs T into uninitialized storage pointed by `ptr` using the args
-// specified in the tuple.
-template <class Alloc, class T, class Tuple>
-void ConstructFromTuple(Alloc* alloc, T* ptr, Tuple&& t) {
- memory_internal::ConstructFromTupleImpl(
- alloc, ptr, std::forward<Tuple>(t),
- absl::make_index_sequence<
- std::tuple_size<typename std::decay<Tuple>::type>::value>());
-}
-
-// Constructs T using the args specified in the tuple and calls F with the
-// constructed value.
-template <class T, class Tuple, class F>
-decltype(std::declval<F>()(std::declval<T>())) WithConstructed(
- Tuple&& t, F&& f) {
- return memory_internal::WithConstructedImpl<T>(
- std::forward<Tuple>(t),
- absl::make_index_sequence<
- std::tuple_size<typename std::decay<Tuple>::type>::value>(),
- std::forward<F>(f));
-}
-
-// Given arguments of an std::pair's consructor, PairArgs() returns a pair of
-// tuples with references to the passed arguments. The tuples contain
-// constructor arguments for the first and the second elements of the pair.
-//
-// The following two snippets are equivalent.
-//
-// 1. std::pair<F, S> p(args...);
-//
-// 2. auto a = PairArgs(args...);
-// std::pair<F, S> p(std::piecewise_construct,
-// std::move(a.first), std::move(a.second));
-inline std::pair<std::tuple<>, std::tuple<>> PairArgs() { return {}; }
-template <class F, class S>
-std::pair<std::tuple<F&&>, std::tuple<S&&>> PairArgs(F&& f, S&& s) {
- return {std::piecewise_construct, std::forward_as_tuple(std::forward<F>(f)),
- std::forward_as_tuple(std::forward<S>(s))};
-}
-template <class F, class S>
-std::pair<std::tuple<const F&>, std::tuple<const S&>> PairArgs(
- const std::pair<F, S>& p) {
- return PairArgs(p.first, p.second);
-}
-template <class F, class S>
-std::pair<std::tuple<F&&>, std::tuple<S&&>> PairArgs(std::pair<F, S>&& p) {
- return PairArgs(std::forward<F>(p.first), std::forward<S>(p.second));
-}
-template <class F, class S>
-auto PairArgs(std::piecewise_construct_t, F&& f, S&& s)
- -> decltype(std::make_pair(memory_internal::TupleRef(std::forward<F>(f)),
- memory_internal::TupleRef(std::forward<S>(s)))) {
- return std::make_pair(memory_internal::TupleRef(std::forward<F>(f)),
- memory_internal::TupleRef(std::forward<S>(s)));
-}
-
-// A helper function for implementing apply() in map policies.
-template <class F, class... Args>
-auto DecomposePair(F&& f, Args&&... args)
- -> decltype(memory_internal::DecomposePairImpl(
- std::forward<F>(f), PairArgs(std::forward<Args>(args)...))) {
- return memory_internal::DecomposePairImpl(
- std::forward<F>(f), PairArgs(std::forward<Args>(args)...));
-}
-
-// A helper function for implementing apply() in set policies.
-template <class F, class Arg>
-decltype(std::declval<F>()(std::declval<const Arg&>(), std::declval<Arg>()))
-DecomposeValue(F&& f, Arg&& arg) {
- const auto& key = arg;
- return std::forward<F>(f)(key, std::forward<Arg>(arg));
-}
-
-// Helper functions for asan and msan.
-inline void SanitizerPoisonMemoryRegion(const void* m, size_t s) {
-#ifdef ABSL_HAVE_ADDRESS_SANITIZER
- ASAN_POISON_MEMORY_REGION(m, s);
-#endif
-#ifdef ABSL_HAVE_MEMORY_SANITIZER
- __msan_poison(m, s);
-#endif
- (void)m;
- (void)s;
-}
-
-inline void SanitizerUnpoisonMemoryRegion(const void* m, size_t s) {
-#ifdef ABSL_HAVE_ADDRESS_SANITIZER
- ASAN_UNPOISON_MEMORY_REGION(m, s);
-#endif
-#ifdef ABSL_HAVE_MEMORY_SANITIZER
- __msan_unpoison(m, s);
-#endif
- (void)m;
- (void)s;
-}
-
-template <typename T>
-inline void SanitizerPoisonObject(const T* object) {
- SanitizerPoisonMemoryRegion(object, sizeof(T));
-}
-
-template <typename T>
-inline void SanitizerUnpoisonObject(const T* object) {
- SanitizerUnpoisonMemoryRegion(object, sizeof(T));
-}
-
-namespace memory_internal {
-
-// If Pair is a standard-layout type, OffsetOf<Pair>::kFirst and
-// OffsetOf<Pair>::kSecond are equivalent to offsetof(Pair, first) and
-// offsetof(Pair, second) respectively. Otherwise they are -1.
-//
-// The purpose of OffsetOf is to avoid calling offsetof() on non-standard-layout
-// type, which is non-portable.
-template <class Pair, class = std::true_type>
-struct OffsetOf {
- static constexpr size_t kFirst = static_cast<size_t>(-1);
- static constexpr size_t kSecond = static_cast<size_t>(-1);
-};
-
-template <class Pair>
-struct OffsetOf<Pair, typename std::is_standard_layout<Pair>::type> {
- static constexpr size_t kFirst = offsetof(Pair, first);
- static constexpr size_t kSecond = offsetof(Pair, second);
-};
-
-template <class K, class V>
-struct IsLayoutCompatible {
- private:
- struct Pair {
- K first;
- V second;
- };
-
- // Is P layout-compatible with Pair?
- template <class P>
- static constexpr bool LayoutCompatible() {
- return std::is_standard_layout<P>() && sizeof(P) == sizeof(Pair) &&
- alignof(P) == alignof(Pair) &&
- memory_internal::OffsetOf<P>::kFirst ==
- memory_internal::OffsetOf<Pair>::kFirst &&
- memory_internal::OffsetOf<P>::kSecond ==
- memory_internal::OffsetOf<Pair>::kSecond;
- }
-
- public:
- // Whether pair<const K, V> and pair<K, V> are layout-compatible. If they are,
- // then it is safe to store them in a union and read from either.
- static constexpr bool value = std::is_standard_layout<K>() &&
- std::is_standard_layout<Pair>() &&
- memory_internal::OffsetOf<Pair>::kFirst == 0 &&
- LayoutCompatible<std::pair<K, V>>() &&
- LayoutCompatible<std::pair<const K, V>>();
-};
-
-} // namespace memory_internal
-
-// The internal storage type for key-value containers like flat_hash_map.
-//
-// It is convenient for the value_type of a flat_hash_map<K, V> to be
-// pair<const K, V>; the "const K" prevents accidental modification of the key
-// when dealing with the reference returned from find() and similar methods.
-// However, this creates other problems; we want to be able to emplace(K, V)
-// efficiently with move operations, and similarly be able to move a
-// pair<K, V> in insert().
-//
-// The solution is this union, which aliases the const and non-const versions
-// of the pair. This also allows flat_hash_map<const K, V> to work, even though
-// that has the same efficiency issues with move in emplace() and insert() -
-// but people do it anyway.
-//
-// If kMutableKeys is false, only the value member can be accessed.
-//
-// If kMutableKeys is true, key can be accessed through all slots while value
-// and mutable_value must be accessed only via INITIALIZED slots. Slots are
-// created and destroyed via mutable_value so that the key can be moved later.
-//
-// Accessing one of the union fields while the other is active is safe as
-// long as they are layout-compatible, which is guaranteed by the definition of
-// kMutableKeys. For C++11, the relevant section of the standard is
-// https://timsong-cpp.github.io/cppwp/n3337/class.mem#19 (9.2.19)
-template <class K, class V>
-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<absl::remove_const_t<K>, absl::remove_const_t<V>>;
-
- value_type value;
- mutable_value_type mutable_value;
- absl::remove_const_t<K> key;
-};
-
-template <class K, class V>
-struct map_slot_policy {
- using slot_type = map_slot_type<K, V>;
- using value_type = std::pair<const K, V>;
- using mutable_value_type =
- std::pair<absl::remove_const_t<K>, absl::remove_const_t<V>>;
-
- private:
- static void emplace(slot_type* slot) {
- // The construction of union doesn't do anything at runtime but it allows us
- // to access its members without violating aliasing rules.
- new (slot) slot_type;
- }
- // If pair<const K, V> and pair<K, V> are layout-compatible, we can accept one
- // or the other via slot_type. We are also free to access the key via
- // slot_type::key in this case.
- using kMutableKeys = memory_internal::IsLayoutCompatible<K, V>;
-
- public:
- static value_type& element(slot_type* slot) { return slot->value; }
- static const value_type& element(const slot_type* slot) {
- return slot->value;
- }
-
- // When C++17 is available, we can use std::launder to provide mutable
- // access to the key for use in node handle.
-#if defined(__cpp_lib_launder) && __cpp_lib_launder >= 201606
- static K& mutable_key(slot_type* slot) {
- // Still check for kMutableKeys so that we can avoid calling std::launder
- // unless necessary because it can interfere with optimizations.
- return kMutableKeys::value ? slot->key
- : *std::launder(const_cast<K*>(
- std::addressof(slot->value.first)));
- }
-#else // !(defined(__cpp_lib_launder) && __cpp_lib_launder >= 201606)
- static const K& mutable_key(slot_type* slot) { return key(slot); }
-#endif
-
- static const K& key(const slot_type* slot) {
- return kMutableKeys::value ? slot->key : slot->value.first;
- }
-
- template <class Allocator, class... Args>
- static void construct(Allocator* alloc, slot_type* slot, Args&&... args) {
- emplace(slot);
- if (kMutableKeys::value) {
- absl::allocator_traits<Allocator>::construct(*alloc, &slot->mutable_value,
- std::forward<Args>(args)...);
- } else {
- absl::allocator_traits<Allocator>::construct(*alloc, &slot->value,
- std::forward<Args>(args)...);
- }
- }
-
- // Construct this slot by moving from another slot.
- template <class Allocator>
- static void construct(Allocator* alloc, slot_type* slot, slot_type* other) {
- emplace(slot);
- if (kMutableKeys::value) {
- absl::allocator_traits<Allocator>::construct(
- *alloc, &slot->mutable_value, std::move(other->mutable_value));
- } else {
- absl::allocator_traits<Allocator>::construct(*alloc, &slot->value,
- std::move(other->value));
- }
- }
-
- // Construct this slot by copying from another slot.
- template <class Allocator>
- static void construct(Allocator* alloc, slot_type* slot,
- const slot_type* other) {
- emplace(slot);
- absl::allocator_traits<Allocator>::construct(*alloc, &slot->value,
- other->value);
- }
-
- template <class Allocator>
- static void destroy(Allocator* alloc, slot_type* slot) {
- if (kMutableKeys::value) {
- absl::allocator_traits<Allocator>::destroy(*alloc, &slot->mutable_value);
- } else {
- absl::allocator_traits<Allocator>::destroy(*alloc, &slot->value);
- }
- }
-
- template <class Allocator>
- static void transfer(Allocator* alloc, slot_type* new_slot,
- slot_type* old_slot) {
- emplace(new_slot);
-#if defined(__cpp_lib_launder) && __cpp_lib_launder >= 201606
- if (absl::is_trivially_relocatable<value_type>()) {
- // TODO(b/247130232,b/251814870): remove casts after fixing warnings.
- std::memcpy(static_cast<void*>(std::launder(&new_slot->value)),
- static_cast<const void*>(&old_slot->value),
- sizeof(value_type));
- return;
- }
-#endif
-
- if (kMutableKeys::value) {
- absl::allocator_traits<Allocator>::construct(
- *alloc, &new_slot->mutable_value, std::move(old_slot->mutable_value));
- } else {
- absl::allocator_traits<Allocator>::construct(*alloc, &new_slot->value,
- std::move(old_slot->value));
- }
- destroy(alloc, old_slot);
- }
-};
-
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_INTERNAL_CONTAINER_MEMORY_H_
diff --git a/third_party/abseil-cpp/absl/container/internal/container_memory_test.cc b/third_party/abseil-cpp/absl/container/internal/container_memory_test.cc
deleted file mode 100644
index fb9c4dd..0000000
--- a/third_party/abseil-cpp/absl/container/internal/container_memory_test.cc
+++ /dev/null
@@ -1,257 +0,0 @@
-// Copyright 2018 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/container/internal/container_memory.h"
-
-#include <cstdint>
-#include <tuple>
-#include <typeindex>
-#include <typeinfo>
-#include <utility>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/container/internal/test_instance_tracker.h"
-#include "absl/strings/string_view.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-namespace {
-
-using ::absl::test_internal::CopyableMovableInstance;
-using ::absl::test_internal::InstanceTracker;
-using ::testing::_;
-using ::testing::ElementsAre;
-using ::testing::Gt;
-using ::testing::Pair;
-
-TEST(Memory, AlignmentLargerThanBase) {
- std::allocator<int8_t> alloc;
- void* mem = Allocate<2>(&alloc, 3);
- EXPECT_EQ(0, reinterpret_cast<uintptr_t>(mem) % 2);
- memcpy(mem, "abc", 3);
- Deallocate<2>(&alloc, mem, 3);
-}
-
-TEST(Memory, AlignmentSmallerThanBase) {
- std::allocator<int64_t> alloc;
- void* mem = Allocate<2>(&alloc, 3);
- EXPECT_EQ(0, reinterpret_cast<uintptr_t>(mem) % 2);
- memcpy(mem, "abc", 3);
- Deallocate<2>(&alloc, mem, 3);
-}
-
-std::map<std::type_index, int>& AllocationMap() {
- static auto* map = new std::map<std::type_index, int>;
- return *map;
-}
-
-template <typename T>
-struct TypeCountingAllocator {
- TypeCountingAllocator() = default;
- template <typename U>
- TypeCountingAllocator(const TypeCountingAllocator<U>&) {} // NOLINT
-
- using value_type = T;
-
- T* allocate(size_t n, const void* = nullptr) {
- AllocationMap()[typeid(T)] += n;
- return std::allocator<T>().allocate(n);
- }
- void deallocate(T* p, std::size_t n) {
- AllocationMap()[typeid(T)] -= n;
- return std::allocator<T>().deallocate(p, n);
- }
-};
-
-TEST(Memory, AllocateDeallocateMatchType) {
- TypeCountingAllocator<int> alloc;
- void* mem = Allocate<1>(&alloc, 1);
- // Verify that it was allocated
- EXPECT_THAT(AllocationMap(), ElementsAre(Pair(_, Gt(0))));
- Deallocate<1>(&alloc, mem, 1);
- // Verify that the deallocation matched.
- EXPECT_THAT(AllocationMap(), ElementsAre(Pair(_, 0)));
-}
-
-class Fixture : public ::testing::Test {
- using Alloc = std::allocator<std::string>;
-
- public:
- Fixture() { ptr_ = std::allocator_traits<Alloc>::allocate(*alloc(), 1); }
- ~Fixture() override {
- std::allocator_traits<Alloc>::destroy(*alloc(), ptr_);
- std::allocator_traits<Alloc>::deallocate(*alloc(), ptr_, 1);
- }
- std::string* ptr() { return ptr_; }
- Alloc* alloc() { return &alloc_; }
-
- private:
- Alloc alloc_;
- std::string* ptr_;
-};
-
-TEST_F(Fixture, ConstructNoArgs) {
- ConstructFromTuple(alloc(), ptr(), std::forward_as_tuple());
- EXPECT_EQ(*ptr(), "");
-}
-
-TEST_F(Fixture, ConstructOneArg) {
- ConstructFromTuple(alloc(), ptr(), std::forward_as_tuple("abcde"));
- EXPECT_EQ(*ptr(), "abcde");
-}
-
-TEST_F(Fixture, ConstructTwoArg) {
- ConstructFromTuple(alloc(), ptr(), std::forward_as_tuple(5, 'a'));
- EXPECT_EQ(*ptr(), "aaaaa");
-}
-
-TEST(PairArgs, NoArgs) {
- EXPECT_THAT(PairArgs(),
- Pair(std::forward_as_tuple(), std::forward_as_tuple()));
-}
-
-TEST(PairArgs, TwoArgs) {
- EXPECT_EQ(
- std::make_pair(std::forward_as_tuple(1), std::forward_as_tuple('A')),
- PairArgs(1, 'A'));
-}
-
-TEST(PairArgs, Pair) {
- EXPECT_EQ(
- std::make_pair(std::forward_as_tuple(1), std::forward_as_tuple('A')),
- PairArgs(std::make_pair(1, 'A')));
-}
-
-TEST(PairArgs, Piecewise) {
- EXPECT_EQ(
- std::make_pair(std::forward_as_tuple(1), std::forward_as_tuple('A')),
- PairArgs(std::piecewise_construct, std::forward_as_tuple(1),
- std::forward_as_tuple('A')));
-}
-
-TEST(WithConstructed, Simple) {
- EXPECT_EQ(1, WithConstructed<absl::string_view>(
- std::make_tuple(std::string("a")),
- [](absl::string_view str) { return str.size(); }));
-}
-
-template <class F, class Arg>
-decltype(DecomposeValue(std::declval<F>(), std::declval<Arg>()))
-DecomposeValueImpl(int, F&& f, Arg&& arg) {
- return DecomposeValue(std::forward<F>(f), std::forward<Arg>(arg));
-}
-
-template <class F, class Arg>
-const char* DecomposeValueImpl(char, F&& f, Arg&& arg) {
- return "not decomposable";
-}
-
-template <class F, class Arg>
-decltype(DecomposeValueImpl(0, std::declval<F>(), std::declval<Arg>()))
-TryDecomposeValue(F&& f, Arg&& arg) {
- return DecomposeValueImpl(0, std::forward<F>(f), std::forward<Arg>(arg));
-}
-
-TEST(DecomposeValue, Decomposable) {
- auto f = [](const int& x, int&& y) { // NOLINT
- EXPECT_EQ(&x, &y);
- EXPECT_EQ(42, x);
- return 'A';
- };
- EXPECT_EQ('A', TryDecomposeValue(f, 42));
-}
-
-TEST(DecomposeValue, NotDecomposable) {
- auto f = [](void*) {
- ADD_FAILURE() << "Must not be called";
- return 'A';
- };
- EXPECT_STREQ("not decomposable", TryDecomposeValue(f, 42));
-}
-
-template <class F, class... Args>
-decltype(DecomposePair(std::declval<F>(), std::declval<Args>()...))
-DecomposePairImpl(int, F&& f, Args&&... args) {
- return DecomposePair(std::forward<F>(f), std::forward<Args>(args)...);
-}
-
-template <class F, class... Args>
-const char* DecomposePairImpl(char, F&& f, Args&&... args) {
- return "not decomposable";
-}
-
-template <class F, class... Args>
-decltype(DecomposePairImpl(0, std::declval<F>(), std::declval<Args>()...))
-TryDecomposePair(F&& f, Args&&... args) {
- return DecomposePairImpl(0, std::forward<F>(f), std::forward<Args>(args)...);
-}
-
-TEST(DecomposePair, Decomposable) {
- auto f = [](const int& x, // NOLINT
- std::piecewise_construct_t, std::tuple<int&&> k,
- std::tuple<double>&& v) {
- EXPECT_EQ(&x, &std::get<0>(k));
- EXPECT_EQ(42, x);
- EXPECT_EQ(0.5, std::get<0>(v));
- return 'A';
- };
- EXPECT_EQ('A', TryDecomposePair(f, 42, 0.5));
- EXPECT_EQ('A', TryDecomposePair(f, std::make_pair(42, 0.5)));
- EXPECT_EQ('A', TryDecomposePair(f, std::piecewise_construct,
- std::make_tuple(42), std::make_tuple(0.5)));
-}
-
-TEST(DecomposePair, NotDecomposable) {
- auto f = [](...) {
- ADD_FAILURE() << "Must not be called";
- return 'A';
- };
- EXPECT_STREQ("not decomposable",
- TryDecomposePair(f));
- EXPECT_STREQ("not decomposable",
- TryDecomposePair(f, std::piecewise_construct, std::make_tuple(),
- 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
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/container/internal/counting_allocator.h b/third_party/abseil-cpp/absl/container/internal/counting_allocator.h
deleted file mode 100644
index 66068a5..0000000
--- a/third_party/abseil-cpp/absl/container/internal/counting_allocator.h
+++ /dev/null
@@ -1,122 +0,0 @@
-// Copyright 2018 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_CONTAINER_INTERNAL_COUNTING_ALLOCATOR_H_
-#define ABSL_CONTAINER_INTERNAL_COUNTING_ALLOCATOR_H_
-
-#include <cstdint>
-#include <memory>
-
-#include "absl/base/config.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-
-// This is a stateful allocator, but the state lives outside of the
-// allocator (in whatever test is using the allocator). This is odd
-// but helps in tests where the allocator is propagated into nested
-// containers - that chain of allocators uses the same state and is
-// thus easier to query for aggregate allocation information.
-template <typename T>
-class CountingAllocator {
- public:
- using Allocator = std::allocator<T>;
- using AllocatorTraits = std::allocator_traits<Allocator>;
- using value_type = typename AllocatorTraits::value_type;
- using pointer = typename AllocatorTraits::pointer;
- using const_pointer = typename AllocatorTraits::const_pointer;
- using size_type = typename AllocatorTraits::size_type;
- using difference_type = typename AllocatorTraits::difference_type;
-
- CountingAllocator() = default;
- explicit CountingAllocator(int64_t* bytes_used) : bytes_used_(bytes_used) {}
- CountingAllocator(int64_t* bytes_used, int64_t* instance_count)
- : bytes_used_(bytes_used), instance_count_(instance_count) {}
-
- template <typename U>
- CountingAllocator(const CountingAllocator<U>& x)
- : bytes_used_(x.bytes_used_), instance_count_(x.instance_count_) {}
-
- pointer allocate(
- size_type n,
- typename AllocatorTraits::const_void_pointer hint = nullptr) {
- Allocator allocator;
- pointer ptr = AllocatorTraits::allocate(allocator, n, hint);
- if (bytes_used_ != nullptr) {
- *bytes_used_ += n * sizeof(T);
- }
- return ptr;
- }
-
- void deallocate(pointer p, size_type n) {
- Allocator allocator;
- AllocatorTraits::deallocate(allocator, p, n);
- if (bytes_used_ != nullptr) {
- *bytes_used_ -= n * sizeof(T);
- }
- }
-
- template <typename U, typename... Args>
- void construct(U* p, Args&&... args) {
- Allocator allocator;
- AllocatorTraits::construct(allocator, p, std::forward<Args>(args)...);
- if (instance_count_ != nullptr) {
- *instance_count_ += 1;
- }
- }
-
- template <typename U>
- void destroy(U* p) {
- Allocator allocator;
- // Ignore GCC warning bug.
-#if ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(12, 0)
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wuse-after-free"
-#endif
- AllocatorTraits::destroy(allocator, p);
-#if ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(12, 0)
-#pragma GCC diagnostic pop
-#endif
- if (instance_count_ != nullptr) {
- *instance_count_ -= 1;
- }
- }
-
- template <typename U>
- class rebind {
- public:
- using other = CountingAllocator<U>;
- };
-
- friend bool operator==(const CountingAllocator& a,
- const CountingAllocator& b) {
- return a.bytes_used_ == b.bytes_used_ &&
- a.instance_count_ == b.instance_count_;
- }
-
- friend bool operator!=(const CountingAllocator& a,
- const CountingAllocator& b) {
- return !(a == b);
- }
-
- int64_t* bytes_used_ = nullptr;
- int64_t* instance_count_ = nullptr;
-};
-
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_INTERNAL_COUNTING_ALLOCATOR_H_
diff --git a/third_party/abseil-cpp/absl/container/internal/hash_function_defaults.h b/third_party/abseil-cpp/absl/container/internal/hash_function_defaults.h
deleted file mode 100644
index 250e662..0000000
--- a/third_party/abseil-cpp/absl/container/internal/hash_function_defaults.h
+++ /dev/null
@@ -1,163 +0,0 @@
-// Copyright 2018 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.
-//
-// Define the default Hash and Eq functions for SwissTable containers.
-//
-// std::hash<T> and std::equal_to<T> are not appropriate hash and equal
-// functions for SwissTable containers. There are two reasons for this.
-//
-// SwissTable containers are power of 2 sized containers:
-//
-// This means they use the lower bits of the hash value to find the slot for
-// each entry. The typical hash function for integral types is the identity.
-// This is a very weak hash function for SwissTable and any power of 2 sized
-// hashtable implementation which will lead to excessive collisions. For
-// SwissTable we use murmur3 style mixing to reduce collisions to a minimum.
-//
-// SwissTable containers support heterogeneous lookup:
-//
-// In order to make heterogeneous lookup work, hash and equal functions must be
-// polymorphic. At the same time they have to satisfy the same requirements the
-// C++ standard imposes on hash functions and equality operators. That is:
-//
-// if hash_default_eq<T>(a, b) returns true for any a and b of type T, then
-// hash_default_hash<T>(a) must equal hash_default_hash<T>(b)
-//
-// For SwissTable containers this requirement is relaxed to allow a and b of
-// any and possibly different types. Note that like the standard the hash and
-// equal functions are still bound to T. This is important because some type U
-// can be hashed by/tested for equality differently depending on T. A notable
-// example is `const char*`. `const char*` is treated as a c-style string when
-// the hash function is hash<std::string> but as a pointer when the hash
-// function is hash<void*>.
-//
-#ifndef ABSL_CONTAINER_INTERNAL_HASH_FUNCTION_DEFAULTS_H_
-#define ABSL_CONTAINER_INTERNAL_HASH_FUNCTION_DEFAULTS_H_
-
-#include <stdint.h>
-#include <cstddef>
-#include <memory>
-#include <string>
-#include <type_traits>
-
-#include "absl/base/config.h"
-#include "absl/hash/hash.h"
-#include "absl/strings/cord.h"
-#include "absl/strings/string_view.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-
-// The hash of an object of type T is computed by using absl::Hash.
-template <class T, class E = void>
-struct HashEq {
- using Hash = absl::Hash<T>;
- using Eq = std::equal_to<T>;
-};
-
-struct StringHash {
- using is_transparent = void;
-
- size_t operator()(absl::string_view v) const {
- return absl::Hash<absl::string_view>{}(v);
- }
- size_t operator()(const absl::Cord& v) const {
- return absl::Hash<absl::Cord>{}(v);
- }
-};
-
-struct StringEq {
- using is_transparent = void;
- bool operator()(absl::string_view lhs, absl::string_view rhs) const {
- return lhs == rhs;
- }
- bool operator()(const absl::Cord& lhs, const absl::Cord& rhs) const {
- return lhs == rhs;
- }
- bool operator()(const absl::Cord& lhs, absl::string_view rhs) const {
- return lhs == rhs;
- }
- bool operator()(absl::string_view lhs, const absl::Cord& rhs) const {
- return lhs == rhs;
- }
-};
-
-// Supports heterogeneous lookup for string-like elements.
-struct StringHashEq {
- using Hash = StringHash;
- using Eq = StringEq;
-};
-
-template <>
-struct HashEq<std::string> : StringHashEq {};
-template <>
-struct HashEq<absl::string_view> : StringHashEq {};
-template <>
-struct HashEq<absl::Cord> : StringHashEq {};
-
-// Supports heterogeneous lookup for pointers and smart pointers.
-template <class T>
-struct HashEq<T*> {
- struct Hash {
- using is_transparent = void;
- template <class U>
- size_t operator()(const U& ptr) const {
- return absl::Hash<const T*>{}(HashEq::ToPtr(ptr));
- }
- };
- struct Eq {
- using is_transparent = void;
- template <class A, class B>
- bool operator()(const A& a, const B& b) const {
- return HashEq::ToPtr(a) == HashEq::ToPtr(b);
- }
- };
-
- private:
- static const T* ToPtr(const T* ptr) { return ptr; }
- template <class U, class D>
- static const T* ToPtr(const std::unique_ptr<U, D>& ptr) {
- return ptr.get();
- }
- template <class U>
- static const T* ToPtr(const std::shared_ptr<U>& ptr) {
- return ptr.get();
- }
-};
-
-template <class T, class D>
-struct HashEq<std::unique_ptr<T, D>> : HashEq<T*> {};
-template <class T>
-struct HashEq<std::shared_ptr<T>> : HashEq<T*> {};
-
-// This header's visibility is restricted. If you need to access the default
-// hasher please use the container's ::hasher alias instead.
-//
-// Example: typename Hash = typename absl::flat_hash_map<K, V>::hasher
-template <class T>
-using hash_default_hash = typename container_internal::HashEq<T>::Hash;
-
-// This header's visibility is restricted. If you need to access the default
-// key equal please use the container's ::key_equal alias instead.
-//
-// Example: typename Eq = typename absl::flat_hash_map<K, V, Hash>::key_equal
-template <class T>
-using hash_default_eq = typename container_internal::HashEq<T>::Eq;
-
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_INTERNAL_HASH_FUNCTION_DEFAULTS_H_
diff --git a/third_party/abseil-cpp/absl/container/internal/hash_function_defaults_test.cc b/third_party/abseil-cpp/absl/container/internal/hash_function_defaults_test.cc
deleted file mode 100644
index 9f0a4c7..0000000
--- a/third_party/abseil-cpp/absl/container/internal/hash_function_defaults_test.cc
+++ /dev/null
@@ -1,383 +0,0 @@
-// Copyright 2018 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/container/internal/hash_function_defaults.h"
-
-#include <functional>
-#include <type_traits>
-#include <utility>
-
-#include "gtest/gtest.h"
-#include "absl/random/random.h"
-#include "absl/strings/cord.h"
-#include "absl/strings/cord_test_helpers.h"
-#include "absl/strings/string_view.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-namespace {
-
-using ::testing::Types;
-
-TEST(Eq, Int32) {
- hash_default_eq<int32_t> eq;
- EXPECT_TRUE(eq(1, 1u));
- EXPECT_TRUE(eq(1, char{1}));
- EXPECT_TRUE(eq(1, true));
- EXPECT_TRUE(eq(1, double{1.1}));
- EXPECT_FALSE(eq(1, char{2}));
- EXPECT_FALSE(eq(1, 2u));
- EXPECT_FALSE(eq(1, false));
- EXPECT_FALSE(eq(1, 2.));
-}
-
-TEST(Hash, Int32) {
- hash_default_hash<int32_t> hash;
- auto h = hash(1);
- EXPECT_EQ(h, hash(1u));
- EXPECT_EQ(h, hash(char{1}));
- EXPECT_EQ(h, hash(true));
- EXPECT_EQ(h, hash(double{1.1}));
- EXPECT_NE(h, hash(2u));
- EXPECT_NE(h, hash(char{2}));
- EXPECT_NE(h, hash(false));
- EXPECT_NE(h, hash(2.));
-}
-
-enum class MyEnum { A, B, C, D };
-
-TEST(Eq, Enum) {
- hash_default_eq<MyEnum> eq;
- EXPECT_TRUE(eq(MyEnum::A, MyEnum::A));
- EXPECT_FALSE(eq(MyEnum::A, MyEnum::B));
-}
-
-TEST(Hash, Enum) {
- hash_default_hash<MyEnum> hash;
-
- for (MyEnum e : {MyEnum::A, MyEnum::B, MyEnum::C}) {
- auto h = hash(e);
- EXPECT_EQ(h, hash_default_hash<int>{}(static_cast<int>(e)));
- EXPECT_NE(h, hash(MyEnum::D));
- }
-}
-
-using StringTypes = ::testing::Types<std::string, absl::string_view>;
-
-template <class T>
-struct EqString : ::testing::Test {
- hash_default_eq<T> key_eq;
-};
-
-TYPED_TEST_SUITE(EqString, StringTypes);
-
-template <class T>
-struct HashString : ::testing::Test {
- hash_default_hash<T> hasher;
-};
-
-TYPED_TEST_SUITE(HashString, StringTypes);
-
-TYPED_TEST(EqString, Works) {
- auto eq = this->key_eq;
- EXPECT_TRUE(eq("a", "a"));
- EXPECT_TRUE(eq("a", absl::string_view("a")));
- EXPECT_TRUE(eq("a", std::string("a")));
- EXPECT_FALSE(eq("a", "b"));
- EXPECT_FALSE(eq("a", absl::string_view("b")));
- EXPECT_FALSE(eq("a", std::string("b")));
-}
-
-TYPED_TEST(HashString, Works) {
- auto hash = this->hasher;
- auto h = hash("a");
- EXPECT_EQ(h, hash(absl::string_view("a")));
- EXPECT_EQ(h, hash(std::string("a")));
- EXPECT_NE(h, hash(absl::string_view("b")));
- EXPECT_NE(h, hash(std::string("b")));
-}
-
-struct NoDeleter {
- template <class T>
- void operator()(const T* ptr) const {}
-};
-
-using PointerTypes =
- ::testing::Types<const int*, int*, std::unique_ptr<const int>,
- std::unique_ptr<const int, NoDeleter>,
- std::unique_ptr<int>, std::unique_ptr<int, NoDeleter>,
- std::shared_ptr<const int>, std::shared_ptr<int>>;
-
-template <class T>
-struct EqPointer : ::testing::Test {
- hash_default_eq<T> key_eq;
-};
-
-TYPED_TEST_SUITE(EqPointer, PointerTypes);
-
-template <class T>
-struct HashPointer : ::testing::Test {
- hash_default_hash<T> hasher;
-};
-
-TYPED_TEST_SUITE(HashPointer, PointerTypes);
-
-TYPED_TEST(EqPointer, Works) {
- int dummy;
- auto eq = this->key_eq;
- auto sptr = std::make_shared<int>();
- std::shared_ptr<const int> csptr = sptr;
- int* ptr = sptr.get();
- const int* cptr = ptr;
- std::unique_ptr<int, NoDeleter> uptr(ptr);
- std::unique_ptr<const int, NoDeleter> cuptr(ptr);
-
- EXPECT_TRUE(eq(ptr, cptr));
- EXPECT_TRUE(eq(ptr, sptr));
- EXPECT_TRUE(eq(ptr, uptr));
- EXPECT_TRUE(eq(ptr, csptr));
- EXPECT_TRUE(eq(ptr, cuptr));
- EXPECT_FALSE(eq(&dummy, cptr));
- EXPECT_FALSE(eq(&dummy, sptr));
- EXPECT_FALSE(eq(&dummy, uptr));
- EXPECT_FALSE(eq(&dummy, csptr));
- EXPECT_FALSE(eq(&dummy, cuptr));
-}
-
-TEST(Hash, DerivedAndBase) {
- struct Base {};
- struct Derived : Base {};
-
- hash_default_hash<Base*> hasher;
-
- Base base;
- Derived derived;
- EXPECT_NE(hasher(&base), hasher(&derived));
- EXPECT_EQ(hasher(static_cast<Base*>(&derived)), hasher(&derived));
-
- auto dp = std::make_shared<Derived>();
- EXPECT_EQ(hasher(static_cast<Base*>(dp.get())), hasher(dp));
-}
-
-TEST(Hash, FunctionPointer) {
- using Func = int (*)();
- hash_default_hash<Func> hasher;
- hash_default_eq<Func> eq;
-
- Func p1 = [] { return 1; }, p2 = [] { return 2; };
- EXPECT_EQ(hasher(p1), hasher(p1));
- EXPECT_TRUE(eq(p1, p1));
-
- EXPECT_NE(hasher(p1), hasher(p2));
- EXPECT_FALSE(eq(p1, p2));
-}
-
-TYPED_TEST(HashPointer, Works) {
- int dummy;
- auto hash = this->hasher;
- auto sptr = std::make_shared<int>();
- std::shared_ptr<const int> csptr = sptr;
- int* ptr = sptr.get();
- const int* cptr = ptr;
- std::unique_ptr<int, NoDeleter> uptr(ptr);
- std::unique_ptr<const int, NoDeleter> cuptr(ptr);
-
- EXPECT_EQ(hash(ptr), hash(cptr));
- EXPECT_EQ(hash(ptr), hash(sptr));
- EXPECT_EQ(hash(ptr), hash(uptr));
- EXPECT_EQ(hash(ptr), hash(csptr));
- EXPECT_EQ(hash(ptr), hash(cuptr));
- EXPECT_NE(hash(&dummy), hash(cptr));
- EXPECT_NE(hash(&dummy), hash(sptr));
- EXPECT_NE(hash(&dummy), hash(uptr));
- EXPECT_NE(hash(&dummy), hash(csptr));
- EXPECT_NE(hash(&dummy), hash(cuptr));
-}
-
-TEST(EqCord, Works) {
- hash_default_eq<absl::Cord> eq;
- const absl::string_view a_string_view = "a";
- const absl::Cord a_cord(a_string_view);
- const absl::string_view b_string_view = "b";
- const absl::Cord b_cord(b_string_view);
-
- EXPECT_TRUE(eq(a_cord, a_cord));
- EXPECT_TRUE(eq(a_cord, a_string_view));
- EXPECT_TRUE(eq(a_string_view, a_cord));
- EXPECT_FALSE(eq(a_cord, b_cord));
- EXPECT_FALSE(eq(a_cord, b_string_view));
- EXPECT_FALSE(eq(b_string_view, a_cord));
-}
-
-TEST(HashCord, Works) {
- hash_default_hash<absl::Cord> hash;
- const absl::string_view a_string_view = "a";
- const absl::Cord a_cord(a_string_view);
- const absl::string_view b_string_view = "b";
- const absl::Cord b_cord(b_string_view);
-
- EXPECT_EQ(hash(a_cord), hash(a_cord));
- EXPECT_EQ(hash(b_cord), hash(b_cord));
- EXPECT_EQ(hash(a_string_view), hash(a_cord));
- EXPECT_EQ(hash(b_string_view), hash(b_cord));
- EXPECT_EQ(hash(absl::Cord("")), hash(""));
- EXPECT_EQ(hash(absl::Cord()), hash(absl::string_view()));
-
- EXPECT_NE(hash(a_cord), hash(b_cord));
- EXPECT_NE(hash(a_cord), hash(b_string_view));
- EXPECT_NE(hash(a_string_view), hash(b_cord));
- EXPECT_NE(hash(a_string_view), hash(b_string_view));
-}
-
-void NoOpReleaser(absl::string_view data, void* arg) {}
-
-TEST(HashCord, FragmentedCordWorks) {
- hash_default_hash<absl::Cord> hash;
- absl::Cord c = absl::MakeFragmentedCord({"a", "b", "c"});
- EXPECT_FALSE(c.TryFlat().has_value());
- EXPECT_EQ(hash(c), hash("abc"));
-}
-
-TEST(HashCord, FragmentedLongCordWorks) {
- hash_default_hash<absl::Cord> hash;
- // Crete some large strings which do not fit on the stack.
- std::string a(65536, 'a');
- std::string b(65536, 'b');
- absl::Cord c = absl::MakeFragmentedCord({a, b});
- EXPECT_FALSE(c.TryFlat().has_value());
- EXPECT_EQ(hash(c), hash(a + b));
-}
-
-TEST(HashCord, RandomCord) {
- hash_default_hash<absl::Cord> hash;
- auto bitgen = absl::BitGen();
- for (int i = 0; i < 1000; ++i) {
- const int number_of_segments = absl::Uniform(bitgen, 0, 10);
- std::vector<std::string> pieces;
- for (size_t s = 0; s < number_of_segments; ++s) {
- std::string str;
- str.resize(absl::Uniform(bitgen, 0, 4096));
- // MSVC needed the explicit return type in the lambda.
- std::generate(str.begin(), str.end(), [&]() -> char {
- return static_cast<char>(absl::Uniform<unsigned char>(bitgen));
- });
- pieces.push_back(str);
- }
- absl::Cord c = absl::MakeFragmentedCord(pieces);
- EXPECT_EQ(hash(c), hash(std::string(c)));
- }
-}
-
-// Cartesian product of (std::string, absl::string_view)
-// with (std::string, absl::string_view, const char*, absl::Cord).
-using StringTypesCartesianProduct = Types<
- // clang-format off
- std::pair<absl::Cord, std::string>,
- std::pair<absl::Cord, absl::string_view>,
- std::pair<absl::Cord, absl::Cord>,
- std::pair<absl::Cord, const char*>,
-
- std::pair<std::string, absl::Cord>,
- std::pair<absl::string_view, absl::Cord>,
-
- std::pair<absl::string_view, std::string>,
- std::pair<absl::string_view, absl::string_view>,
- std::pair<absl::string_view, const char*>>;
-// clang-format on
-
-constexpr char kFirstString[] = "abc123";
-constexpr char kSecondString[] = "ijk456";
-
-template <typename T>
-struct StringLikeTest : public ::testing::Test {
- typename T::first_type a1{kFirstString};
- typename T::second_type b1{kFirstString};
- typename T::first_type a2{kSecondString};
- typename T::second_type b2{kSecondString};
- hash_default_eq<typename T::first_type> eq;
- hash_default_hash<typename T::first_type> hash;
-};
-
-TYPED_TEST_SUITE_P(StringLikeTest);
-
-TYPED_TEST_P(StringLikeTest, Eq) {
- EXPECT_TRUE(this->eq(this->a1, this->b1));
- EXPECT_TRUE(this->eq(this->b1, this->a1));
-}
-
-TYPED_TEST_P(StringLikeTest, NotEq) {
- EXPECT_FALSE(this->eq(this->a1, this->b2));
- EXPECT_FALSE(this->eq(this->b2, this->a1));
-}
-
-TYPED_TEST_P(StringLikeTest, HashEq) {
- EXPECT_EQ(this->hash(this->a1), this->hash(this->b1));
- EXPECT_EQ(this->hash(this->a2), this->hash(this->b2));
- // It would be a poor hash function which collides on these strings.
- EXPECT_NE(this->hash(this->a1), this->hash(this->b2));
-}
-
-TYPED_TEST_SUITE(StringLikeTest, StringTypesCartesianProduct);
-
-} // namespace
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-enum Hash : size_t {
- kStd = 0x1, // std::hash
-#ifdef _MSC_VER
- kExtension = kStd, // In MSVC, std::hash == ::hash
-#else // _MSC_VER
- kExtension = 0x2, // ::hash (GCC extension)
-#endif // _MSC_VER
-};
-
-// H is a bitmask of Hash enumerations.
-// Hashable<H> is hashable via all means specified in H.
-template <int H>
-struct Hashable {
- static constexpr bool HashableBy(Hash h) { return h & H; }
-};
-
-namespace std {
-template <int H>
-struct hash<Hashable<H>> {
- template <class E = Hashable<H>,
- class = typename std::enable_if<E::HashableBy(kStd)>::type>
- size_t operator()(E) const {
- return kStd;
- }
-};
-} // namespace std
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-namespace {
-
-template <class T>
-size_t Hash(const T& v) {
- return hash_default_hash<T>()(v);
-}
-
-TEST(Delegate, HashDispatch) {
- EXPECT_EQ(Hash(kStd), Hash(Hashable<kStd>()));
-}
-
-} // namespace
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/container/internal/hash_generator_testing.cc b/third_party/abseil-cpp/absl/container/internal/hash_generator_testing.cc
deleted file mode 100644
index 59cc5aa..0000000
--- a/third_party/abseil-cpp/absl/container/internal/hash_generator_testing.cc
+++ /dev/null
@@ -1,76 +0,0 @@
-// Copyright 2018 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/container/internal/hash_generator_testing.h"
-
-#include <deque>
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-namespace hash_internal {
-namespace {
-
-class RandomDeviceSeedSeq {
- public:
- using result_type = typename std::random_device::result_type;
-
- template <class Iterator>
- void generate(Iterator start, Iterator end) {
- while (start != end) {
- *start = gen_();
- ++start;
- }
- }
-
- private:
- std::random_device gen_;
-};
-
-} // namespace
-
-std::mt19937_64* GetSharedRng() {
- static auto* rng = [] {
- RandomDeviceSeedSeq seed_seq;
- return new std::mt19937_64(seed_seq);
- }();
- return rng;
-}
-
-std::string Generator<std::string>::operator()() const {
- // NOLINTNEXTLINE(runtime/int)
- std::uniform_int_distribution<short> chars(0x20, 0x7E);
- std::string res;
- res.resize(32);
- std::generate(res.begin(), res.end(),
- [&]() { return chars(*GetSharedRng()); });
- return res;
-}
-
-absl::string_view Generator<absl::string_view>::operator()() const {
- static auto* arena = new std::deque<std::string>();
- // NOLINTNEXTLINE(runtime/int)
- std::uniform_int_distribution<short> chars(0x20, 0x7E);
- arena->emplace_back();
- auto& res = arena->back();
- res.resize(32);
- std::generate(res.begin(), res.end(),
- [&]() { return chars(*GetSharedRng()); });
- return res;
-}
-
-} // namespace hash_internal
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/container/internal/hash_generator_testing.h b/third_party/abseil-cpp/absl/container/internal/hash_generator_testing.h
deleted file mode 100644
index f1f555a..0000000
--- a/third_party/abseil-cpp/absl/container/internal/hash_generator_testing.h
+++ /dev/null
@@ -1,182 +0,0 @@
-// Copyright 2018 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.
-//
-// Generates random values for testing. Specialized only for the few types we
-// care about.
-
-#ifndef ABSL_CONTAINER_INTERNAL_HASH_GENERATOR_TESTING_H_
-#define ABSL_CONTAINER_INTERNAL_HASH_GENERATOR_TESTING_H_
-
-#include <stdint.h>
-
-#include <algorithm>
-#include <cassert>
-#include <iosfwd>
-#include <random>
-#include <tuple>
-#include <type_traits>
-#include <utility>
-#include <vector>
-
-#include "absl/container/internal/hash_policy_testing.h"
-#include "absl/memory/memory.h"
-#include "absl/meta/type_traits.h"
-#include "absl/strings/string_view.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-namespace hash_internal {
-namespace generator_internal {
-
-template <class Container, class = void>
-struct IsMap : std::false_type {};
-
-template <class Map>
-struct IsMap<Map, absl::void_t<typename Map::mapped_type>> : std::true_type {};
-
-} // namespace generator_internal
-
-std::mt19937_64* GetSharedRng();
-
-enum Enum {
- kEnumEmpty,
- kEnumDeleted,
-};
-
-enum class EnumClass : uint64_t {
- kEmpty,
- kDeleted,
-};
-
-inline std::ostream& operator<<(std::ostream& o, const EnumClass& ec) {
- return o << static_cast<uint64_t>(ec);
-}
-
-template <class T, class E = void>
-struct Generator;
-
-template <class T>
-struct Generator<T, typename std::enable_if<std::is_integral<T>::value>::type> {
- T operator()() const {
- std::uniform_int_distribution<T> dist;
- return dist(*GetSharedRng());
- }
-};
-
-template <>
-struct Generator<Enum> {
- Enum operator()() const {
- std::uniform_int_distribution<typename std::underlying_type<Enum>::type>
- dist;
- while (true) {
- auto variate = dist(*GetSharedRng());
- if (variate != kEnumEmpty && variate != kEnumDeleted)
- return static_cast<Enum>(variate);
- }
- }
-};
-
-template <>
-struct Generator<EnumClass> {
- EnumClass operator()() const {
- std::uniform_int_distribution<
- typename std::underlying_type<EnumClass>::type>
- dist;
- while (true) {
- EnumClass variate = static_cast<EnumClass>(dist(*GetSharedRng()));
- if (variate != EnumClass::kEmpty && variate != EnumClass::kDeleted)
- return static_cast<EnumClass>(variate);
- }
- }
-};
-
-template <>
-struct Generator<std::string> {
- std::string operator()() const;
-};
-
-template <>
-struct Generator<absl::string_view> {
- absl::string_view operator()() const;
-};
-
-template <>
-struct Generator<NonStandardLayout> {
- NonStandardLayout operator()() const {
- return NonStandardLayout(Generator<std::string>()());
- }
-};
-
-template <class K, class V>
-struct Generator<std::pair<K, V>> {
- std::pair<K, V> operator()() const {
- return std::pair<K, V>(Generator<typename std::decay<K>::type>()(),
- Generator<typename std::decay<V>::type>()());
- }
-};
-
-template <class... Ts>
-struct Generator<std::tuple<Ts...>> {
- std::tuple<Ts...> operator()() const {
- return std::tuple<Ts...>(Generator<typename std::decay<Ts>::type>()()...);
- }
-};
-
-template <class T>
-struct Generator<std::unique_ptr<T>> {
- std::unique_ptr<T> operator()() const {
- return absl::make_unique<T>(Generator<T>()());
- }
-};
-
-template <class U>
-struct Generator<U, absl::void_t<decltype(std::declval<U&>().key()),
- decltype(std::declval<U&>().value())>>
- : Generator<std::pair<
- typename std::decay<decltype(std::declval<U&>().key())>::type,
- typename std::decay<decltype(std::declval<U&>().value())>::type>> {};
-
-template <class Container>
-using GeneratedType = decltype(
- std::declval<const Generator<
- typename std::conditional<generator_internal::IsMap<Container>::value,
- typename Container::value_type,
- typename Container::key_type>::type>&>()());
-
-// Naive wrapper that performs a linear search of previous values.
-// Beware this is O(SQR), which is reasonable for smaller kMaxValues.
-template <class T, size_t kMaxValues = 64, class E = void>
-struct UniqueGenerator {
- Generator<T, E> gen;
- std::vector<T> values;
-
- T operator()() {
- assert(values.size() < kMaxValues);
- for (;;) {
- T value = gen();
- if (std::find(values.begin(), values.end(), value) == values.end()) {
- values.push_back(value);
- return value;
- }
- }
- }
-};
-
-} // namespace hash_internal
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_INTERNAL_HASH_GENERATOR_TESTING_H_
diff --git a/third_party/abseil-cpp/absl/container/internal/hash_policy_testing.h b/third_party/abseil-cpp/absl/container/internal/hash_policy_testing.h
deleted file mode 100644
index 01c40d2..0000000
--- a/third_party/abseil-cpp/absl/container/internal/hash_policy_testing.h
+++ /dev/null
@@ -1,184 +0,0 @@
-// Copyright 2018 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.
-//
-// Utilities to help tests verify that hash tables properly handle stateful
-// allocators and hash functions.
-
-#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() {
- // 0 is reserved for moved from state.
- static size_t gId = 1;
- return gId++;
- }
-};
-
-} // namespace hash_testing_internal
-
-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;
- }
-};
-
-// It is expected that Alloc() == Alloc() for all allocators so we cannot use
-// WithId base. We need to explicitly assign ids.
-template <class T = int>
-struct Alloc : std::allocator<T> {
- using propagate_on_container_swap = std::true_type;
-
- // Using old paradigm for this to ensure compatibility.
- 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;
-}
-
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-// ABSL_UNORDERED_SUPPORTS_ALLOC_CTORS is false for glibcxx versions
-// where the unordered containers are missing certain constructors that
-// take allocator arguments. This test is defined ad-hoc for the platforms
-// we care about (notably Crosstool 17) because libstdcxx's useless
-// versioning scheme precludes a more principled solution.
-// From GCC-4.9 Changelog: (src: https://gcc.gnu.org/gcc-4.9/changes.html)
-// "the unordered associative containers in <unordered_map> and <unordered_set>
-// meet the allocator-aware container requirements;"
-#if (defined(__GLIBCXX__) && __GLIBCXX__ <= 20140425 ) || \
-( __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 9 ))
-#define ABSL_UNORDERED_SUPPORTS_ALLOC_CTORS 0
-#else
-#define ABSL_UNORDERED_SUPPORTS_ALLOC_CTORS 1
-#endif
-
-#endif // ABSL_CONTAINER_INTERNAL_HASH_POLICY_TESTING_H_
diff --git a/third_party/abseil-cpp/absl/container/internal/hash_policy_testing_test.cc b/third_party/abseil-cpp/absl/container/internal/hash_policy_testing_test.cc
deleted file mode 100644
index f0b20fe..0000000
--- a/third_party/abseil-cpp/absl/container/internal/hash_policy_testing_test.cc
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright 2018 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/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());
-}
-
-} // namespace
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/container/internal/hash_policy_traits.h b/third_party/abseil-cpp/absl/container/internal/hash_policy_traits.h
deleted file mode 100644
index 164ec12..0000000
--- a/third_party/abseil-cpp/absl/container/internal/hash_policy_traits.h
+++ /dev/null
@@ -1,157 +0,0 @@
-// Copyright 2018 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_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 {
-
-// Defines how slots are initialized/destroyed/moved.
-template <class Policy, class = void>
-struct hash_policy_traits : common_policy_traits<Policy> {
- // The type of the keys stored in the hashtable.
- using key_type = typename Policy::key_type;
-
- private:
- struct ReturnKey {
- // When C++17 is available, we can use std::launder to provide mutable
- // access to the key for use in node handle.
-#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);
- }
-
- // When Key=T&, we forward the lvalue reference.
- // When Key=T, we return by value to avoid a dangling reference.
- // eg, for string_hash_map.
- 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:
- // The actual object stored in the hash table.
- using slot_type = typename Policy::slot_type;
-
- // The argument type for insertions into the hashtable. This is different
- // from value_type for increased performance. See initializer_list constructor
- // and insert() member functions for more details.
- 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;
-
- // Policies can set this variable to tell raw_hash_set that all iterators
- // should be constant, even `iterator`. This is useful for set-like
- // containers.
- // Defaults to false if not provided by the policy.
- using constant_iterators = ConstantIteratorsImpl<>;
-
- // Returns the amount of memory owned by `slot`, exclusive of `sizeof(*slot)`.
- //
- // If `slot` is nullptr, returns the constant amount of memory owned by any
- // full slot or -1 if slots own variable amounts of memory.
- //
- // PRECONDITION: `slot` is INITIALIZED or nullptr
- template <class P = Policy>
- static size_t space_used(const slot_type* slot) {
- return P::space_used(slot);
- }
-
- // Provides generalized access to the key for elements, both for elements in
- // the table and for elements that have not yet been inserted (or even
- // constructed). We would like an API that allows us to say: `key(args...)`
- // but we cannot do that for all cases, so we use this more general API that
- // can be used for many things, including the following:
- //
- // - Given an element in a table, get its key.
- // - Given an element initializer, get its key.
- // - Given `emplace()` arguments, get the element key.
- //
- // Implementations of this must adhere to a very strict technical
- // specification around aliasing and consuming arguments:
- //
- // Let `value_type` be the result type of `element()` without ref- and
- // cv-qualifiers. The first argument is a functor, the rest are constructor
- // arguments for `value_type`. Returns `std::forward<F>(f)(k, xs...)`, where
- // `k` is the element key, and `xs...` are the new constructor arguments for
- // `value_type`. It's allowed for `k` to alias `xs...`, and for both to alias
- // `ts...`. The key won't be touched once `xs...` are used to construct an
- // element; `ts...` won't be touched at all, which allows `apply()` to consume
- // any rvalues among them.
- //
- // If `value_type` is constructible from `Ts&&...`, `Policy::apply()` must not
- // trigger a hard compile error unless it originates from `f`. In other words,
- // `Policy::apply()` must be SFINAE-friendly. If `value_type` is not
- // constructible from `Ts&&...`, either SFINAE or a hard compile error is OK.
- //
- // If `Ts...` is `[cv] value_type[&]` or `[cv] init_type[&]`,
- // `Policy::apply()` must work. A compile error is not allowed, SFINAE or not.
- 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)...);
- }
-
- // Returns the "key" portion of the slot.
- // Used for node handle manipulation.
- 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));
- }
-
- // Returns the "value" (as opposed to the "key") portion of the element. Used
- // by maps to implement `operator[]`, `at()` and `insert_or_assign()`.
- template <class T, class P = Policy>
- static auto value(T* elem) -> decltype(P::value(elem)) {
- return P::value(elem);
- }
-};
-
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_INTERNAL_HASH_POLICY_TRAITS_H_
diff --git a/third_party/abseil-cpp/absl/container/internal/hash_policy_traits_test.cc b/third_party/abseil-cpp/absl/container/internal/hash_policy_traits_test.cc
deleted file mode 100644
index 82d7cc3..0000000
--- a/third_party/abseil-cpp/absl/container/internal/hash_policy_traits_test.cc
+++ /dev/null
@@ -1,80 +0,0 @@
-// Copyright 2018 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/container/internal/hash_policy_traits.h"
-
-#include <functional>
-#include <memory>
-#include <new>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.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;
-};
-
-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));
-}
-
-} // namespace
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/container/internal/hashtable_debug.h b/third_party/abseil-cpp/absl/container/internal/hashtable_debug.h
deleted file mode 100644
index 19d5212..0000000
--- a/third_party/abseil-cpp/absl/container/internal/hashtable_debug.h
+++ /dev/null
@@ -1,110 +0,0 @@
-// Copyright 2018 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.
-//
-// This library provides APIs to debug the probing behavior of hash tables.
-//
-// In general, the probing behavior is a black box for users and only the
-// side effects can be measured in the form of performance differences.
-// These APIs give a glimpse on the actual behavior of the probing algorithms in
-// these hashtables given a specified hash function and a set of elements.
-//
-// The probe count distribution can be used to assess the quality of the hash
-// function for that particular hash table. Note that a hash function that
-// performs well in one hash table implementation does not necessarily performs
-// well in a different one.
-//
-// This library supports std::unordered_{set,map}, dense_hash_{set,map} and
-// absl::{flat,node,string}_hash_{set,map}.
-
-#ifndef ABSL_CONTAINER_INTERNAL_HASHTABLE_DEBUG_H_
-#define ABSL_CONTAINER_INTERNAL_HASHTABLE_DEBUG_H_
-
-#include <cstddef>
-#include <algorithm>
-#include <type_traits>
-#include <vector>
-
-#include "absl/container/internal/hashtable_debug_hooks.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-
-// Returns the number of probes required to lookup `key`. Returns 0 for a
-// search with no collisions. Higher values mean more hash collisions occurred;
-// however, the exact meaning of this number varies according to the container
-// type.
-template <typename C>
-size_t GetHashtableDebugNumProbes(
- const C& c, const typename C::key_type& key) {
- return absl::container_internal::hashtable_debug_internal::
- HashtableDebugAccess<C>::GetNumProbes(c, key);
-}
-
-// Gets a histogram of the number of probes for each elements in the container.
-// The sum of all the values in the vector is equal to container.size().
-template <typename C>
-std::vector<size_t> GetHashtableDebugNumProbesHistogram(const C& container) {
- std::vector<size_t> v;
- for (auto it = container.begin(); it != container.end(); ++it) {
- size_t num_probes = GetHashtableDebugNumProbes(
- container,
- absl::container_internal::hashtable_debug_internal::GetKey<C>(*it, 0));
- v.resize((std::max)(v.size(), num_probes + 1));
- v[num_probes]++;
- }
- return v;
-}
-
-struct HashtableDebugProbeSummary {
- size_t total_elements;
- size_t total_num_probes;
- double mean;
-};
-
-// Gets a summary of the probe count distribution for the elements in the
-// container.
-template <typename C>
-HashtableDebugProbeSummary GetHashtableDebugProbeSummary(const C& container) {
- auto probes = GetHashtableDebugNumProbesHistogram(container);
- HashtableDebugProbeSummary summary = {};
- for (size_t i = 0; i < probes.size(); ++i) {
- summary.total_elements += probes[i];
- summary.total_num_probes += probes[i] * i;
- }
- summary.mean = 1.0 * summary.total_num_probes / summary.total_elements;
- return summary;
-}
-
-// Returns the number of bytes requested from the allocator by the container
-// and not freed.
-template <typename C>
-size_t AllocatedByteSize(const C& c) {
- return absl::container_internal::hashtable_debug_internal::
- HashtableDebugAccess<C>::AllocatedByteSize(c);
-}
-
-// Returns a tight lower bound for AllocatedByteSize(c) where `c` is of type `C`
-// and `c.size()` is equal to `num_elements`.
-template <typename C>
-size_t LowerBoundAllocatedByteSize(size_t num_elements) {
- return absl::container_internal::hashtable_debug_internal::
- HashtableDebugAccess<C>::LowerBoundAllocatedByteSize(num_elements);
-}
-
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_INTERNAL_HASHTABLE_DEBUG_H_
diff --git a/third_party/abseil-cpp/absl/container/internal/hashtable_debug_hooks.h b/third_party/abseil-cpp/absl/container/internal/hashtable_debug_hooks.h
deleted file mode 100644
index 3e9ea59..0000000
--- a/third_party/abseil-cpp/absl/container/internal/hashtable_debug_hooks.h
+++ /dev/null
@@ -1,85 +0,0 @@
-// Copyright 2018 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.
-//
-// Provides the internal API for hashtable_debug.h.
-
-#ifndef ABSL_CONTAINER_INTERNAL_HASHTABLE_DEBUG_HOOKS_H_
-#define ABSL_CONTAINER_INTERNAL_HASHTABLE_DEBUG_HOOKS_H_
-
-#include <cstddef>
-
-#include <algorithm>
-#include <type_traits>
-#include <vector>
-
-#include "absl/base/config.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-namespace hashtable_debug_internal {
-
-// If it is a map, call get<0>().
-using std::get;
-template <typename T, typename = typename T::mapped_type>
-auto GetKey(const typename T::value_type& pair, int) -> decltype(get<0>(pair)) {
- return get<0>(pair);
-}
-
-// If it is not a map, return the value directly.
-template <typename T>
-const typename T::key_type& GetKey(const typename T::key_type& key, char) {
- return key;
-}
-
-// Containers should specialize this to provide debug information for that
-// container.
-template <class Container, typename Enabler = void>
-struct HashtableDebugAccess {
- // Returns the number of probes required to find `key` in `c`. The "number of
- // probes" is a concept that can vary by container. Implementations should
- // return 0 when `key` was found in the minimum number of operations and
- // should increment the result for each non-trivial operation required to find
- // `key`.
- //
- // The default implementation uses the bucket api from the standard and thus
- // works for `std::unordered_*` containers.
- static size_t GetNumProbes(const Container& c,
- const typename Container::key_type& key) {
- if (!c.bucket_count()) return {};
- size_t num_probes = 0;
- size_t bucket = c.bucket(key);
- for (auto it = c.begin(bucket), e = c.end(bucket);; ++it, ++num_probes) {
- if (it == e) return num_probes;
- if (c.key_eq()(key, GetKey<Container>(*it, 0))) return num_probes;
- }
- }
-
- // Returns the number of bytes requested from the allocator by the container
- // and not freed.
- //
- // static size_t AllocatedByteSize(const Container& c);
-
- // Returns a tight lower bound for AllocatedByteSize(c) where `c` is of type
- // `Container` and `c.size()` is equal to `num_elements`.
- //
- // static size_t LowerBoundAllocatedByteSize(size_t num_elements);
-};
-
-} // namespace hashtable_debug_internal
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_INTERNAL_HASHTABLE_DEBUG_HOOKS_H_
diff --git a/third_party/abseil-cpp/absl/container/internal/hashtablez_sampler.cc b/third_party/abseil-cpp/absl/container/internal/hashtablez_sampler.cc
deleted file mode 100644
index 5b8cf34..0000000
--- a/third_party/abseil-cpp/absl/container/internal/hashtablez_sampler.cc
+++ /dev/null
@@ -1,237 +0,0 @@
-// Copyright 2018 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/container/internal/hashtablez_sampler.h"
-
-#include <atomic>
-#include <cassert>
-#include <cmath>
-#include <functional>
-#include <limits>
-
-#include "absl/base/attributes.h"
-#include "absl/base/config.h"
-#include "absl/debugging/stacktrace.h"
-#include "absl/memory/memory.h"
-#include "absl/profiling/internal/exponential_biased.h"
-#include "absl/profiling/internal/sample_recorder.h"
-#include "absl/synchronization/mutex.h"
-#include "absl/utility/utility.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-
-#ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL
-constexpr int HashtablezInfo::kMaxStackDepth;
-#endif
-
-namespace {
-ABSL_CONST_INIT std::atomic<bool> g_hashtablez_enabled{
- false
-};
-ABSL_CONST_INIT std::atomic<int32_t> g_hashtablez_sample_parameter{1 << 10};
-std::atomic<HashtablezConfigListener> g_hashtablez_config_listener{nullptr};
-
-#if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
-ABSL_PER_THREAD_TLS_KEYWORD absl::profiling_internal::ExponentialBiased
- g_exponential_biased_generator;
-#endif
-
-void TriggerHashtablezConfigListener() {
- auto* listener = g_hashtablez_config_listener.load(std::memory_order_acquire);
- if (listener != nullptr) listener();
-}
-
-} // namespace
-
-#if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
-ABSL_PER_THREAD_TLS_KEYWORD SamplingState global_next_sample = {0, 0};
-#endif // defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
-
-HashtablezSampler& GlobalHashtablezSampler() {
- static auto* sampler = new HashtablezSampler();
- return *sampler;
-}
-
-HashtablezInfo::HashtablezInfo() = default;
-HashtablezInfo::~HashtablezInfo() = default;
-
-void HashtablezInfo::PrepareForSampling(int64_t stride,
- size_t inline_element_size_value) {
- capacity.store(0, std::memory_order_relaxed);
- size.store(0, std::memory_order_relaxed);
- num_erases.store(0, std::memory_order_relaxed);
- num_rehashes.store(0, std::memory_order_relaxed);
- max_probe_length.store(0, std::memory_order_relaxed);
- total_probe_length.store(0, std::memory_order_relaxed);
- hashes_bitwise_or.store(0, std::memory_order_relaxed);
- hashes_bitwise_and.store(~size_t{}, std::memory_order_relaxed);
- hashes_bitwise_xor.store(0, std::memory_order_relaxed);
- max_reserve.store(0, std::memory_order_relaxed);
-
- create_time = absl::Now();
- weight = stride;
- // The inliner makes hardcoded skip_count difficult (especially when combined
- // with LTO). We use the ability to exclude stacks by regex when encoding
- // instead.
- depth = absl::GetStackTrace(stack, HashtablezInfo::kMaxStackDepth,
- /* skip_count= */ 0);
- inline_element_size = inline_element_size_value;
-}
-
-static bool ShouldForceSampling() {
- enum ForceState {
- kDontForce,
- kForce,
- kUninitialized
- };
- ABSL_CONST_INIT static std::atomic<ForceState> global_state{
- kUninitialized};
- ForceState state = global_state.load(std::memory_order_relaxed);
- if (ABSL_PREDICT_TRUE(state == kDontForce)) return false;
-
- if (state == kUninitialized) {
- state = ABSL_INTERNAL_C_SYMBOL(AbslContainerInternalSampleEverything)()
- ? kForce
- : kDontForce;
- global_state.store(state, std::memory_order_relaxed);
- }
- return state == kForce;
-}
-
-HashtablezInfo* SampleSlow(SamplingState& next_sample,
- size_t inline_element_size) {
- if (ABSL_PREDICT_FALSE(ShouldForceSampling())) {
- next_sample.next_sample = 1;
- const int64_t old_stride = exchange(next_sample.sample_stride, 1);
- HashtablezInfo* result =
- GlobalHashtablezSampler().Register(old_stride, inline_element_size);
- return result;
- }
-
-#if !defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
- next_sample = {
- std::numeric_limits<int64_t>::max(),
- std::numeric_limits<int64_t>::max(),
- };
- return nullptr;
-#else
- bool first = next_sample.next_sample < 0;
-
- const int64_t next_stride = g_exponential_biased_generator.GetStride(
- g_hashtablez_sample_parameter.load(std::memory_order_relaxed));
-
- next_sample.next_sample = next_stride;
- const int64_t old_stride = exchange(next_sample.sample_stride, next_stride);
- // Small values of interval are equivalent to just sampling next time.
- ABSL_ASSERT(next_stride >= 1);
-
- // g_hashtablez_enabled can be dynamically flipped, we need to set a threshold
- // low enough that we will start sampling in a reasonable time, so we just use
- // the default sampling rate.
- if (!g_hashtablez_enabled.load(std::memory_order_relaxed)) return nullptr;
-
- // We will only be negative on our first count, so we should just retry in
- // that case.
- if (first) {
- if (ABSL_PREDICT_TRUE(--next_sample.next_sample > 0)) return nullptr;
- return SampleSlow(next_sample, inline_element_size);
- }
-
- return GlobalHashtablezSampler().Register(old_stride, inline_element_size);
-#endif
-}
-
-void UnsampleSlow(HashtablezInfo* info) {
- GlobalHashtablezSampler().Unregister(info);
-}
-
-void RecordInsertSlow(HashtablezInfo* info, size_t hash,
- size_t distance_from_desired) {
- // SwissTables probe in groups of 16, so scale this to count items probes and
- // not offset from desired.
- size_t probe_length = distance_from_desired;
-#ifdef ABSL_INTERNAL_HAVE_SSE2
- probe_length /= 16;
-#else
- probe_length /= 8;
-#endif
-
- info->hashes_bitwise_and.fetch_and(hash, std::memory_order_relaxed);
- info->hashes_bitwise_or.fetch_or(hash, std::memory_order_relaxed);
- info->hashes_bitwise_xor.fetch_xor(hash, std::memory_order_relaxed);
- info->max_probe_length.store(
- std::max(info->max_probe_length.load(std::memory_order_relaxed),
- probe_length),
- std::memory_order_relaxed);
- info->total_probe_length.fetch_add(probe_length, std::memory_order_relaxed);
- info->size.fetch_add(1, std::memory_order_relaxed);
-}
-
-void SetHashtablezConfigListener(HashtablezConfigListener l) {
- g_hashtablez_config_listener.store(l, std::memory_order_release);
-}
-
-bool IsHashtablezEnabled() {
- return g_hashtablez_enabled.load(std::memory_order_acquire);
-}
-
-void SetHashtablezEnabled(bool enabled) {
- SetHashtablezEnabledInternal(enabled);
- TriggerHashtablezConfigListener();
-}
-
-void SetHashtablezEnabledInternal(bool enabled) {
- g_hashtablez_enabled.store(enabled, std::memory_order_release);
-}
-
-int32_t GetHashtablezSampleParameter() {
- return g_hashtablez_sample_parameter.load(std::memory_order_acquire);
-}
-
-void SetHashtablezSampleParameter(int32_t rate) {
- SetHashtablezSampleParameterInternal(rate);
- TriggerHashtablezConfigListener();
-}
-
-void SetHashtablezSampleParameterInternal(int32_t rate) {
- if (rate > 0) {
- g_hashtablez_sample_parameter.store(rate, std::memory_order_release);
- } else {
- ABSL_RAW_LOG(ERROR, "Invalid hashtablez sample rate: %lld",
- static_cast<long long>(rate)); // NOLINT(runtime/int)
- }
-}
-
-size_t GetHashtablezMaxSamples() {
- return GlobalHashtablezSampler().GetMaxSamples();
-}
-
-void SetHashtablezMaxSamples(size_t max) {
- SetHashtablezMaxSamplesInternal(max);
- TriggerHashtablezConfigListener();
-}
-
-void SetHashtablezMaxSamplesInternal(size_t max) {
- if (max > 0) {
- GlobalHashtablezSampler().SetMaxSamples(max);
- } else {
- ABSL_RAW_LOG(ERROR, "Invalid hashtablez max samples: 0");
- }
-}
-
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/container/internal/hashtablez_sampler.h b/third_party/abseil-cpp/absl/container/internal/hashtablez_sampler.h
deleted file mode 100644
index a89518b..0000000
--- a/third_party/abseil-cpp/absl/container/internal/hashtablez_sampler.h
+++ /dev/null
@@ -1,299 +0,0 @@
-// Copyright 2018 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.
-//
-// -----------------------------------------------------------------------------
-// File: hashtablez_sampler.h
-// -----------------------------------------------------------------------------
-//
-// This header file defines the API for a low level library to sample hashtables
-// and collect runtime statistics about them.
-//
-// `HashtablezSampler` controls the lifecycle of `HashtablezInfo` objects which
-// store information about a single sample.
-//
-// `Record*` methods store information into samples.
-// `Sample()` and `Unsample()` make use of a single global sampler with
-// properties controlled by the flags hashtablez_enabled,
-// hashtablez_sample_rate, and hashtablez_max_samples.
-//
-// WARNING
-//
-// Using this sampling API may cause sampled Swiss tables to use the global
-// allocator (operator `new`) in addition to any custom allocator. If you
-// are using a table in an unusual circumstance where allocation or calling a
-// linux syscall is unacceptable, this could interfere.
-//
-// This utility is internal-only. Use at your own risk.
-
-#ifndef ABSL_CONTAINER_INTERNAL_HASHTABLEZ_SAMPLER_H_
-#define ABSL_CONTAINER_INTERNAL_HASHTABLEZ_SAMPLER_H_
-
-#include <atomic>
-#include <functional>
-#include <memory>
-#include <vector>
-
-#include "absl/base/config.h"
-#include "absl/base/internal/per_thread_tls.h"
-#include "absl/base/optimization.h"
-#include "absl/profiling/internal/sample_recorder.h"
-#include "absl/synchronization/mutex.h"
-#include "absl/utility/utility.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-
-// Stores information about a sampled hashtable. All mutations to this *must*
-// be made through `Record*` functions below. All reads from this *must* only
-// occur in the callback to `HashtablezSampler::Iterate`.
-struct HashtablezInfo : public profiling_internal::Sample<HashtablezInfo> {
- // Constructs the object but does not fill in any fields.
- HashtablezInfo();
- ~HashtablezInfo();
- HashtablezInfo(const HashtablezInfo&) = delete;
- HashtablezInfo& operator=(const HashtablezInfo&) = delete;
-
- // Puts the object into a clean state, fills in the logically `const` members,
- // blocking for any readers that are currently sampling the object.
- void PrepareForSampling(int64_t stride, size_t inline_element_size_value)
- ABSL_EXCLUSIVE_LOCKS_REQUIRED(init_mu);
-
- // These fields are mutated by the various Record* APIs and need to be
- // thread-safe.
- std::atomic<size_t> capacity;
- std::atomic<size_t> size;
- std::atomic<size_t> num_erases;
- std::atomic<size_t> num_rehashes;
- std::atomic<size_t> max_probe_length;
- std::atomic<size_t> total_probe_length;
- std::atomic<size_t> hashes_bitwise_or;
- std::atomic<size_t> hashes_bitwise_and;
- std::atomic<size_t> hashes_bitwise_xor;
- std::atomic<size_t> max_reserve;
-
- // All of the fields below are set by `PrepareForSampling`, they must not be
- // mutated in `Record*` functions. They are logically `const` in that sense.
- // These are guarded by init_mu, but that is not externalized to clients,
- // which can read them only during `SampleRecorder::Iterate` which will hold
- // the lock.
- static constexpr int kMaxStackDepth = 64;
- absl::Time create_time;
- int32_t depth;
- void* stack[kMaxStackDepth];
- size_t inline_element_size; // How big is the slot?
-};
-
-inline void RecordRehashSlow(HashtablezInfo* info, size_t total_probe_length) {
-#ifdef ABSL_INTERNAL_HAVE_SSE2
- total_probe_length /= 16;
-#else
- total_probe_length /= 8;
-#endif
- info->total_probe_length.store(total_probe_length, std::memory_order_relaxed);
- info->num_erases.store(0, std::memory_order_relaxed);
- // There is only one concurrent writer, so `load` then `store` is sufficient
- // instead of using `fetch_add`.
- info->num_rehashes.store(
- 1 + info->num_rehashes.load(std::memory_order_relaxed),
- std::memory_order_relaxed);
-}
-
-inline void RecordReservationSlow(HashtablezInfo* info,
- size_t target_capacity) {
- info->max_reserve.store(
- (std::max)(info->max_reserve.load(std::memory_order_relaxed),
- target_capacity),
- std::memory_order_relaxed);
-}
-
-inline void RecordClearedReservationSlow(HashtablezInfo* info) {
- info->max_reserve.store(0, std::memory_order_relaxed);
-}
-
-inline void RecordStorageChangedSlow(HashtablezInfo* info, size_t size,
- size_t capacity) {
- info->size.store(size, std::memory_order_relaxed);
- info->capacity.store(capacity, std::memory_order_relaxed);
- if (size == 0) {
- // This is a clear, reset the total/num_erases too.
- info->total_probe_length.store(0, std::memory_order_relaxed);
- info->num_erases.store(0, std::memory_order_relaxed);
- }
-}
-
-void RecordInsertSlow(HashtablezInfo* info, size_t hash,
- size_t distance_from_desired);
-
-inline void RecordEraseSlow(HashtablezInfo* info) {
- info->size.fetch_sub(1, std::memory_order_relaxed);
- // There is only one concurrent writer, so `load` then `store` is sufficient
- // instead of using `fetch_add`.
- info->num_erases.store(
- 1 + info->num_erases.load(std::memory_order_relaxed),
- std::memory_order_relaxed);
-}
-
-struct SamplingState {
- int64_t next_sample;
- // When we make a sampling decision, we record that distance so we can weight
- // each sample.
- int64_t sample_stride;
-};
-
-HashtablezInfo* SampleSlow(SamplingState& next_sample,
- size_t inline_element_size);
-void UnsampleSlow(HashtablezInfo* info);
-
-#if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
-#error ABSL_INTERNAL_HASHTABLEZ_SAMPLE cannot be directly set
-#endif // defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
-
-#if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
-class HashtablezInfoHandle {
- public:
- explicit HashtablezInfoHandle() : info_(nullptr) {}
- explicit HashtablezInfoHandle(HashtablezInfo* info) : info_(info) {}
- ~HashtablezInfoHandle() {
- if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
- UnsampleSlow(info_);
- }
-
- HashtablezInfoHandle(const HashtablezInfoHandle&) = delete;
- HashtablezInfoHandle& operator=(const HashtablezInfoHandle&) = delete;
-
- HashtablezInfoHandle(HashtablezInfoHandle&& o) noexcept
- : info_(absl::exchange(o.info_, nullptr)) {}
- HashtablezInfoHandle& operator=(HashtablezInfoHandle&& o) noexcept {
- if (ABSL_PREDICT_FALSE(info_ != nullptr)) {
- UnsampleSlow(info_);
- }
- info_ = absl::exchange(o.info_, nullptr);
- return *this;
- }
-
- inline void RecordStorageChanged(size_t size, size_t capacity) {
- if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
- RecordStorageChangedSlow(info_, size, capacity);
- }
-
- inline void RecordRehash(size_t total_probe_length) {
- if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
- RecordRehashSlow(info_, total_probe_length);
- }
-
- inline void RecordReservation(size_t target_capacity) {
- if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
- RecordReservationSlow(info_, target_capacity);
- }
-
- inline void RecordClearedReservation() {
- if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
- RecordClearedReservationSlow(info_);
- }
-
- inline void RecordInsert(size_t hash, size_t distance_from_desired) {
- if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
- RecordInsertSlow(info_, hash, distance_from_desired);
- }
-
- inline void RecordErase() {
- if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
- RecordEraseSlow(info_);
- }
-
- friend inline void swap(HashtablezInfoHandle& lhs,
- HashtablezInfoHandle& rhs) {
- std::swap(lhs.info_, rhs.info_);
- }
-
- private:
- friend class HashtablezInfoHandlePeer;
- HashtablezInfo* info_;
-};
-#else
-// Ensure that when Hashtablez is turned off at compile time, HashtablezInfo can
-// be removed by the linker, in order to reduce the binary size.
-class HashtablezInfoHandle {
- public:
- explicit HashtablezInfoHandle() = default;
- explicit HashtablezInfoHandle(std::nullptr_t) {}
-
- inline void RecordStorageChanged(size_t /*size*/, size_t /*capacity*/) {}
- inline void RecordRehash(size_t /*total_probe_length*/) {}
- inline void RecordReservation(size_t /*target_capacity*/) {}
- inline void RecordClearedReservation() {}
- inline void RecordInsert(size_t /*hash*/, size_t /*distance_from_desired*/) {}
- inline void RecordErase() {}
-
- friend inline void swap(HashtablezInfoHandle& /*lhs*/,
- HashtablezInfoHandle& /*rhs*/) {}
-};
-#endif // defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
-
-#if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
-extern ABSL_PER_THREAD_TLS_KEYWORD SamplingState global_next_sample;
-#endif // defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
-
-// Returns an RAII sampling handle that manages registration and unregistation
-// with the global sampler.
-inline HashtablezInfoHandle Sample(
- size_t inline_element_size ABSL_ATTRIBUTE_UNUSED) {
-#if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
- if (ABSL_PREDICT_TRUE(--global_next_sample.next_sample > 0)) {
- return HashtablezInfoHandle(nullptr);
- }
- return HashtablezInfoHandle(
- SampleSlow(global_next_sample, inline_element_size));
-#else
- return HashtablezInfoHandle(nullptr);
-#endif // !ABSL_PER_THREAD_TLS
-}
-
-using HashtablezSampler =
- ::absl::profiling_internal::SampleRecorder<HashtablezInfo>;
-
-// Returns a global Sampler.
-HashtablezSampler& GlobalHashtablezSampler();
-
-using HashtablezConfigListener = void (*)();
-void SetHashtablezConfigListener(HashtablezConfigListener l);
-
-// Enables or disables sampling for Swiss tables.
-bool IsHashtablezEnabled();
-void SetHashtablezEnabled(bool enabled);
-void SetHashtablezEnabledInternal(bool enabled);
-
-// Sets the rate at which Swiss tables will be sampled.
-int32_t GetHashtablezSampleParameter();
-void SetHashtablezSampleParameter(int32_t rate);
-void SetHashtablezSampleParameterInternal(int32_t rate);
-
-// Sets a soft max for the number of samples that will be kept.
-size_t GetHashtablezMaxSamples();
-void SetHashtablezMaxSamples(size_t max);
-void SetHashtablezMaxSamplesInternal(size_t max);
-
-// Configuration override.
-// This allows process-wide sampling without depending on order of
-// initialization of static storage duration objects.
-// The definition of this constant is weak, which allows us to inject a
-// different value for it at link time.
-extern "C" bool ABSL_INTERNAL_C_SYMBOL(AbslContainerInternalSampleEverything)();
-
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_INTERNAL_HASHTABLEZ_SAMPLER_H_
diff --git a/third_party/abseil-cpp/absl/container/internal/hashtablez_sampler_force_weak_definition.cc b/third_party/abseil-cpp/absl/container/internal/hashtablez_sampler_force_weak_definition.cc
deleted file mode 100644
index ed35a7e..0000000
--- a/third_party/abseil-cpp/absl/container/internal/hashtablez_sampler_force_weak_definition.cc
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright 2018 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/container/internal/hashtablez_sampler.h"
-
-#include "absl/base/attributes.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-
-// See hashtablez_sampler.h for details.
-extern "C" ABSL_ATTRIBUTE_WEAK bool ABSL_INTERNAL_C_SYMBOL(
- AbslContainerInternalSampleEverything)() {
- return false;
-}
-
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/container/internal/hashtablez_sampler_test.cc b/third_party/abseil-cpp/absl/container/internal/hashtablez_sampler_test.cc
deleted file mode 100644
index 665d518..0000000
--- a/third_party/abseil-cpp/absl/container/internal/hashtablez_sampler_test.cc
+++ /dev/null
@@ -1,428 +0,0 @@
-// Copyright 2018 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/container/internal/hashtablez_sampler.h"
-
-#include <atomic>
-#include <limits>
-#include <random>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/base/attributes.h"
-#include "absl/base/config.h"
-#include "absl/profiling/internal/sample_recorder.h"
-#include "absl/synchronization/blocking_counter.h"
-#include "absl/synchronization/internal/thread_pool.h"
-#include "absl/synchronization/mutex.h"
-#include "absl/synchronization/notification.h"
-#include "absl/time/clock.h"
-#include "absl/time/time.h"
-
-#ifdef ABSL_INTERNAL_HAVE_SSE2
-constexpr int kProbeLength = 16;
-#else
-constexpr int kProbeLength = 8;
-#endif
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-#if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
-class HashtablezInfoHandlePeer {
- public:
- static bool IsSampled(const HashtablezInfoHandle& h) {
- return h.info_ != nullptr;
- }
-
- static HashtablezInfo* GetInfo(HashtablezInfoHandle* h) { return h->info_; }
-};
-#else
-class HashtablezInfoHandlePeer {
- public:
- static bool IsSampled(const HashtablezInfoHandle&) { return false; }
- static HashtablezInfo* GetInfo(HashtablezInfoHandle*) { return nullptr; }
-};
-#endif // defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
-
-namespace {
-using ::absl::synchronization_internal::ThreadPool;
-using ::testing::IsEmpty;
-using ::testing::UnorderedElementsAre;
-
-std::vector<size_t> GetSizes(HashtablezSampler* s) {
- std::vector<size_t> res;
- s->Iterate([&](const HashtablezInfo& info) {
- res.push_back(info.size.load(std::memory_order_acquire));
- });
- return res;
-}
-
-HashtablezInfo* Register(HashtablezSampler* s, size_t size) {
- const int64_t test_stride = 123;
- const size_t test_element_size = 17;
- auto* info = s->Register(test_stride, test_element_size);
- assert(info != nullptr);
- info->size.store(size);
- return info;
-}
-
-TEST(HashtablezInfoTest, PrepareForSampling) {
- absl::Time test_start = absl::Now();
- const int64_t test_stride = 123;
- const size_t test_element_size = 17;
- HashtablezInfo info;
- absl::MutexLock l(&info.init_mu);
- info.PrepareForSampling(test_stride, test_element_size);
-
- EXPECT_EQ(info.capacity.load(), 0);
- EXPECT_EQ(info.size.load(), 0);
- EXPECT_EQ(info.num_erases.load(), 0);
- EXPECT_EQ(info.num_rehashes.load(), 0);
- EXPECT_EQ(info.max_probe_length.load(), 0);
- EXPECT_EQ(info.total_probe_length.load(), 0);
- EXPECT_EQ(info.hashes_bitwise_or.load(), 0);
- EXPECT_EQ(info.hashes_bitwise_and.load(), ~size_t{});
- EXPECT_EQ(info.hashes_bitwise_xor.load(), 0);
- EXPECT_EQ(info.max_reserve.load(), 0);
- EXPECT_GE(info.create_time, test_start);
- EXPECT_EQ(info.weight, test_stride);
- EXPECT_EQ(info.inline_element_size, test_element_size);
-
- info.capacity.store(1, std::memory_order_relaxed);
- info.size.store(1, std::memory_order_relaxed);
- info.num_erases.store(1, std::memory_order_relaxed);
- info.max_probe_length.store(1, std::memory_order_relaxed);
- info.total_probe_length.store(1, std::memory_order_relaxed);
- info.hashes_bitwise_or.store(1, std::memory_order_relaxed);
- info.hashes_bitwise_and.store(1, std::memory_order_relaxed);
- info.hashes_bitwise_xor.store(1, std::memory_order_relaxed);
- info.max_reserve.store(1, std::memory_order_relaxed);
- info.create_time = test_start - absl::Hours(20);
-
- info.PrepareForSampling(test_stride * 2, test_element_size);
- EXPECT_EQ(info.capacity.load(), 0);
- EXPECT_EQ(info.size.load(), 0);
- EXPECT_EQ(info.num_erases.load(), 0);
- EXPECT_EQ(info.num_rehashes.load(), 0);
- EXPECT_EQ(info.max_probe_length.load(), 0);
- EXPECT_EQ(info.total_probe_length.load(), 0);
- EXPECT_EQ(info.hashes_bitwise_or.load(), 0);
- EXPECT_EQ(info.hashes_bitwise_and.load(), ~size_t{});
- EXPECT_EQ(info.hashes_bitwise_xor.load(), 0);
- EXPECT_EQ(info.max_reserve.load(), 0);
- EXPECT_EQ(info.weight, 2 * test_stride);
- EXPECT_EQ(info.inline_element_size, test_element_size);
- EXPECT_GE(info.create_time, test_start);
-}
-
-TEST(HashtablezInfoTest, RecordStorageChanged) {
- HashtablezInfo info;
- absl::MutexLock l(&info.init_mu);
- const int64_t test_stride = 21;
- const size_t test_element_size = 19;
- info.PrepareForSampling(test_stride, test_element_size);
- RecordStorageChangedSlow(&info, 17, 47);
- EXPECT_EQ(info.size.load(), 17);
- EXPECT_EQ(info.capacity.load(), 47);
- RecordStorageChangedSlow(&info, 20, 20);
- EXPECT_EQ(info.size.load(), 20);
- EXPECT_EQ(info.capacity.load(), 20);
-}
-
-TEST(HashtablezInfoTest, RecordInsert) {
- HashtablezInfo info;
- absl::MutexLock l(&info.init_mu);
- const int64_t test_stride = 25;
- const size_t test_element_size = 23;
- info.PrepareForSampling(test_stride, test_element_size);
- EXPECT_EQ(info.max_probe_length.load(), 0);
- RecordInsertSlow(&info, 0x0000FF00, 6 * kProbeLength);
- EXPECT_EQ(info.max_probe_length.load(), 6);
- EXPECT_EQ(info.hashes_bitwise_and.load(), 0x0000FF00);
- EXPECT_EQ(info.hashes_bitwise_or.load(), 0x0000FF00);
- EXPECT_EQ(info.hashes_bitwise_xor.load(), 0x0000FF00);
- RecordInsertSlow(&info, 0x000FF000, 4 * kProbeLength);
- EXPECT_EQ(info.max_probe_length.load(), 6);
- EXPECT_EQ(info.hashes_bitwise_and.load(), 0x0000F000);
- EXPECT_EQ(info.hashes_bitwise_or.load(), 0x000FFF00);
- EXPECT_EQ(info.hashes_bitwise_xor.load(), 0x000F0F00);
- RecordInsertSlow(&info, 0x00FF0000, 12 * kProbeLength);
- EXPECT_EQ(info.max_probe_length.load(), 12);
- EXPECT_EQ(info.hashes_bitwise_and.load(), 0x00000000);
- EXPECT_EQ(info.hashes_bitwise_or.load(), 0x00FFFF00);
- EXPECT_EQ(info.hashes_bitwise_xor.load(), 0x00F00F00);
-}
-
-TEST(HashtablezInfoTest, RecordErase) {
- const int64_t test_stride = 31;
- const size_t test_element_size = 29;
- HashtablezInfo info;
- absl::MutexLock l(&info.init_mu);
- info.PrepareForSampling(test_stride, test_element_size);
- EXPECT_EQ(info.num_erases.load(), 0);
- EXPECT_EQ(info.size.load(), 0);
- RecordInsertSlow(&info, 0x0000FF00, 6 * kProbeLength);
- EXPECT_EQ(info.size.load(), 1);
- RecordEraseSlow(&info);
- EXPECT_EQ(info.size.load(), 0);
- EXPECT_EQ(info.num_erases.load(), 1);
- EXPECT_EQ(info.inline_element_size, test_element_size);
-}
-
-TEST(HashtablezInfoTest, RecordRehash) {
- const int64_t test_stride = 33;
- const size_t test_element_size = 31;
- HashtablezInfo info;
- absl::MutexLock l(&info.init_mu);
- info.PrepareForSampling(test_stride, test_element_size);
- RecordInsertSlow(&info, 0x1, 0);
- RecordInsertSlow(&info, 0x2, kProbeLength);
- RecordInsertSlow(&info, 0x4, kProbeLength);
- RecordInsertSlow(&info, 0x8, 2 * kProbeLength);
- EXPECT_EQ(info.size.load(), 4);
- EXPECT_EQ(info.total_probe_length.load(), 4);
-
- RecordEraseSlow(&info);
- RecordEraseSlow(&info);
- EXPECT_EQ(info.size.load(), 2);
- EXPECT_EQ(info.total_probe_length.load(), 4);
- EXPECT_EQ(info.num_erases.load(), 2);
-
- RecordRehashSlow(&info, 3 * kProbeLength);
- EXPECT_EQ(info.size.load(), 2);
- EXPECT_EQ(info.total_probe_length.load(), 3);
- EXPECT_EQ(info.num_erases.load(), 0);
- EXPECT_EQ(info.num_rehashes.load(), 1);
- EXPECT_EQ(info.inline_element_size, test_element_size);
-}
-
-TEST(HashtablezInfoTest, RecordReservation) {
- HashtablezInfo info;
- absl::MutexLock l(&info.init_mu);
- const int64_t test_stride = 35;
- const size_t test_element_size = 33;
- info.PrepareForSampling(test_stride, test_element_size);
- RecordReservationSlow(&info, 3);
- EXPECT_EQ(info.max_reserve.load(), 3);
-
- RecordReservationSlow(&info, 2);
- // High watermark does not change
- EXPECT_EQ(info.max_reserve.load(), 3);
-
- RecordReservationSlow(&info, 10);
- // High watermark does change
- EXPECT_EQ(info.max_reserve.load(), 10);
-}
-
-#if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
-TEST(HashtablezSamplerTest, SmallSampleParameter) {
- const size_t test_element_size = 31;
- SetHashtablezEnabled(true);
- SetHashtablezSampleParameter(100);
-
- for (int i = 0; i < 1000; ++i) {
- SamplingState next_sample = {0, 0};
- HashtablezInfo* sample = SampleSlow(next_sample, test_element_size);
- EXPECT_GT(next_sample.next_sample, 0);
- EXPECT_EQ(next_sample.next_sample, next_sample.sample_stride);
- EXPECT_NE(sample, nullptr);
- UnsampleSlow(sample);
- }
-}
-
-TEST(HashtablezSamplerTest, LargeSampleParameter) {
- const size_t test_element_size = 31;
- SetHashtablezEnabled(true);
- SetHashtablezSampleParameter(std::numeric_limits<int32_t>::max());
-
- for (int i = 0; i < 1000; ++i) {
- SamplingState next_sample = {0, 0};
- HashtablezInfo* sample = SampleSlow(next_sample, test_element_size);
- EXPECT_GT(next_sample.next_sample, 0);
- EXPECT_EQ(next_sample.next_sample, next_sample.sample_stride);
- EXPECT_NE(sample, nullptr);
- UnsampleSlow(sample);
- }
-}
-
-TEST(HashtablezSamplerTest, Sample) {
- const size_t test_element_size = 31;
- SetHashtablezEnabled(true);
- SetHashtablezSampleParameter(100);
- int64_t num_sampled = 0;
- int64_t total = 0;
- double sample_rate = 0.0;
- for (int i = 0; i < 1000000; ++i) {
- HashtablezInfoHandle h = Sample(test_element_size);
- ++total;
- if (HashtablezInfoHandlePeer::IsSampled(h)) {
- ++num_sampled;
- }
- sample_rate = static_cast<double>(num_sampled) / total;
- if (0.005 < sample_rate && sample_rate < 0.015) break;
- }
- EXPECT_NEAR(sample_rate, 0.01, 0.005);
-}
-
-TEST(HashtablezSamplerTest, Handle) {
- auto& sampler = GlobalHashtablezSampler();
- const int64_t test_stride = 41;
- const size_t test_element_size = 39;
- HashtablezInfoHandle h(sampler.Register(test_stride, test_element_size));
- auto* info = HashtablezInfoHandlePeer::GetInfo(&h);
- info->hashes_bitwise_and.store(0x12345678, std::memory_order_relaxed);
-
- bool found = false;
- sampler.Iterate([&](const HashtablezInfo& h) {
- if (&h == info) {
- EXPECT_EQ(h.weight, test_stride);
- EXPECT_EQ(h.hashes_bitwise_and.load(), 0x12345678);
- found = true;
- }
- });
- EXPECT_TRUE(found);
-
- h = HashtablezInfoHandle();
- found = false;
- sampler.Iterate([&](const HashtablezInfo& h) {
- if (&h == info) {
- // this will only happen if some other thread has resurrected the info
- // the old handle was using.
- if (h.hashes_bitwise_and.load() == 0x12345678) {
- found = true;
- }
- }
- });
- EXPECT_FALSE(found);
-}
-#endif
-
-
-TEST(HashtablezSamplerTest, Registration) {
- HashtablezSampler sampler;
- auto* info1 = Register(&sampler, 1);
- EXPECT_THAT(GetSizes(&sampler), UnorderedElementsAre(1));
-
- auto* info2 = Register(&sampler, 2);
- EXPECT_THAT(GetSizes(&sampler), UnorderedElementsAre(1, 2));
- info1->size.store(3);
- EXPECT_THAT(GetSizes(&sampler), UnorderedElementsAre(3, 2));
-
- sampler.Unregister(info1);
- sampler.Unregister(info2);
-}
-
-TEST(HashtablezSamplerTest, Unregistration) {
- HashtablezSampler sampler;
- std::vector<HashtablezInfo*> infos;
- for (size_t i = 0; i < 3; ++i) {
- infos.push_back(Register(&sampler, i));
- }
- EXPECT_THAT(GetSizes(&sampler), UnorderedElementsAre(0, 1, 2));
-
- sampler.Unregister(infos[1]);
- EXPECT_THAT(GetSizes(&sampler), UnorderedElementsAre(0, 2));
-
- infos.push_back(Register(&sampler, 3));
- infos.push_back(Register(&sampler, 4));
- EXPECT_THAT(GetSizes(&sampler), UnorderedElementsAre(0, 2, 3, 4));
- sampler.Unregister(infos[3]);
- EXPECT_THAT(GetSizes(&sampler), UnorderedElementsAre(0, 2, 4));
-
- sampler.Unregister(infos[0]);
- sampler.Unregister(infos[2]);
- sampler.Unregister(infos[4]);
- EXPECT_THAT(GetSizes(&sampler), IsEmpty());
-}
-
-TEST(HashtablezSamplerTest, MultiThreaded) {
- HashtablezSampler sampler;
- Notification stop;
- ThreadPool pool(10);
-
- for (int i = 0; i < 10; ++i) {
- const int64_t sampling_stride = 11 + i % 3;
- const size_t elt_size = 10 + i % 2;
- pool.Schedule([&sampler, &stop, sampling_stride, elt_size]() {
- std::random_device rd;
- std::mt19937 gen(rd());
-
- std::vector<HashtablezInfo*> infoz;
- while (!stop.HasBeenNotified()) {
- if (infoz.empty()) {
- infoz.push_back(sampler.Register(sampling_stride, elt_size));
- }
- switch (std::uniform_int_distribution<>(0, 2)(gen)) {
- case 0: {
- infoz.push_back(sampler.Register(sampling_stride, elt_size));
- break;
- }
- case 1: {
- size_t p =
- std::uniform_int_distribution<>(0, infoz.size() - 1)(gen);
- HashtablezInfo* info = infoz[p];
- infoz[p] = infoz.back();
- infoz.pop_back();
- EXPECT_EQ(info->weight, sampling_stride);
- sampler.Unregister(info);
- break;
- }
- case 2: {
- absl::Duration oldest = absl::ZeroDuration();
- sampler.Iterate([&](const HashtablezInfo& info) {
- oldest = std::max(oldest, absl::Now() - info.create_time);
- });
- ASSERT_GE(oldest, absl::ZeroDuration());
- break;
- }
- }
- }
- });
- }
- // The threads will hammer away. Give it a little bit of time for tsan to
- // spot errors.
- absl::SleepFor(absl::Seconds(3));
- stop.Notify();
-}
-
-TEST(HashtablezSamplerTest, Callback) {
- HashtablezSampler sampler;
-
- auto* info1 = Register(&sampler, 1);
- auto* info2 = Register(&sampler, 2);
-
- static const HashtablezInfo* expected;
-
- auto callback = [](const HashtablezInfo& info) {
- // We can't use `info` outside of this callback because the object will be
- // disposed as soon as we return from here.
- EXPECT_EQ(&info, expected);
- };
-
- // Set the callback.
- EXPECT_EQ(sampler.SetDisposeCallback(callback), nullptr);
- expected = info1;
- sampler.Unregister(info1);
-
- // Unset the callback.
- EXPECT_EQ(callback, sampler.SetDisposeCallback(nullptr));
- expected = nullptr; // no more calls.
- sampler.Unregister(info2);
-}
-
-} // namespace
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/container/internal/inlined_vector.h b/third_party/abseil-cpp/absl/container/internal/inlined_vector.h
deleted file mode 100644
index e2dd843..0000000
--- a/third_party/abseil-cpp/absl/container/internal/inlined_vector.h
+++ /dev/null
@@ -1,1022 +0,0 @@
-// Copyright 2019 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_CONTAINER_INTERNAL_INLINED_VECTOR_H_
-#define ABSL_CONTAINER_INTERNAL_INLINED_VECTOR_H_
-
-#include <algorithm>
-#include <cstddef>
-#include <cstring>
-#include <iterator>
-#include <limits>
-#include <memory>
-#include <new>
-#include <type_traits>
-#include <utility>
-
-#include "absl/base/attributes.h"
-#include "absl/base/macros.h"
-#include "absl/container/internal/compressed_tuple.h"
-#include "absl/memory/memory.h"
-#include "absl/meta/type_traits.h"
-#include "absl/types/span.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace inlined_vector_internal {
-
-// GCC does not deal very well with the below code
-#if !defined(__clang__) && defined(__GNUC__)
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Warray-bounds"
-#endif
-
-template <typename A>
-using AllocatorTraits = std::allocator_traits<A>;
-template <typename A>
-using ValueType = typename AllocatorTraits<A>::value_type;
-template <typename A>
-using SizeType = typename AllocatorTraits<A>::size_type;
-template <typename A>
-using Pointer = typename AllocatorTraits<A>::pointer;
-template <typename A>
-using ConstPointer = typename AllocatorTraits<A>::const_pointer;
-template <typename A>
-using SizeType = typename AllocatorTraits<A>::size_type;
-template <typename A>
-using DifferenceType = typename AllocatorTraits<A>::difference_type;
-template <typename A>
-using Reference = ValueType<A>&;
-template <typename A>
-using ConstReference = const ValueType<A>&;
-template <typename A>
-using Iterator = Pointer<A>;
-template <typename A>
-using ConstIterator = ConstPointer<A>;
-template <typename A>
-using ReverseIterator = typename std::reverse_iterator<Iterator<A>>;
-template <typename A>
-using ConstReverseIterator = typename std::reverse_iterator<ConstIterator<A>>;
-template <typename A>
-using MoveIterator = typename std::move_iterator<Iterator<A>>;
-
-template <typename Iterator>
-using IsAtLeastForwardIterator = std::is_convertible<
- typename std::iterator_traits<Iterator>::iterator_category,
- std::forward_iterator_tag>;
-
-template <typename A>
-using IsMemcpyOk =
- absl::conjunction<std::is_same<A, std::allocator<ValueType<A>>>,
- absl::is_trivially_copy_constructible<ValueType<A>>,
- absl::is_trivially_copy_assignable<ValueType<A>>,
- absl::is_trivially_destructible<ValueType<A>>>;
-
-template <typename A>
-using IsMoveAssignOk = std::is_move_assignable<ValueType<A>>;
-template <typename A>
-using IsSwapOk = absl::type_traits_internal::IsSwappable<ValueType<A>>;
-
-template <typename T>
-struct TypeIdentity {
- using type = T;
-};
-
-// Used for function arguments in template functions to prevent ADL by forcing
-// callers to explicitly specify the template parameter.
-template <typename T>
-using NoTypeDeduction = typename TypeIdentity<T>::type;
-
-template <typename A, bool IsTriviallyDestructible =
- absl::is_trivially_destructible<ValueType<A>>::value>
-struct DestroyAdapter;
-
-template <typename A>
-struct DestroyAdapter<A, /* IsTriviallyDestructible */ false> {
- static void DestroyElements(A& allocator, Pointer<A> destroy_first,
- SizeType<A> destroy_size) {
- for (SizeType<A> i = destroy_size; i != 0;) {
- --i;
- AllocatorTraits<A>::destroy(allocator, destroy_first + i);
- }
- }
-};
-
-template <typename A>
-struct DestroyAdapter<A, /* IsTriviallyDestructible */ true> {
- static void DestroyElements(A& allocator, Pointer<A> destroy_first,
- SizeType<A> destroy_size) {
- static_cast<void>(allocator);
- static_cast<void>(destroy_first);
- static_cast<void>(destroy_size);
- }
-};
-
-template <typename A>
-struct Allocation {
- Pointer<A> data;
- SizeType<A> capacity;
-};
-
-template <typename A,
- bool IsOverAligned =
- (alignof(ValueType<A>) > ABSL_INTERNAL_DEFAULT_NEW_ALIGNMENT)>
-struct MallocAdapter {
- static Allocation<A> Allocate(A& allocator, SizeType<A> requested_capacity) {
- return {AllocatorTraits<A>::allocate(allocator, requested_capacity),
- requested_capacity};
- }
-
- static void Deallocate(A& allocator, Pointer<A> pointer,
- SizeType<A> capacity) {
- AllocatorTraits<A>::deallocate(allocator, pointer, capacity);
- }
-};
-
-template <typename A, typename ValueAdapter>
-void ConstructElements(NoTypeDeduction<A>& allocator,
- Pointer<A> construct_first, ValueAdapter& values,
- SizeType<A> construct_size) {
- for (SizeType<A> i = 0; i < construct_size; ++i) {
- ABSL_INTERNAL_TRY { values.ConstructNext(allocator, construct_first + i); }
- ABSL_INTERNAL_CATCH_ANY {
- DestroyAdapter<A>::DestroyElements(allocator, construct_first, i);
- ABSL_INTERNAL_RETHROW;
- }
- }
-}
-
-template <typename A, typename ValueAdapter>
-void AssignElements(Pointer<A> assign_first, ValueAdapter& values,
- SizeType<A> assign_size) {
- for (SizeType<A> i = 0; i < assign_size; ++i) {
- values.AssignNext(assign_first + i);
- }
-}
-
-template <typename A>
-struct StorageView {
- Pointer<A> data;
- SizeType<A> size;
- SizeType<A> capacity;
-};
-
-template <typename A, typename Iterator>
-class IteratorValueAdapter {
- public:
- explicit IteratorValueAdapter(const Iterator& it) : it_(it) {}
-
- void ConstructNext(A& allocator, Pointer<A> construct_at) {
- AllocatorTraits<A>::construct(allocator, construct_at, *it_);
- ++it_;
- }
-
- void AssignNext(Pointer<A> assign_at) {
- *assign_at = *it_;
- ++it_;
- }
-
- private:
- Iterator it_;
-};
-
-template <typename A>
-class CopyValueAdapter {
- public:
- explicit CopyValueAdapter(ConstPointer<A> p) : ptr_(p) {}
-
- void ConstructNext(A& allocator, Pointer<A> construct_at) {
- AllocatorTraits<A>::construct(allocator, construct_at, *ptr_);
- }
-
- void AssignNext(Pointer<A> assign_at) { *assign_at = *ptr_; }
-
- private:
- ConstPointer<A> ptr_;
-};
-
-template <typename A>
-class DefaultValueAdapter {
- public:
- explicit DefaultValueAdapter() {}
-
- void ConstructNext(A& allocator, Pointer<A> construct_at) {
- AllocatorTraits<A>::construct(allocator, construct_at);
- }
-
- void AssignNext(Pointer<A> assign_at) { *assign_at = ValueType<A>(); }
-};
-
-template <typename A>
-class AllocationTransaction {
- public:
- explicit AllocationTransaction(A& allocator)
- : allocator_data_(allocator, nullptr), capacity_(0) {}
-
- ~AllocationTransaction() {
- if (DidAllocate()) {
- MallocAdapter<A>::Deallocate(GetAllocator(), GetData(), GetCapacity());
- }
- }
-
- AllocationTransaction(const AllocationTransaction&) = delete;
- void operator=(const AllocationTransaction&) = delete;
-
- A& GetAllocator() { return allocator_data_.template get<0>(); }
- Pointer<A>& GetData() { return allocator_data_.template get<1>(); }
- SizeType<A>& GetCapacity() { return capacity_; }
-
- bool DidAllocate() { return GetData() != nullptr; }
-
- Pointer<A> Allocate(SizeType<A> requested_capacity) {
- Allocation<A> result =
- MallocAdapter<A>::Allocate(GetAllocator(), requested_capacity);
- GetData() = result.data;
- GetCapacity() = result.capacity;
- return result.data;
- }
-
- ABSL_MUST_USE_RESULT Allocation<A> Release() && {
- Allocation<A> result = {GetData(), GetCapacity()};
- Reset();
- return result;
- }
-
- private:
- void Reset() {
- GetData() = nullptr;
- GetCapacity() = 0;
- }
-
- container_internal::CompressedTuple<A, Pointer<A>> allocator_data_;
- SizeType<A> capacity_;
-};
-
-template <typename A>
-class ConstructionTransaction {
- public:
- explicit ConstructionTransaction(A& allocator)
- : allocator_data_(allocator, nullptr), size_(0) {}
-
- ~ConstructionTransaction() {
- if (DidConstruct()) {
- DestroyAdapter<A>::DestroyElements(GetAllocator(), GetData(), GetSize());
- }
- }
-
- ConstructionTransaction(const ConstructionTransaction&) = delete;
- void operator=(const ConstructionTransaction&) = delete;
-
- A& GetAllocator() { return allocator_data_.template get<0>(); }
- Pointer<A>& GetData() { return allocator_data_.template get<1>(); }
- SizeType<A>& GetSize() { return size_; }
-
- bool DidConstruct() { return GetData() != nullptr; }
- template <typename ValueAdapter>
- void Construct(Pointer<A> data, ValueAdapter& values, SizeType<A> size) {
- ConstructElements<A>(GetAllocator(), data, values, size);
- GetData() = data;
- GetSize() = size;
- }
- void Commit() && {
- GetData() = nullptr;
- GetSize() = 0;
- }
-
- private:
- container_internal::CompressedTuple<A, Pointer<A>> allocator_data_;
- SizeType<A> size_;
-};
-
-template <typename T, size_t N, typename A>
-class Storage {
- public:
- struct MemcpyPolicy {};
- struct ElementwiseAssignPolicy {};
- struct ElementwiseSwapPolicy {};
- struct ElementwiseConstructPolicy {};
-
- using MoveAssignmentPolicy = absl::conditional_t<
- IsMemcpyOk<A>::value, MemcpyPolicy,
- absl::conditional_t<IsMoveAssignOk<A>::value, ElementwiseAssignPolicy,
- ElementwiseConstructPolicy>>;
- using SwapPolicy = absl::conditional_t<
- IsMemcpyOk<A>::value, MemcpyPolicy,
- absl::conditional_t<IsSwapOk<A>::value, ElementwiseSwapPolicy,
- ElementwiseConstructPolicy>>;
-
- static SizeType<A> NextCapacity(SizeType<A> current_capacity) {
- return current_capacity * 2;
- }
-
- static SizeType<A> ComputeCapacity(SizeType<A> current_capacity,
- SizeType<A> requested_capacity) {
- return (std::max)(NextCapacity(current_capacity), requested_capacity);
- }
-
- // ---------------------------------------------------------------------------
- // Storage Constructors and Destructor
- // ---------------------------------------------------------------------------
-
- Storage() : metadata_(A(), /* size and is_allocated */ 0u) {}
-
- explicit Storage(const A& allocator)
- : metadata_(allocator, /* size and is_allocated */ 0u) {}
-
- ~Storage() {
- if (GetSizeAndIsAllocated() == 0) {
- // Empty and not allocated; nothing to do.
- } else if (IsMemcpyOk<A>::value) {
- // No destructors need to be run; just deallocate if necessary.
- DeallocateIfAllocated();
- } else {
- DestroyContents();
- }
- }
-
- // ---------------------------------------------------------------------------
- // Storage Member Accessors
- // ---------------------------------------------------------------------------
-
- SizeType<A>& GetSizeAndIsAllocated() { return metadata_.template get<1>(); }
-
- const SizeType<A>& GetSizeAndIsAllocated() const {
- return metadata_.template get<1>();
- }
-
- SizeType<A> GetSize() const { return GetSizeAndIsAllocated() >> 1; }
-
- bool GetIsAllocated() const { return GetSizeAndIsAllocated() & 1; }
-
- Pointer<A> GetAllocatedData() { return data_.allocated.allocated_data; }
-
- ConstPointer<A> GetAllocatedData() const {
- return data_.allocated.allocated_data;
- }
-
- Pointer<A> GetInlinedData() {
- return reinterpret_cast<Pointer<A>>(
- std::addressof(data_.inlined.inlined_data[0]));
- }
-
- ConstPointer<A> GetInlinedData() const {
- return reinterpret_cast<ConstPointer<A>>(
- std::addressof(data_.inlined.inlined_data[0]));
- }
-
- SizeType<A> GetAllocatedCapacity() const {
- return data_.allocated.allocated_capacity;
- }
-
- SizeType<A> GetInlinedCapacity() const { return static_cast<SizeType<A>>(N); }
-
- StorageView<A> MakeStorageView() {
- return GetIsAllocated() ? StorageView<A>{GetAllocatedData(), GetSize(),
- GetAllocatedCapacity()}
- : StorageView<A>{GetInlinedData(), GetSize(),
- GetInlinedCapacity()};
- }
-
- A& GetAllocator() { return metadata_.template get<0>(); }
-
- const A& GetAllocator() const { return metadata_.template get<0>(); }
-
- // ---------------------------------------------------------------------------
- // Storage Member Mutators
- // ---------------------------------------------------------------------------
-
- ABSL_ATTRIBUTE_NOINLINE void InitFrom(const Storage& other);
-
- template <typename ValueAdapter>
- void Initialize(ValueAdapter values, SizeType<A> new_size);
-
- template <typename ValueAdapter>
- void Assign(ValueAdapter values, SizeType<A> new_size);
-
- template <typename ValueAdapter>
- void Resize(ValueAdapter values, SizeType<A> new_size);
-
- template <typename ValueAdapter>
- Iterator<A> Insert(ConstIterator<A> pos, ValueAdapter values,
- SizeType<A> insert_count);
-
- template <typename... Args>
- Reference<A> EmplaceBack(Args&&... args);
-
- Iterator<A> Erase(ConstIterator<A> from, ConstIterator<A> to);
-
- void Reserve(SizeType<A> requested_capacity);
-
- void ShrinkToFit();
-
- void Swap(Storage* other_storage_ptr);
-
- void SetIsAllocated() {
- GetSizeAndIsAllocated() |= static_cast<SizeType<A>>(1);
- }
-
- void UnsetIsAllocated() {
- GetSizeAndIsAllocated() &= ((std::numeric_limits<SizeType<A>>::max)() - 1);
- }
-
- void SetSize(SizeType<A> size) {
- GetSizeAndIsAllocated() =
- (size << 1) | static_cast<SizeType<A>>(GetIsAllocated());
- }
-
- void SetAllocatedSize(SizeType<A> size) {
- GetSizeAndIsAllocated() = (size << 1) | static_cast<SizeType<A>>(1);
- }
-
- void SetInlinedSize(SizeType<A> size) {
- GetSizeAndIsAllocated() = size << static_cast<SizeType<A>>(1);
- }
-
- void AddSize(SizeType<A> count) {
- GetSizeAndIsAllocated() += count << static_cast<SizeType<A>>(1);
- }
-
- void SubtractSize(SizeType<A> count) {
- ABSL_HARDENING_ASSERT(count <= GetSize());
-
- GetSizeAndIsAllocated() -= count << static_cast<SizeType<A>>(1);
- }
-
- void SetAllocation(Allocation<A> allocation) {
- data_.allocated.allocated_data = allocation.data;
- data_.allocated.allocated_capacity = allocation.capacity;
- }
-
- void MemcpyFrom(const Storage& other_storage) {
- ABSL_HARDENING_ASSERT(IsMemcpyOk<A>::value ||
- other_storage.GetIsAllocated());
-
- GetSizeAndIsAllocated() = other_storage.GetSizeAndIsAllocated();
- data_ = other_storage.data_;
- }
-
- void DeallocateIfAllocated() {
- if (GetIsAllocated()) {
- MallocAdapter<A>::Deallocate(GetAllocator(), GetAllocatedData(),
- GetAllocatedCapacity());
- }
- }
-
- private:
- ABSL_ATTRIBUTE_NOINLINE void DestroyContents();
-
- using Metadata = container_internal::CompressedTuple<A, SizeType<A>>;
-
- struct Allocated {
- Pointer<A> allocated_data;
- SizeType<A> allocated_capacity;
- };
-
- struct Inlined {
- alignas(ValueType<A>) char inlined_data[sizeof(ValueType<A>[N])];
- };
-
- union Data {
- Allocated allocated;
- Inlined inlined;
- };
-
- void SwapN(ElementwiseSwapPolicy, Storage* other, SizeType<A> n);
- void SwapN(ElementwiseConstructPolicy, Storage* other, SizeType<A> n);
-
- void SwapInlinedElements(MemcpyPolicy, Storage* other);
- template <typename NotMemcpyPolicy>
- void SwapInlinedElements(NotMemcpyPolicy, Storage* other);
-
- template <typename... Args>
- ABSL_ATTRIBUTE_NOINLINE Reference<A> EmplaceBackSlow(Args&&... args);
-
- Metadata metadata_;
- Data data_;
-};
-
-template <typename T, size_t N, typename A>
-void Storage<T, N, A>::DestroyContents() {
- Pointer<A> data = GetIsAllocated() ? GetAllocatedData() : GetInlinedData();
- DestroyAdapter<A>::DestroyElements(GetAllocator(), data, GetSize());
- DeallocateIfAllocated();
-}
-
-template <typename T, size_t N, typename A>
-void Storage<T, N, A>::InitFrom(const Storage& other) {
- const SizeType<A> n = other.GetSize();
- ABSL_HARDENING_ASSERT(n > 0); // Empty sources handled handled in caller.
- ConstPointer<A> src;
- Pointer<A> dst;
- if (!other.GetIsAllocated()) {
- dst = GetInlinedData();
- src = other.GetInlinedData();
- } else {
- // Because this is only called from the `InlinedVector` constructors, it's
- // safe to take on the allocation with size `0`. If `ConstructElements(...)`
- // throws, deallocation will be automatically handled by `~Storage()`.
- SizeType<A> requested_capacity = ComputeCapacity(GetInlinedCapacity(), n);
- Allocation<A> allocation =
- MallocAdapter<A>::Allocate(GetAllocator(), requested_capacity);
- SetAllocation(allocation);
- dst = allocation.data;
- src = other.GetAllocatedData();
- }
- if (IsMemcpyOk<A>::value) {
- std::memcpy(reinterpret_cast<char*>(dst),
- reinterpret_cast<const char*>(src), n * sizeof(ValueType<A>));
- } else {
- auto values = IteratorValueAdapter<A, ConstPointer<A>>(src);
- ConstructElements<A>(GetAllocator(), dst, values, n);
- }
- GetSizeAndIsAllocated() = other.GetSizeAndIsAllocated();
-}
-
-template <typename T, size_t N, typename A>
-template <typename ValueAdapter>
-auto Storage<T, N, A>::Initialize(ValueAdapter values, SizeType<A> new_size)
- -> void {
- // Only callable from constructors!
- ABSL_HARDENING_ASSERT(!GetIsAllocated());
- ABSL_HARDENING_ASSERT(GetSize() == 0);
-
- Pointer<A> construct_data;
- if (new_size > GetInlinedCapacity()) {
- // Because this is only called from the `InlinedVector` constructors, it's
- // safe to take on the allocation with size `0`. If `ConstructElements(...)`
- // throws, deallocation will be automatically handled by `~Storage()`.
- SizeType<A> requested_capacity =
- ComputeCapacity(GetInlinedCapacity(), new_size);
- Allocation<A> allocation =
- MallocAdapter<A>::Allocate(GetAllocator(), requested_capacity);
- construct_data = allocation.data;
- SetAllocation(allocation);
- SetIsAllocated();
- } else {
- construct_data = GetInlinedData();
- }
-
- ConstructElements<A>(GetAllocator(), construct_data, values, new_size);
-
- // Since the initial size was guaranteed to be `0` and the allocated bit is
- // already correct for either case, *adding* `new_size` gives us the correct
- // result faster than setting it directly.
- AddSize(new_size);
-}
-
-template <typename T, size_t N, typename A>
-template <typename ValueAdapter>
-auto Storage<T, N, A>::Assign(ValueAdapter values, SizeType<A> new_size)
- -> void {
- StorageView<A> storage_view = MakeStorageView();
-
- AllocationTransaction<A> allocation_tx(GetAllocator());
-
- absl::Span<ValueType<A>> assign_loop;
- absl::Span<ValueType<A>> construct_loop;
- absl::Span<ValueType<A>> destroy_loop;
-
- if (new_size > storage_view.capacity) {
- SizeType<A> requested_capacity =
- ComputeCapacity(storage_view.capacity, new_size);
- construct_loop = {allocation_tx.Allocate(requested_capacity), new_size};
- destroy_loop = {storage_view.data, storage_view.size};
- } else if (new_size > storage_view.size) {
- assign_loop = {storage_view.data, storage_view.size};
- construct_loop = {storage_view.data + storage_view.size,
- new_size - storage_view.size};
- } else {
- assign_loop = {storage_view.data, new_size};
- destroy_loop = {storage_view.data + new_size, storage_view.size - new_size};
- }
-
- AssignElements<A>(assign_loop.data(), values, assign_loop.size());
-
- ConstructElements<A>(GetAllocator(), construct_loop.data(), values,
- construct_loop.size());
-
- DestroyAdapter<A>::DestroyElements(GetAllocator(), destroy_loop.data(),
- destroy_loop.size());
-
- if (allocation_tx.DidAllocate()) {
- DeallocateIfAllocated();
- SetAllocation(std::move(allocation_tx).Release());
- SetIsAllocated();
- }
-
- SetSize(new_size);
-}
-
-template <typename T, size_t N, typename A>
-template <typename ValueAdapter>
-auto Storage<T, N, A>::Resize(ValueAdapter values, SizeType<A> new_size)
- -> void {
- StorageView<A> storage_view = MakeStorageView();
- Pointer<A> const base = storage_view.data;
- const SizeType<A> size = storage_view.size;
- A& alloc = GetAllocator();
- if (new_size <= size) {
- // Destroy extra old elements.
- DestroyAdapter<A>::DestroyElements(alloc, base + new_size, size - new_size);
- } else if (new_size <= storage_view.capacity) {
- // Construct new elements in place.
- ConstructElements<A>(alloc, base + size, values, new_size - size);
- } else {
- // Steps:
- // a. Allocate new backing store.
- // b. Construct new elements in new backing store.
- // c. Move existing elements from old backing store to new backing store.
- // d. Destroy all elements in old backing store.
- // Use transactional wrappers for the first two steps so we can roll
- // back if necessary due to exceptions.
- AllocationTransaction<A> allocation_tx(alloc);
- SizeType<A> requested_capacity =
- ComputeCapacity(storage_view.capacity, new_size);
- Pointer<A> new_data = allocation_tx.Allocate(requested_capacity);
-
- ConstructionTransaction<A> construction_tx(alloc);
- construction_tx.Construct(new_data + size, values, new_size - size);
-
- IteratorValueAdapter<A, MoveIterator<A>> move_values(
- (MoveIterator<A>(base)));
- ConstructElements<A>(alloc, new_data, move_values, size);
-
- DestroyAdapter<A>::DestroyElements(alloc, base, size);
- std::move(construction_tx).Commit();
- DeallocateIfAllocated();
- SetAllocation(std::move(allocation_tx).Release());
- SetIsAllocated();
- }
- SetSize(new_size);
-}
-
-template <typename T, size_t N, typename A>
-template <typename ValueAdapter>
-auto Storage<T, N, A>::Insert(ConstIterator<A> pos, ValueAdapter values,
- SizeType<A> insert_count) -> Iterator<A> {
- StorageView<A> storage_view = MakeStorageView();
-
- auto insert_index = static_cast<SizeType<A>>(
- std::distance(ConstIterator<A>(storage_view.data), pos));
- SizeType<A> insert_end_index = insert_index + insert_count;
- SizeType<A> new_size = storage_view.size + insert_count;
-
- if (new_size > storage_view.capacity) {
- AllocationTransaction<A> allocation_tx(GetAllocator());
- ConstructionTransaction<A> construction_tx(GetAllocator());
- ConstructionTransaction<A> move_construction_tx(GetAllocator());
-
- IteratorValueAdapter<A, MoveIterator<A>> move_values(
- MoveIterator<A>(storage_view.data));
-
- SizeType<A> requested_capacity =
- ComputeCapacity(storage_view.capacity, new_size);
- Pointer<A> new_data = allocation_tx.Allocate(requested_capacity);
-
- construction_tx.Construct(new_data + insert_index, values, insert_count);
-
- move_construction_tx.Construct(new_data, move_values, insert_index);
-
- ConstructElements<A>(GetAllocator(), new_data + insert_end_index,
- move_values, storage_view.size - insert_index);
-
- DestroyAdapter<A>::DestroyElements(GetAllocator(), storage_view.data,
- storage_view.size);
-
- std::move(construction_tx).Commit();
- std::move(move_construction_tx).Commit();
- DeallocateIfAllocated();
- SetAllocation(std::move(allocation_tx).Release());
-
- SetAllocatedSize(new_size);
- return Iterator<A>(new_data + insert_index);
- } else {
- SizeType<A> move_construction_destination_index =
- (std::max)(insert_end_index, storage_view.size);
-
- ConstructionTransaction<A> move_construction_tx(GetAllocator());
-
- IteratorValueAdapter<A, MoveIterator<A>> move_construction_values(
- MoveIterator<A>(storage_view.data +
- (move_construction_destination_index - insert_count)));
- absl::Span<ValueType<A>> move_construction = {
- storage_view.data + move_construction_destination_index,
- new_size - move_construction_destination_index};
-
- Pointer<A> move_assignment_values = storage_view.data + insert_index;
- absl::Span<ValueType<A>> move_assignment = {
- storage_view.data + insert_end_index,
- move_construction_destination_index - insert_end_index};
-
- absl::Span<ValueType<A>> insert_assignment = {move_assignment_values,
- move_construction.size()};
-
- absl::Span<ValueType<A>> insert_construction = {
- insert_assignment.data() + insert_assignment.size(),
- insert_count - insert_assignment.size()};
-
- move_construction_tx.Construct(move_construction.data(),
- move_construction_values,
- move_construction.size());
-
- for (Pointer<A>
- destination = move_assignment.data() + move_assignment.size(),
- last_destination = move_assignment.data(),
- source = move_assignment_values + move_assignment.size();
- ;) {
- --destination;
- --source;
- if (destination < last_destination) break;
- *destination = std::move(*source);
- }
-
- AssignElements<A>(insert_assignment.data(), values,
- insert_assignment.size());
-
- ConstructElements<A>(GetAllocator(), insert_construction.data(), values,
- insert_construction.size());
-
- std::move(move_construction_tx).Commit();
-
- AddSize(insert_count);
- return Iterator<A>(storage_view.data + insert_index);
- }
-}
-
-template <typename T, size_t N, typename A>
-template <typename... Args>
-auto Storage<T, N, A>::EmplaceBack(Args&&... args) -> Reference<A> {
- StorageView<A> storage_view = MakeStorageView();
- const SizeType<A> n = storage_view.size;
- if (ABSL_PREDICT_TRUE(n != storage_view.capacity)) {
- // Fast path; new element fits.
- Pointer<A> last_ptr = storage_view.data + n;
- AllocatorTraits<A>::construct(GetAllocator(), last_ptr,
- std::forward<Args>(args)...);
- AddSize(1);
- return *last_ptr;
- }
- // TODO(b/173712035): Annotate with musttail attribute to prevent regression.
- return EmplaceBackSlow(std::forward<Args>(args)...);
-}
-
-template <typename T, size_t N, typename A>
-template <typename... Args>
-auto Storage<T, N, A>::EmplaceBackSlow(Args&&... args) -> Reference<A> {
- StorageView<A> storage_view = MakeStorageView();
- AllocationTransaction<A> allocation_tx(GetAllocator());
- IteratorValueAdapter<A, MoveIterator<A>> move_values(
- MoveIterator<A>(storage_view.data));
- SizeType<A> requested_capacity = NextCapacity(storage_view.capacity);
- Pointer<A> construct_data = allocation_tx.Allocate(requested_capacity);
- Pointer<A> last_ptr = construct_data + storage_view.size;
-
- // Construct new element.
- AllocatorTraits<A>::construct(GetAllocator(), last_ptr,
- std::forward<Args>(args)...);
- // Move elements from old backing store to new backing store.
- ABSL_INTERNAL_TRY {
- ConstructElements<A>(GetAllocator(), allocation_tx.GetData(), move_values,
- storage_view.size);
- }
- ABSL_INTERNAL_CATCH_ANY {
- AllocatorTraits<A>::destroy(GetAllocator(), last_ptr);
- ABSL_INTERNAL_RETHROW;
- }
- // Destroy elements in old backing store.
- DestroyAdapter<A>::DestroyElements(GetAllocator(), storage_view.data,
- storage_view.size);
-
- DeallocateIfAllocated();
- SetAllocation(std::move(allocation_tx).Release());
- SetIsAllocated();
- AddSize(1);
- return *last_ptr;
-}
-
-template <typename T, size_t N, typename A>
-auto Storage<T, N, A>::Erase(ConstIterator<A> from, ConstIterator<A> to)
- -> Iterator<A> {
- StorageView<A> storage_view = MakeStorageView();
-
- auto erase_size = static_cast<SizeType<A>>(std::distance(from, to));
- auto erase_index = static_cast<SizeType<A>>(
- std::distance(ConstIterator<A>(storage_view.data), from));
- SizeType<A> erase_end_index = erase_index + erase_size;
-
- IteratorValueAdapter<A, MoveIterator<A>> move_values(
- MoveIterator<A>(storage_view.data + erase_end_index));
-
- AssignElements<A>(storage_view.data + erase_index, move_values,
- storage_view.size - erase_end_index);
-
- DestroyAdapter<A>::DestroyElements(
- GetAllocator(), storage_view.data + (storage_view.size - erase_size),
- erase_size);
-
- SubtractSize(erase_size);
- return Iterator<A>(storage_view.data + erase_index);
-}
-
-template <typename T, size_t N, typename A>
-auto Storage<T, N, A>::Reserve(SizeType<A> requested_capacity) -> void {
- StorageView<A> storage_view = MakeStorageView();
-
- if (ABSL_PREDICT_FALSE(requested_capacity <= storage_view.capacity)) return;
-
- AllocationTransaction<A> allocation_tx(GetAllocator());
-
- IteratorValueAdapter<A, MoveIterator<A>> move_values(
- MoveIterator<A>(storage_view.data));
-
- SizeType<A> new_requested_capacity =
- ComputeCapacity(storage_view.capacity, requested_capacity);
- Pointer<A> new_data = allocation_tx.Allocate(new_requested_capacity);
-
- ConstructElements<A>(GetAllocator(), new_data, move_values,
- storage_view.size);
-
- DestroyAdapter<A>::DestroyElements(GetAllocator(), storage_view.data,
- storage_view.size);
-
- DeallocateIfAllocated();
- SetAllocation(std::move(allocation_tx).Release());
- SetIsAllocated();
-}
-
-template <typename T, size_t N, typename A>
-auto Storage<T, N, A>::ShrinkToFit() -> void {
- // May only be called on allocated instances!
- ABSL_HARDENING_ASSERT(GetIsAllocated());
-
- StorageView<A> storage_view{GetAllocatedData(), GetSize(),
- GetAllocatedCapacity()};
-
- if (ABSL_PREDICT_FALSE(storage_view.size == storage_view.capacity)) return;
-
- AllocationTransaction<A> allocation_tx(GetAllocator());
-
- IteratorValueAdapter<A, MoveIterator<A>> move_values(
- MoveIterator<A>(storage_view.data));
-
- Pointer<A> construct_data;
- if (storage_view.size > GetInlinedCapacity()) {
- SizeType<A> requested_capacity = storage_view.size;
- construct_data = allocation_tx.Allocate(requested_capacity);
- if (allocation_tx.GetCapacity() >= storage_view.capacity) {
- // Already using the smallest available heap allocation.
- return;
- }
- } else {
- construct_data = GetInlinedData();
- }
-
- ABSL_INTERNAL_TRY {
- ConstructElements<A>(GetAllocator(), construct_data, move_values,
- storage_view.size);
- }
- ABSL_INTERNAL_CATCH_ANY {
- SetAllocation({storage_view.data, storage_view.capacity});
- ABSL_INTERNAL_RETHROW;
- }
-
- DestroyAdapter<A>::DestroyElements(GetAllocator(), storage_view.data,
- storage_view.size);
-
- MallocAdapter<A>::Deallocate(GetAllocator(), storage_view.data,
- storage_view.capacity);
-
- if (allocation_tx.DidAllocate()) {
- SetAllocation(std::move(allocation_tx).Release());
- } else {
- UnsetIsAllocated();
- }
-}
-
-template <typename T, size_t N, typename A>
-auto Storage<T, N, A>::Swap(Storage* other_storage_ptr) -> void {
- using std::swap;
- ABSL_HARDENING_ASSERT(this != other_storage_ptr);
-
- if (GetIsAllocated() && other_storage_ptr->GetIsAllocated()) {
- swap(data_.allocated, other_storage_ptr->data_.allocated);
- } else if (!GetIsAllocated() && !other_storage_ptr->GetIsAllocated()) {
- SwapInlinedElements(SwapPolicy{}, other_storage_ptr);
- } else {
- Storage* allocated_ptr = this;
- Storage* inlined_ptr = other_storage_ptr;
- if (!allocated_ptr->GetIsAllocated()) swap(allocated_ptr, inlined_ptr);
-
- StorageView<A> allocated_storage_view{
- allocated_ptr->GetAllocatedData(), allocated_ptr->GetSize(),
- allocated_ptr->GetAllocatedCapacity()};
-
- IteratorValueAdapter<A, MoveIterator<A>> move_values(
- MoveIterator<A>(inlined_ptr->GetInlinedData()));
-
- ABSL_INTERNAL_TRY {
- ConstructElements<A>(inlined_ptr->GetAllocator(),
- allocated_ptr->GetInlinedData(), move_values,
- inlined_ptr->GetSize());
- }
- ABSL_INTERNAL_CATCH_ANY {
- allocated_ptr->SetAllocation(Allocation<A>{
- allocated_storage_view.data, allocated_storage_view.capacity});
- ABSL_INTERNAL_RETHROW;
- }
-
- DestroyAdapter<A>::DestroyElements(inlined_ptr->GetAllocator(),
- inlined_ptr->GetInlinedData(),
- inlined_ptr->GetSize());
-
- inlined_ptr->SetAllocation(Allocation<A>{allocated_storage_view.data,
- allocated_storage_view.capacity});
- }
-
- swap(GetSizeAndIsAllocated(), other_storage_ptr->GetSizeAndIsAllocated());
- swap(GetAllocator(), other_storage_ptr->GetAllocator());
-}
-
-template <typename T, size_t N, typename A>
-void Storage<T, N, A>::SwapN(ElementwiseSwapPolicy, Storage* other,
- SizeType<A> n) {
- std::swap_ranges(GetInlinedData(), GetInlinedData() + n,
- other->GetInlinedData());
-}
-
-template <typename T, size_t N, typename A>
-void Storage<T, N, A>::SwapN(ElementwiseConstructPolicy, Storage* other,
- SizeType<A> n) {
- Pointer<A> a = GetInlinedData();
- Pointer<A> b = other->GetInlinedData();
- // see note on allocators in `SwapInlinedElements`.
- A& allocator_a = GetAllocator();
- A& allocator_b = other->GetAllocator();
- for (SizeType<A> i = 0; i < n; ++i, ++a, ++b) {
- ValueType<A> tmp(std::move(*a));
-
- AllocatorTraits<A>::destroy(allocator_a, a);
- AllocatorTraits<A>::construct(allocator_b, a, std::move(*b));
-
- AllocatorTraits<A>::destroy(allocator_b, b);
- AllocatorTraits<A>::construct(allocator_a, b, std::move(tmp));
- }
-}
-
-template <typename T, size_t N, typename A>
-void Storage<T, N, A>::SwapInlinedElements(MemcpyPolicy, Storage* other) {
- Data tmp = data_;
- data_ = other->data_;
- other->data_ = tmp;
-}
-
-template <typename T, size_t N, typename A>
-template <typename NotMemcpyPolicy>
-void Storage<T, N, A>::SwapInlinedElements(NotMemcpyPolicy policy,
- Storage* other) {
- // Note: `destroy` needs to use pre-swap allocator while `construct` -
- // post-swap allocator. Allocators will be swaped later on outside of
- // `SwapInlinedElements`.
- Storage* small_ptr = this;
- Storage* large_ptr = other;
- if (small_ptr->GetSize() > large_ptr->GetSize()) {
- std::swap(small_ptr, large_ptr);
- }
-
- auto small_size = small_ptr->GetSize();
- auto diff = large_ptr->GetSize() - small_size;
- SwapN(policy, other, small_size);
-
- IteratorValueAdapter<A, MoveIterator<A>> move_values(
- MoveIterator<A>(large_ptr->GetInlinedData() + small_size));
-
- ConstructElements<A>(large_ptr->GetAllocator(),
- small_ptr->GetInlinedData() + small_size, move_values,
- diff);
-
- DestroyAdapter<A>::DestroyElements(large_ptr->GetAllocator(),
- large_ptr->GetInlinedData() + small_size,
- diff);
-}
-
-// End ignore "array-bounds"
-#if !defined(__clang__) && defined(__GNUC__)
-#pragma GCC diagnostic pop
-#endif
-
-} // namespace inlined_vector_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_INTERNAL_INLINED_VECTOR_H_
diff --git a/third_party/abseil-cpp/absl/container/internal/layout.h b/third_party/abseil-cpp/absl/container/internal/layout.h
deleted file mode 100644
index a59a243..0000000
--- a/third_party/abseil-cpp/absl/container/internal/layout.h
+++ /dev/null
@@ -1,743 +0,0 @@
-// Copyright 2018 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.
-//
-// MOTIVATION AND TUTORIAL
-//
-// If you want to put in a single heap allocation N doubles followed by M ints,
-// it's easy if N and M are known at compile time.
-//
-// struct S {
-// double a[N];
-// int b[M];
-// };
-//
-// S* p = new S;
-//
-// But what if N and M are known only in run time? Class template Layout to the
-// rescue! It's a portable generalization of the technique known as struct hack.
-//
-// // This object will tell us everything we need to know about the memory
-// // layout of double[N] followed by int[M]. It's structurally identical to
-// // size_t[2] that stores N and M. It's very cheap to create.
-// const Layout<double, int> layout(N, M);
-//
-// // Allocate enough memory for both arrays. `AllocSize()` tells us how much
-// // memory is needed. We are free to use any allocation function we want as
-// // long as it returns aligned memory.
-// std::unique_ptr<unsigned char[]> p(new unsigned char[layout.AllocSize()]);
-//
-// // Obtain the pointer to the array of doubles.
-// // Equivalent to `reinterpret_cast<double*>(p.get())`.
-// //
-// // We could have written layout.Pointer<0>(p) instead. If all the types are
-// // unique you can use either form, but if some types are repeated you must
-// // use the index form.
-// double* a = layout.Pointer<double>(p.get());
-//
-// // Obtain the pointer to the array of ints.
-// // Equivalent to `reinterpret_cast<int*>(p.get() + N * 8)`.
-// int* b = layout.Pointer<int>(p);
-//
-// If we are unable to specify sizes of all fields, we can pass as many sizes as
-// we can to `Partial()`. In return, it'll allow us to access the fields whose
-// locations and sizes can be computed from the provided information.
-// `Partial()` comes in handy when the array sizes are embedded into the
-// allocation.
-//
-// // size_t[1] containing N, size_t[1] containing M, double[N], int[M].
-// using L = Layout<size_t, size_t, double, int>;
-//
-// unsigned char* Allocate(size_t n, size_t m) {
-// const L layout(1, 1, n, m);
-// unsigned char* p = new unsigned char[layout.AllocSize()];
-// *layout.Pointer<0>(p) = n;
-// *layout.Pointer<1>(p) = m;
-// return p;
-// }
-//
-// void Use(unsigned char* p) {
-// // First, extract N and M.
-// // Specify that the first array has only one element. Using `prefix` we
-// // can access the first two arrays but not more.
-// constexpr auto prefix = L::Partial(1);
-// size_t n = *prefix.Pointer<0>(p);
-// size_t m = *prefix.Pointer<1>(p);
-//
-// // Now we can get pointers to the payload.
-// const L layout(1, 1, n, m);
-// double* a = layout.Pointer<double>(p);
-// int* b = layout.Pointer<int>(p);
-// }
-//
-// The layout we used above combines fixed-size with dynamically-sized fields.
-// This is quite common. Layout is optimized for this use case and generates
-// optimal code. All computations that can be performed at compile time are
-// indeed performed at compile time.
-//
-// Efficiency tip: The order of fields matters. In `Layout<T1, ..., TN>` try to
-// ensure that `alignof(T1) >= ... >= alignof(TN)`. This way you'll have no
-// padding in between arrays.
-//
-// You can manually override the alignment of an array by wrapping the type in
-// `Aligned<T, N>`. `Layout<..., Aligned<T, N>, ...>` has exactly the same API
-// and behavior as `Layout<..., T, ...>` except that the first element of the
-// array of `T` is aligned to `N` (the rest of the elements follow without
-// padding). `N` cannot be less than `alignof(T)`.
-//
-// `AllocSize()` and `Pointer()` are the most basic methods for dealing with
-// memory layouts. Check out the reference or code below to discover more.
-//
-// EXAMPLE
-//
-// // Immutable move-only string with sizeof equal to sizeof(void*). The
-// // string size and the characters are kept in the same heap allocation.
-// class CompactString {
-// public:
-// CompactString(const char* s = "") {
-// const size_t size = strlen(s);
-// // size_t[1] followed by char[size + 1].
-// const L layout(1, size + 1);
-// p_.reset(new unsigned char[layout.AllocSize()]);
-// // If running under ASAN, mark the padding bytes, if any, to catch
-// // memory errors.
-// layout.PoisonPadding(p_.get());
-// // Store the size in the allocation.
-// *layout.Pointer<size_t>(p_.get()) = size;
-// // Store the characters in the allocation.
-// memcpy(layout.Pointer<char>(p_.get()), s, size + 1);
-// }
-//
-// size_t size() const {
-// // Equivalent to reinterpret_cast<size_t&>(*p).
-// return *L::Partial().Pointer<size_t>(p_.get());
-// }
-//
-// const char* c_str() const {
-// // Equivalent to reinterpret_cast<char*>(p.get() + sizeof(size_t)).
-// // The argument in Partial(1) specifies that we have size_t[1] in front
-// // of the characters.
-// return L::Partial(1).Pointer<char>(p_.get());
-// }
-//
-// private:
-// // Our heap allocation contains a size_t followed by an array of chars.
-// using L = Layout<size_t, char>;
-// std::unique_ptr<unsigned char[]> p_;
-// };
-//
-// int main() {
-// CompactString s = "hello";
-// assert(s.size() == 5);
-// assert(strcmp(s.c_str(), "hello") == 0);
-// }
-//
-// DOCUMENTATION
-//
-// The interface exported by this file consists of:
-// - class `Layout<>` and its public members.
-// - The public members of class `internal_layout::LayoutImpl<>`. That class
-// isn't intended to be used directly, and its name and template parameter
-// list are internal implementation details, but the class itself provides
-// most of the functionality in this file. See comments on its members for
-// detailed documentation.
-//
-// `Layout<T1,... Tn>::Partial(count1,..., countm)` (where `m` <= `n`) returns a
-// `LayoutImpl<>` object. `Layout<T1,..., Tn> layout(count1,..., countn)`
-// creates a `Layout` object, which exposes the same functionality by inheriting
-// from `LayoutImpl<>`.
-
-#ifndef ABSL_CONTAINER_INTERNAL_LAYOUT_H_
-#define ABSL_CONTAINER_INTERNAL_LAYOUT_H_
-
-#include <assert.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include <ostream>
-#include <string>
-#include <tuple>
-#include <type_traits>
-#include <typeinfo>
-#include <utility>
-
-#include "absl/base/config.h"
-#include "absl/meta/type_traits.h"
-#include "absl/strings/str_cat.h"
-#include "absl/types/span.h"
-#include "absl/utility/utility.h"
-
-#ifdef ABSL_HAVE_ADDRESS_SANITIZER
-#include <sanitizer/asan_interface.h>
-#endif
-
-#if defined(__GXX_RTTI)
-#define ABSL_INTERNAL_HAS_CXA_DEMANGLE
-#endif
-
-#ifdef ABSL_INTERNAL_HAS_CXA_DEMANGLE
-#include <cxxabi.h>
-#endif
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-
-// A type wrapper that instructs `Layout` to use the specific alignment for the
-// array. `Layout<..., Aligned<T, N>, ...>` has exactly the same API
-// and behavior as `Layout<..., T, ...>` except that the first element of the
-// array of `T` is aligned to `N` (the rest of the elements follow without
-// padding).
-//
-// Requires: `N >= alignof(T)` and `N` is a power of 2.
-template <class T, size_t N>
-struct Aligned;
-
-namespace internal_layout {
-
-template <class T>
-struct NotAligned {};
-
-template <class T, size_t N>
-struct NotAligned<const Aligned<T, N>> {
- static_assert(sizeof(T) == 0, "Aligned<T, N> cannot be const-qualified");
-};
-
-template <size_t>
-using IntToSize = size_t;
-
-template <class>
-using TypeToSize = size_t;
-
-template <class T>
-struct Type : NotAligned<T> {
- using type = T;
-};
-
-template <class T, size_t N>
-struct Type<Aligned<T, N>> {
- using type = T;
-};
-
-template <class T>
-struct SizeOf : NotAligned<T>, std::integral_constant<size_t, sizeof(T)> {};
-
-template <class T, size_t N>
-struct SizeOf<Aligned<T, N>> : std::integral_constant<size_t, sizeof(T)> {};
-
-// Note: workaround for https://gcc.gnu.org/PR88115
-template <class T>
-struct AlignOf : NotAligned<T> {
- static constexpr size_t value = alignof(T);
-};
-
-template <class T, size_t N>
-struct AlignOf<Aligned<T, N>> {
- static_assert(N % alignof(T) == 0,
- "Custom alignment can't be lower than the type's alignment");
- static constexpr size_t value = N;
-};
-
-// Does `Ts...` contain `T`?
-template <class T, class... Ts>
-using Contains = absl::disjunction<std::is_same<T, Ts>...>;
-
-template <class From, class To>
-using CopyConst =
- typename std::conditional<std::is_const<From>::value, const To, To>::type;
-
-// Note: We're not qualifying this with absl:: because it doesn't compile under
-// MSVC.
-template <class T>
-using SliceType = Span<T>;
-
-// This namespace contains no types. It prevents functions defined in it from
-// being found by ADL.
-namespace adl_barrier {
-
-template <class Needle, class... Ts>
-constexpr size_t Find(Needle, Needle, Ts...) {
- static_assert(!Contains<Needle, Ts...>(), "Duplicate element type");
- return 0;
-}
-
-template <class Needle, class T, class... Ts>
-constexpr size_t Find(Needle, T, Ts...) {
- return adl_barrier::Find(Needle(), Ts()...) + 1;
-}
-
-constexpr bool IsPow2(size_t n) { return !(n & (n - 1)); }
-
-// Returns `q * m` for the smallest `q` such that `q * m >= n`.
-// Requires: `m` is a power of two. It's enforced by IsLegalElementType below.
-constexpr size_t Align(size_t n, size_t m) { return (n + m - 1) & ~(m - 1); }
-
-constexpr size_t Min(size_t a, size_t b) { return b < a ? b : a; }
-
-constexpr size_t Max(size_t a) { return a; }
-
-template <class... Ts>
-constexpr size_t Max(size_t a, size_t b, Ts... rest) {
- return adl_barrier::Max(b < a ? a : b, rest...);
-}
-
-template <class T>
-std::string TypeName() {
- std::string out;
- int status = 0;
- char* demangled = nullptr;
-#ifdef ABSL_INTERNAL_HAS_CXA_DEMANGLE
- demangled = abi::__cxa_demangle(typeid(T).name(), nullptr, nullptr, &status);
-#endif
- if (status == 0 && demangled != nullptr) { // Demangling succeeded.
- absl::StrAppend(&out, "<", demangled, ">");
- free(demangled);
- } else {
-#if defined(__GXX_RTTI) || defined(_CPPRTTI)
- absl::StrAppend(&out, "<", typeid(T).name(), ">");
-#endif
- }
- return out;
-}
-
-} // namespace adl_barrier
-
-template <bool C>
-using EnableIf = typename std::enable_if<C, int>::type;
-
-// Can `T` be a template argument of `Layout`?
-template <class T>
-using IsLegalElementType = std::integral_constant<
- bool, !std::is_reference<T>::value && !std::is_volatile<T>::value &&
- !std::is_reference<typename Type<T>::type>::value &&
- !std::is_volatile<typename Type<T>::type>::value &&
- adl_barrier::IsPow2(AlignOf<T>::value)>;
-
-template <class Elements, class SizeSeq, class OffsetSeq>
-class LayoutImpl;
-
-// Public base class of `Layout` and the result type of `Layout::Partial()`.
-//
-// `Elements...` contains all template arguments of `Layout` that created this
-// instance.
-//
-// `SizeSeq...` is `[0, NumSizes)` where `NumSizes` is the number of arguments
-// passed to `Layout::Partial()` or `Layout::Layout()`.
-//
-// `OffsetSeq...` is `[0, NumOffsets)` where `NumOffsets` is
-// `Min(sizeof...(Elements), NumSizes + 1)` (the number of arrays for which we
-// can compute offsets).
-template <class... Elements, size_t... SizeSeq, size_t... OffsetSeq>
-class LayoutImpl<std::tuple<Elements...>, absl::index_sequence<SizeSeq...>,
- absl::index_sequence<OffsetSeq...>> {
- private:
- static_assert(sizeof...(Elements) > 0, "At least one field is required");
- static_assert(absl::conjunction<IsLegalElementType<Elements>...>::value,
- "Invalid element type (see IsLegalElementType)");
-
- enum {
- NumTypes = sizeof...(Elements),
- NumSizes = sizeof...(SizeSeq),
- NumOffsets = sizeof...(OffsetSeq),
- };
-
- // These are guaranteed by `Layout`.
- static_assert(NumOffsets == adl_barrier::Min(NumTypes, NumSizes + 1),
- "Internal error");
- static_assert(NumTypes > 0, "Internal error");
-
- // Returns the index of `T` in `Elements...`. Results in a compilation error
- // if `Elements...` doesn't contain exactly one instance of `T`.
- template <class T>
- static constexpr size_t ElementIndex() {
- static_assert(Contains<Type<T>, Type<typename Type<Elements>::type>...>(),
- "Type not found");
- return adl_barrier::Find(Type<T>(),
- Type<typename Type<Elements>::type>()...);
- }
-
- template <size_t N>
- using ElementAlignment =
- AlignOf<typename std::tuple_element<N, std::tuple<Elements...>>::type>;
-
- public:
- // Element types of all arrays packed in a tuple.
- using ElementTypes = std::tuple<typename Type<Elements>::type...>;
-
- // Element type of the Nth array.
- template <size_t N>
- using ElementType = typename std::tuple_element<N, ElementTypes>::type;
-
- constexpr explicit LayoutImpl(IntToSize<SizeSeq>... sizes)
- : size_{sizes...} {}
-
- // Alignment of the layout, equal to the strictest alignment of all elements.
- // All pointers passed to the methods of layout must be aligned to this value.
- static constexpr size_t Alignment() {
- return adl_barrier::Max(AlignOf<Elements>::value...);
- }
-
- // Offset in bytes of the Nth array.
- //
- // // int[3], 4 bytes of padding, double[4].
- // Layout<int, double> x(3, 4);
- // assert(x.Offset<0>() == 0); // The ints starts from 0.
- // assert(x.Offset<1>() == 16); // The doubles starts from 16.
- //
- // Requires: `N <= NumSizes && N < sizeof...(Ts)`.
- template <size_t N, EnableIf<N == 0> = 0>
- constexpr size_t Offset() const {
- return 0;
- }
-
- template <size_t N, EnableIf<N != 0> = 0>
- constexpr size_t Offset() const {
- static_assert(N < NumOffsets, "Index out of bounds");
- return adl_barrier::Align(
- Offset<N - 1>() + SizeOf<ElementType<N - 1>>::value * size_[N - 1],
- ElementAlignment<N>::value);
- }
-
- // Offset in bytes of the array with the specified element type. There must
- // be exactly one such array and its zero-based index must be at most
- // `NumSizes`.
- //
- // // int[3], 4 bytes of padding, double[4].
- // Layout<int, double> x(3, 4);
- // assert(x.Offset<int>() == 0); // The ints starts from 0.
- // assert(x.Offset<double>() == 16); // The doubles starts from 16.
- template <class T>
- constexpr size_t Offset() const {
- return Offset<ElementIndex<T>()>();
- }
-
- // Offsets in bytes of all arrays for which the offsets are known.
- constexpr std::array<size_t, NumOffsets> Offsets() const {
- return {{Offset<OffsetSeq>()...}};
- }
-
- // The number of elements in the Nth array. This is the Nth argument of
- // `Layout::Partial()` or `Layout::Layout()` (zero-based).
- //
- // // int[3], 4 bytes of padding, double[4].
- // Layout<int, double> x(3, 4);
- // assert(x.Size<0>() == 3);
- // assert(x.Size<1>() == 4);
- //
- // Requires: `N < NumSizes`.
- template <size_t N>
- constexpr size_t Size() const {
- static_assert(N < NumSizes, "Index out of bounds");
- return size_[N];
- }
-
- // The number of elements in the array with the specified element type.
- // There must be exactly one such array and its zero-based index must be
- // at most `NumSizes`.
- //
- // // int[3], 4 bytes of padding, double[4].
- // Layout<int, double> x(3, 4);
- // assert(x.Size<int>() == 3);
- // assert(x.Size<double>() == 4);
- template <class T>
- constexpr size_t Size() const {
- return Size<ElementIndex<T>()>();
- }
-
- // The number of elements of all arrays for which they are known.
- constexpr std::array<size_t, NumSizes> Sizes() const {
- return {{Size<SizeSeq>()...}};
- }
-
- // Pointer to the beginning of the Nth array.
- //
- // `Char` must be `[const] [signed|unsigned] char`.
- //
- // // int[3], 4 bytes of padding, double[4].
- // Layout<int, double> x(3, 4);
- // unsigned char* p = new unsigned char[x.AllocSize()];
- // int* ints = x.Pointer<0>(p);
- // double* doubles = x.Pointer<1>(p);
- //
- // Requires: `N <= NumSizes && N < sizeof...(Ts)`.
- // Requires: `p` is aligned to `Alignment()`.
- template <size_t N, class Char>
- CopyConst<Char, ElementType<N>>* Pointer(Char* p) const {
- using C = typename std::remove_const<Char>::type;
- static_assert(
- std::is_same<C, char>() || std::is_same<C, unsigned char>() ||
- std::is_same<C, signed char>(),
- "The argument must be a pointer to [const] [signed|unsigned] char");
- constexpr size_t alignment = Alignment();
- (void)alignment;
- assert(reinterpret_cast<uintptr_t>(p) % alignment == 0);
- return reinterpret_cast<CopyConst<Char, ElementType<N>>*>(p + Offset<N>());
- }
-
- // Pointer to the beginning of the array with the specified element type.
- // There must be exactly one such array and its zero-based index must be at
- // most `NumSizes`.
- //
- // `Char` must be `[const] [signed|unsigned] char`.
- //
- // // int[3], 4 bytes of padding, double[4].
- // Layout<int, double> x(3, 4);
- // unsigned char* p = new unsigned char[x.AllocSize()];
- // int* ints = x.Pointer<int>(p);
- // double* doubles = x.Pointer<double>(p);
- //
- // Requires: `p` is aligned to `Alignment()`.
- template <class T, class Char>
- CopyConst<Char, T>* Pointer(Char* p) const {
- return Pointer<ElementIndex<T>()>(p);
- }
-
- // Pointers to all arrays for which pointers are known.
- //
- // `Char` must be `[const] [signed|unsigned] char`.
- //
- // // int[3], 4 bytes of padding, double[4].
- // Layout<int, double> x(3, 4);
- // unsigned char* p = new unsigned char[x.AllocSize()];
- //
- // int* ints;
- // double* doubles;
- // std::tie(ints, doubles) = x.Pointers(p);
- //
- // Requires: `p` is aligned to `Alignment()`.
- //
- // Note: We're not using ElementType alias here because it does not compile
- // under MSVC.
- template <class Char>
- std::tuple<CopyConst<
- Char, typename std::tuple_element<OffsetSeq, ElementTypes>::type>*...>
- Pointers(Char* p) const {
- return std::tuple<CopyConst<Char, ElementType<OffsetSeq>>*...>(
- Pointer<OffsetSeq>(p)...);
- }
-
- // The Nth array.
- //
- // `Char` must be `[const] [signed|unsigned] char`.
- //
- // // int[3], 4 bytes of padding, double[4].
- // Layout<int, double> x(3, 4);
- // unsigned char* p = new unsigned char[x.AllocSize()];
- // Span<int> ints = x.Slice<0>(p);
- // Span<double> doubles = x.Slice<1>(p);
- //
- // Requires: `N < NumSizes`.
- // Requires: `p` is aligned to `Alignment()`.
- template <size_t N, class Char>
- SliceType<CopyConst<Char, ElementType<N>>> Slice(Char* p) const {
- return SliceType<CopyConst<Char, ElementType<N>>>(Pointer<N>(p), Size<N>());
- }
-
- // The array with the specified element type. There must be exactly one
- // such array and its zero-based index must be less than `NumSizes`.
- //
- // `Char` must be `[const] [signed|unsigned] char`.
- //
- // // int[3], 4 bytes of padding, double[4].
- // Layout<int, double> x(3, 4);
- // unsigned char* p = new unsigned char[x.AllocSize()];
- // Span<int> ints = x.Slice<int>(p);
- // Span<double> doubles = x.Slice<double>(p);
- //
- // Requires: `p` is aligned to `Alignment()`.
- template <class T, class Char>
- SliceType<CopyConst<Char, T>> Slice(Char* p) const {
- return Slice<ElementIndex<T>()>(p);
- }
-
- // All arrays with known sizes.
- //
- // `Char` must be `[const] [signed|unsigned] char`.
- //
- // // int[3], 4 bytes of padding, double[4].
- // Layout<int, double> x(3, 4);
- // unsigned char* p = new unsigned char[x.AllocSize()];
- //
- // Span<int> ints;
- // Span<double> doubles;
- // std::tie(ints, doubles) = x.Slices(p);
- //
- // Requires: `p` is aligned to `Alignment()`.
- //
- // Note: We're not using ElementType alias here because it does not compile
- // under MSVC.
- template <class Char>
- std::tuple<SliceType<CopyConst<
- Char, typename std::tuple_element<SizeSeq, ElementTypes>::type>>...>
- Slices(Char* p) const {
- // Workaround for https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63875 (fixed
- // in 6.1).
- (void)p;
- return std::tuple<SliceType<CopyConst<Char, ElementType<SizeSeq>>>...>(
- Slice<SizeSeq>(p)...);
- }
-
- // The size of the allocation that fits all arrays.
- //
- // // int[3], 4 bytes of padding, double[4].
- // Layout<int, double> x(3, 4);
- // unsigned char* p = new unsigned char[x.AllocSize()]; // 48 bytes
- //
- // Requires: `NumSizes == sizeof...(Ts)`.
- constexpr size_t AllocSize() const {
- static_assert(NumTypes == NumSizes, "You must specify sizes of all fields");
- return Offset<NumTypes - 1>() +
- SizeOf<ElementType<NumTypes - 1>>::value * size_[NumTypes - 1];
- }
-
- // If built with --config=asan, poisons padding bytes (if any) in the
- // allocation. The pointer must point to a memory block at least
- // `AllocSize()` bytes in length.
- //
- // `Char` must be `[const] [signed|unsigned] char`.
- //
- // Requires: `p` is aligned to `Alignment()`.
- template <class Char, size_t N = NumOffsets - 1, EnableIf<N == 0> = 0>
- void PoisonPadding(const Char* p) const {
- Pointer<0>(p); // verify the requirements on `Char` and `p`
- }
-
- template <class Char, size_t N = NumOffsets - 1, EnableIf<N != 0> = 0>
- void PoisonPadding(const Char* p) const {
- static_assert(N < NumOffsets, "Index out of bounds");
- (void)p;
-#ifdef ABSL_HAVE_ADDRESS_SANITIZER
- PoisonPadding<Char, N - 1>(p);
- // The `if` is an optimization. It doesn't affect the observable behaviour.
- if (ElementAlignment<N - 1>::value % ElementAlignment<N>::value) {
- size_t start =
- Offset<N - 1>() + SizeOf<ElementType<N - 1>>::value * size_[N - 1];
- ASAN_POISON_MEMORY_REGION(p + start, Offset<N>() - start);
- }
-#endif
- }
-
- // Human-readable description of the memory layout. Useful for debugging.
- // Slow.
- //
- // // char[5], 3 bytes of padding, int[3], 4 bytes of padding, followed
- // // by an unknown number of doubles.
- // auto x = Layout<char, int, double>::Partial(5, 3);
- // assert(x.DebugString() ==
- // "@0<char>(1)[5]; @8<int>(4)[3]; @24<double>(8)");
- //
- // Each field is in the following format: @offset<type>(sizeof)[size] (<type>
- // may be missing depending on the target platform). For example,
- // @8<int>(4)[3] means that at offset 8 we have an array of ints, where each
- // int is 4 bytes, and we have 3 of those ints. The size of the last field may
- // be missing (as in the example above). Only fields with known offsets are
- // described. Type names may differ across platforms: one compiler might
- // produce "unsigned*" where another produces "unsigned int *".
- std::string DebugString() const {
- const auto offsets = Offsets();
- const size_t sizes[] = {SizeOf<ElementType<OffsetSeq>>::value...};
- const std::string types[] = {
- adl_barrier::TypeName<ElementType<OffsetSeq>>()...};
- std::string res = absl::StrCat("@0", types[0], "(", sizes[0], ")");
- for (size_t i = 0; i != NumOffsets - 1; ++i) {
- absl::StrAppend(&res, "[", size_[i], "]; @", offsets[i + 1], types[i + 1],
- "(", sizes[i + 1], ")");
- }
- // NumSizes is a constant that may be zero. Some compilers cannot see that
- // inside the if statement "size_[NumSizes - 1]" must be valid.
- int last = static_cast<int>(NumSizes) - 1;
- if (NumTypes == NumSizes && last >= 0) {
- absl::StrAppend(&res, "[", size_[last], "]");
- }
- return res;
- }
-
- private:
- // Arguments of `Layout::Partial()` or `Layout::Layout()`.
- size_t size_[NumSizes > 0 ? NumSizes : 1];
-};
-
-template <size_t NumSizes, class... Ts>
-using LayoutType = LayoutImpl<
- std::tuple<Ts...>, absl::make_index_sequence<NumSizes>,
- absl::make_index_sequence<adl_barrier::Min(sizeof...(Ts), NumSizes + 1)>>;
-
-} // namespace internal_layout
-
-// Descriptor of arrays of various types and sizes laid out in memory one after
-// another. See the top of the file for documentation.
-//
-// Check out the public API of internal_layout::LayoutImpl above. The type is
-// internal to the library but its methods are public, and they are inherited
-// by `Layout`.
-template <class... Ts>
-class Layout : public internal_layout::LayoutType<sizeof...(Ts), Ts...> {
- public:
- static_assert(sizeof...(Ts) > 0, "At least one field is required");
- static_assert(
- absl::conjunction<internal_layout::IsLegalElementType<Ts>...>::value,
- "Invalid element type (see IsLegalElementType)");
-
- // The result type of `Partial()` with `NumSizes` arguments.
- template <size_t NumSizes>
- using PartialType = internal_layout::LayoutType<NumSizes, Ts...>;
-
- // `Layout` knows the element types of the arrays we want to lay out in
- // memory but not the number of elements in each array.
- // `Partial(size1, ..., sizeN)` allows us to specify the latter. The
- // resulting immutable object can be used to obtain pointers to the
- // individual arrays.
- //
- // It's allowed to pass fewer array sizes than the number of arrays. E.g.,
- // if all you need is to the offset of the second array, you only need to
- // pass one argument -- the number of elements in the first array.
- //
- // // int[3] followed by 4 bytes of padding and an unknown number of
- // // doubles.
- // auto x = Layout<int, double>::Partial(3);
- // // doubles start at byte 16.
- // assert(x.Offset<1>() == 16);
- //
- // If you know the number of elements in all arrays, you can still call
- // `Partial()` but it's more convenient to use the constructor of `Layout`.
- //
- // Layout<int, double> x(3, 5);
- //
- // Note: The sizes of the arrays must be specified in number of elements,
- // not in bytes.
- //
- // Requires: `sizeof...(Sizes) <= sizeof...(Ts)`.
- // Requires: all arguments are convertible to `size_t`.
- template <class... Sizes>
- static constexpr PartialType<sizeof...(Sizes)> Partial(Sizes&&... sizes) {
- static_assert(sizeof...(Sizes) <= sizeof...(Ts), "");
- return PartialType<sizeof...(Sizes)>(absl::forward<Sizes>(sizes)...);
- }
-
- // Creates a layout with the sizes of all arrays specified. If you know
- // only the sizes of the first N arrays (where N can be zero), you can use
- // `Partial()` defined above. The constructor is essentially equivalent to
- // calling `Partial()` and passing in all array sizes; the constructor is
- // provided as a convenient abbreviation.
- //
- // Note: The sizes of the arrays must be specified in number of elements,
- // not in bytes.
- constexpr explicit Layout(internal_layout::TypeToSize<Ts>... sizes)
- : internal_layout::LayoutType<sizeof...(Ts), Ts...>(sizes...) {}
-};
-
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_INTERNAL_LAYOUT_H_
diff --git a/third_party/abseil-cpp/absl/container/internal/layout_benchmark.cc b/third_party/abseil-cpp/absl/container/internal/layout_benchmark.cc
deleted file mode 100644
index d8636e8..0000000
--- a/third_party/abseil-cpp/absl/container/internal/layout_benchmark.cc
+++ /dev/null
@@ -1,122 +0,0 @@
-// Copyright 2018 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.
-//
-// Every benchmark should have the same performance as the corresponding
-// headroom benchmark.
-
-#include "absl/base/internal/raw_logging.h"
-#include "absl/container/internal/layout.h"
-#include "benchmark/benchmark.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-namespace {
-
-using ::benchmark::DoNotOptimize;
-
-using Int128 = int64_t[2];
-
-// This benchmark provides the upper bound on performance for BM_OffsetConstant.
-template <size_t Offset, class... Ts>
-void BM_OffsetConstantHeadroom(benchmark::State& state) {
- for (auto _ : state) {
- DoNotOptimize(Offset);
- }
-}
-
-template <size_t Offset, class... Ts>
-void BM_OffsetConstant(benchmark::State& state) {
- using L = Layout<Ts...>;
- ABSL_RAW_CHECK(L::Partial(3, 5, 7).template Offset<3>() == Offset,
- "Invalid offset");
- for (auto _ : state) {
- DoNotOptimize(L::Partial(3, 5, 7).template Offset<3>());
- }
-}
-
-template <class... Ts>
-size_t VariableOffset(size_t n, size_t m, size_t k);
-
-template <>
-size_t VariableOffset<int8_t, int16_t, int32_t, Int128>(size_t n, size_t m,
- size_t k) {
- auto Align = [](size_t n, size_t m) { return (n + m - 1) & ~(m - 1); };
- return Align(Align(Align(n * 1, 2) + m * 2, 4) + k * 4, 8);
-}
-
-template <>
-size_t VariableOffset<Int128, int32_t, int16_t, int8_t>(size_t n, size_t m,
- size_t k) {
- // No alignment is necessary.
- return n * 16 + m * 4 + k * 2;
-}
-
-// This benchmark provides the upper bound on performance for BM_OffsetVariable.
-template <size_t Offset, class... Ts>
-void BM_OffsetVariableHeadroom(benchmark::State& state) {
- size_t n = 3;
- size_t m = 5;
- size_t k = 7;
- ABSL_RAW_CHECK(VariableOffset<Ts...>(n, m, k) == Offset, "Invalid offset");
- for (auto _ : state) {
- DoNotOptimize(n);
- DoNotOptimize(m);
- DoNotOptimize(k);
- DoNotOptimize(VariableOffset<Ts...>(n, m, k));
- }
-}
-
-template <size_t Offset, class... Ts>
-void BM_OffsetVariable(benchmark::State& state) {
- using L = Layout<Ts...>;
- size_t n = 3;
- size_t m = 5;
- size_t k = 7;
- ABSL_RAW_CHECK(L::Partial(n, m, k).template Offset<3>() == Offset,
- "Inavlid offset");
- for (auto _ : state) {
- DoNotOptimize(n);
- DoNotOptimize(m);
- DoNotOptimize(k);
- DoNotOptimize(L::Partial(n, m, k).template Offset<3>());
- }
-}
-
-// Run all benchmarks in two modes:
-//
-// Layout with padding: int8_t[3], int16_t[5], int32_t[7], Int128[?].
-// Layout without padding: Int128[3], int32_t[5], int16_t[7], int8_t[?].
-
-#define OFFSET_BENCHMARK(NAME, OFFSET, T1, T2, T3, T4) \
- auto& NAME##_##OFFSET##_##T1##_##T2##_##T3##_##T4 = \
- NAME<OFFSET, T1, T2, T3, T4>; \
- BENCHMARK(NAME##_##OFFSET##_##T1##_##T2##_##T3##_##T4)
-
-OFFSET_BENCHMARK(BM_OffsetConstantHeadroom, 48, int8_t, int16_t, int32_t,
- Int128);
-OFFSET_BENCHMARK(BM_OffsetConstant, 48, int8_t, int16_t, int32_t, Int128);
-OFFSET_BENCHMARK(BM_OffsetConstantHeadroom, 82, Int128, int32_t, int16_t,
- int8_t);
-OFFSET_BENCHMARK(BM_OffsetConstant, 82, Int128, int32_t, int16_t, int8_t);
-OFFSET_BENCHMARK(BM_OffsetVariableHeadroom, 48, int8_t, int16_t, int32_t,
- Int128);
-OFFSET_BENCHMARK(BM_OffsetVariable, 48, int8_t, int16_t, int32_t, Int128);
-OFFSET_BENCHMARK(BM_OffsetVariableHeadroom, 82, Int128, int32_t, int16_t,
- int8_t);
-OFFSET_BENCHMARK(BM_OffsetVariable, 82, Int128, int32_t, int16_t, int8_t);
-} // namespace
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/container/internal/layout_test.cc b/third_party/abseil-cpp/absl/container/internal/layout_test.cc
deleted file mode 100644
index 54e5d5b..0000000
--- a/third_party/abseil-cpp/absl/container/internal/layout_test.cc
+++ /dev/null
@@ -1,1641 +0,0 @@
-// Copyright 2018 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/container/internal/layout.h"
-
-// We need ::max_align_t because some libstdc++ versions don't provide
-// std::max_align_t
-#include <stddef.h>
-
-#include <cstdint>
-#include <memory>
-#include <sstream>
-#include <type_traits>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/base/config.h"
-#include "absl/base/internal/raw_logging.h"
-#include "absl/types/span.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-namespace {
-
-using ::absl::Span;
-using ::testing::ElementsAre;
-
-size_t Distance(const void* from, const void* to) {
- ABSL_RAW_CHECK(from <= to, "Distance must be non-negative");
- return static_cast<const char*>(to) - static_cast<const char*>(from);
-}
-
-template <class Expected, class Actual>
-Expected Type(Actual val) {
- static_assert(std::is_same<Expected, Actual>(), "");
- return val;
-}
-
-// Helper classes to test different size and alignments.
-struct alignas(8) Int128 {
- uint64_t a, b;
- friend bool operator==(Int128 lhs, Int128 rhs) {
- return std::tie(lhs.a, lhs.b) == std::tie(rhs.a, rhs.b);
- }
-
- static std::string Name() {
- return internal_layout::adl_barrier::TypeName<Int128>();
- }
-};
-
-// int64_t is *not* 8-byte aligned on all platforms!
-struct alignas(8) Int64 {
- int64_t a;
- friend bool operator==(Int64 lhs, Int64 rhs) {
- return lhs.a == rhs.a;
- }
-};
-
-// Properties of types that this test relies on.
-static_assert(sizeof(int8_t) == 1, "");
-static_assert(alignof(int8_t) == 1, "");
-static_assert(sizeof(int16_t) == 2, "");
-static_assert(alignof(int16_t) == 2, "");
-static_assert(sizeof(int32_t) == 4, "");
-static_assert(alignof(int32_t) == 4, "");
-static_assert(sizeof(Int64) == 8, "");
-static_assert(alignof(Int64) == 8, "");
-static_assert(sizeof(Int128) == 16, "");
-static_assert(alignof(Int128) == 8, "");
-
-template <class Expected, class Actual>
-void SameType() {
- static_assert(std::is_same<Expected, Actual>(), "");
-}
-
-TEST(Layout, ElementType) {
- {
- using L = Layout<int32_t>;
- SameType<int32_t, L::ElementType<0>>();
- SameType<int32_t, decltype(L::Partial())::ElementType<0>>();
- SameType<int32_t, decltype(L::Partial(0))::ElementType<0>>();
- }
- {
- using L = Layout<int32_t, int32_t>;
- SameType<int32_t, L::ElementType<0>>();
- SameType<int32_t, L::ElementType<1>>();
- SameType<int32_t, decltype(L::Partial())::ElementType<0>>();
- SameType<int32_t, decltype(L::Partial())::ElementType<1>>();
- SameType<int32_t, decltype(L::Partial(0))::ElementType<0>>();
- SameType<int32_t, decltype(L::Partial(0))::ElementType<1>>();
- }
- {
- using L = Layout<int8_t, int32_t, Int128>;
- SameType<int8_t, L::ElementType<0>>();
- SameType<int32_t, L::ElementType<1>>();
- SameType<Int128, L::ElementType<2>>();
- SameType<int8_t, decltype(L::Partial())::ElementType<0>>();
- SameType<int8_t, decltype(L::Partial(0))::ElementType<0>>();
- SameType<int32_t, decltype(L::Partial(0))::ElementType<1>>();
- SameType<int8_t, decltype(L::Partial(0, 0))::ElementType<0>>();
- SameType<int32_t, decltype(L::Partial(0, 0))::ElementType<1>>();
- SameType<Int128, decltype(L::Partial(0, 0))::ElementType<2>>();
- SameType<int8_t, decltype(L::Partial(0, 0, 0))::ElementType<0>>();
- SameType<int32_t, decltype(L::Partial(0, 0, 0))::ElementType<1>>();
- SameType<Int128, decltype(L::Partial(0, 0, 0))::ElementType<2>>();
- }
-}
-
-TEST(Layout, ElementTypes) {
- {
- using L = Layout<int32_t>;
- SameType<std::tuple<int32_t>, L::ElementTypes>();
- SameType<std::tuple<int32_t>, decltype(L::Partial())::ElementTypes>();
- SameType<std::tuple<int32_t>, decltype(L::Partial(0))::ElementTypes>();
- }
- {
- using L = Layout<int32_t, int32_t>;
- SameType<std::tuple<int32_t, int32_t>, L::ElementTypes>();
- SameType<std::tuple<int32_t, int32_t>,
- decltype(L::Partial())::ElementTypes>();
- SameType<std::tuple<int32_t, int32_t>,
- decltype(L::Partial(0))::ElementTypes>();
- }
- {
- using L = Layout<int8_t, int32_t, Int128>;
- SameType<std::tuple<int8_t, int32_t, Int128>, L::ElementTypes>();
- SameType<std::tuple<int8_t, int32_t, Int128>,
- decltype(L::Partial())::ElementTypes>();
- SameType<std::tuple<int8_t, int32_t, Int128>,
- decltype(L::Partial(0))::ElementTypes>();
- SameType<std::tuple<int8_t, int32_t, Int128>,
- decltype(L::Partial(0, 0))::ElementTypes>();
- SameType<std::tuple<int8_t, int32_t, Int128>,
- decltype(L::Partial(0, 0, 0))::ElementTypes>();
- }
-}
-
-TEST(Layout, OffsetByIndex) {
- {
- using L = Layout<int32_t>;
- EXPECT_EQ(0, L::Partial().Offset<0>());
- EXPECT_EQ(0, L::Partial(3).Offset<0>());
- EXPECT_EQ(0, L(3).Offset<0>());
- }
- {
- using L = Layout<int32_t, int32_t>;
- EXPECT_EQ(0, L::Partial().Offset<0>());
- EXPECT_EQ(0, L::Partial(3).Offset<0>());
- EXPECT_EQ(12, L::Partial(3).Offset<1>());
- EXPECT_EQ(0, L::Partial(3, 5).Offset<0>());
- EXPECT_EQ(12, L::Partial(3, 5).Offset<1>());
- EXPECT_EQ(0, L(3, 5).Offset<0>());
- EXPECT_EQ(12, L(3, 5).Offset<1>());
- }
- {
- using L = Layout<int8_t, int32_t, Int128>;
- EXPECT_EQ(0, L::Partial().Offset<0>());
- EXPECT_EQ(0, L::Partial(0).Offset<0>());
- EXPECT_EQ(0, L::Partial(0).Offset<1>());
- EXPECT_EQ(0, L::Partial(1).Offset<0>());
- EXPECT_EQ(4, L::Partial(1).Offset<1>());
- EXPECT_EQ(0, L::Partial(5).Offset<0>());
- EXPECT_EQ(8, L::Partial(5).Offset<1>());
- EXPECT_EQ(0, L::Partial(0, 0).Offset<0>());
- EXPECT_EQ(0, L::Partial(0, 0).Offset<1>());
- EXPECT_EQ(0, L::Partial(0, 0).Offset<2>());
- EXPECT_EQ(0, L::Partial(1, 0).Offset<0>());
- EXPECT_EQ(4, L::Partial(1, 0).Offset<1>());
- EXPECT_EQ(8, L::Partial(1, 0).Offset<2>());
- EXPECT_EQ(0, L::Partial(5, 3).Offset<0>());
- EXPECT_EQ(8, L::Partial(5, 3).Offset<1>());
- EXPECT_EQ(24, L::Partial(5, 3).Offset<2>());
- EXPECT_EQ(0, L::Partial(0, 0, 0).Offset<0>());
- EXPECT_EQ(0, L::Partial(0, 0, 0).Offset<1>());
- EXPECT_EQ(0, L::Partial(0, 0, 0).Offset<2>());
- EXPECT_EQ(0, L::Partial(1, 0, 0).Offset<0>());
- EXPECT_EQ(4, L::Partial(1, 0, 0).Offset<1>());
- EXPECT_EQ(8, L::Partial(1, 0, 0).Offset<2>());
- EXPECT_EQ(0, L::Partial(5, 3, 1).Offset<0>());
- EXPECT_EQ(24, L::Partial(5, 3, 1).Offset<2>());
- EXPECT_EQ(8, L::Partial(5, 3, 1).Offset<1>());
- EXPECT_EQ(0, L(5, 3, 1).Offset<0>());
- EXPECT_EQ(24, L(5, 3, 1).Offset<2>());
- EXPECT_EQ(8, L(5, 3, 1).Offset<1>());
- }
-}
-
-TEST(Layout, OffsetByType) {
- {
- using L = Layout<int32_t>;
- EXPECT_EQ(0, L::Partial().Offset<int32_t>());
- EXPECT_EQ(0, L::Partial(3).Offset<int32_t>());
- EXPECT_EQ(0, L(3).Offset<int32_t>());
- }
- {
- using L = Layout<int8_t, int32_t, Int128>;
- EXPECT_EQ(0, L::Partial().Offset<int8_t>());
- EXPECT_EQ(0, L::Partial(0).Offset<int8_t>());
- EXPECT_EQ(0, L::Partial(0).Offset<int32_t>());
- EXPECT_EQ(0, L::Partial(1).Offset<int8_t>());
- EXPECT_EQ(4, L::Partial(1).Offset<int32_t>());
- EXPECT_EQ(0, L::Partial(5).Offset<int8_t>());
- EXPECT_EQ(8, L::Partial(5).Offset<int32_t>());
- EXPECT_EQ(0, L::Partial(0, 0).Offset<int8_t>());
- EXPECT_EQ(0, L::Partial(0, 0).Offset<int32_t>());
- EXPECT_EQ(0, L::Partial(0, 0).Offset<Int128>());
- EXPECT_EQ(0, L::Partial(1, 0).Offset<int8_t>());
- EXPECT_EQ(4, L::Partial(1, 0).Offset<int32_t>());
- EXPECT_EQ(8, L::Partial(1, 0).Offset<Int128>());
- EXPECT_EQ(0, L::Partial(5, 3).Offset<int8_t>());
- EXPECT_EQ(8, L::Partial(5, 3).Offset<int32_t>());
- EXPECT_EQ(24, L::Partial(5, 3).Offset<Int128>());
- EXPECT_EQ(0, L::Partial(0, 0, 0).Offset<int8_t>());
- EXPECT_EQ(0, L::Partial(0, 0, 0).Offset<int32_t>());
- EXPECT_EQ(0, L::Partial(0, 0, 0).Offset<Int128>());
- EXPECT_EQ(0, L::Partial(1, 0, 0).Offset<int8_t>());
- EXPECT_EQ(4, L::Partial(1, 0, 0).Offset<int32_t>());
- EXPECT_EQ(8, L::Partial(1, 0, 0).Offset<Int128>());
- EXPECT_EQ(0, L::Partial(5, 3, 1).Offset<int8_t>());
- EXPECT_EQ(24, L::Partial(5, 3, 1).Offset<Int128>());
- EXPECT_EQ(8, L::Partial(5, 3, 1).Offset<int32_t>());
- EXPECT_EQ(0, L(5, 3, 1).Offset<int8_t>());
- EXPECT_EQ(24, L(5, 3, 1).Offset<Int128>());
- EXPECT_EQ(8, L(5, 3, 1).Offset<int32_t>());
- }
-}
-
-TEST(Layout, Offsets) {
- {
- using L = Layout<int32_t>;
- EXPECT_THAT(L::Partial().Offsets(), ElementsAre(0));
- EXPECT_THAT(L::Partial(3).Offsets(), ElementsAre(0));
- EXPECT_THAT(L(3).Offsets(), ElementsAre(0));
- }
- {
- using L = Layout<int32_t, int32_t>;
- EXPECT_THAT(L::Partial().Offsets(), ElementsAre(0));
- EXPECT_THAT(L::Partial(3).Offsets(), ElementsAre(0, 12));
- EXPECT_THAT(L::Partial(3, 5).Offsets(), ElementsAre(0, 12));
- EXPECT_THAT(L(3, 5).Offsets(), ElementsAre(0, 12));
- }
- {
- using L = Layout<int8_t, int32_t, Int128>;
- EXPECT_THAT(L::Partial().Offsets(), ElementsAre(0));
- EXPECT_THAT(L::Partial(1).Offsets(), ElementsAre(0, 4));
- EXPECT_THAT(L::Partial(5).Offsets(), ElementsAre(0, 8));
- EXPECT_THAT(L::Partial(0, 0).Offsets(), ElementsAre(0, 0, 0));
- EXPECT_THAT(L::Partial(1, 0).Offsets(), ElementsAre(0, 4, 8));
- EXPECT_THAT(L::Partial(5, 3).Offsets(), ElementsAre(0, 8, 24));
- EXPECT_THAT(L::Partial(0, 0, 0).Offsets(), ElementsAre(0, 0, 0));
- EXPECT_THAT(L::Partial(1, 0, 0).Offsets(), ElementsAre(0, 4, 8));
- EXPECT_THAT(L::Partial(5, 3, 1).Offsets(), ElementsAre(0, 8, 24));
- EXPECT_THAT(L(5, 3, 1).Offsets(), ElementsAre(0, 8, 24));
- }
-}
-
-TEST(Layout, AllocSize) {
- {
- using L = Layout<int32_t>;
- EXPECT_EQ(0, L::Partial(0).AllocSize());
- EXPECT_EQ(12, L::Partial(3).AllocSize());
- EXPECT_EQ(12, L(3).AllocSize());
- }
- {
- using L = Layout<int32_t, int32_t>;
- EXPECT_EQ(32, L::Partial(3, 5).AllocSize());
- EXPECT_EQ(32, L(3, 5).AllocSize());
- }
- {
- using L = Layout<int8_t, int32_t, Int128>;
- EXPECT_EQ(0, L::Partial(0, 0, 0).AllocSize());
- EXPECT_EQ(8, L::Partial(1, 0, 0).AllocSize());
- EXPECT_EQ(8, L::Partial(0, 1, 0).AllocSize());
- EXPECT_EQ(16, L::Partial(0, 0, 1).AllocSize());
- EXPECT_EQ(24, L::Partial(1, 1, 1).AllocSize());
- EXPECT_EQ(136, L::Partial(3, 5, 7).AllocSize());
- EXPECT_EQ(136, L(3, 5, 7).AllocSize());
- }
-}
-
-TEST(Layout, SizeByIndex) {
- {
- using L = Layout<int32_t>;
- EXPECT_EQ(0, L::Partial(0).Size<0>());
- EXPECT_EQ(3, L::Partial(3).Size<0>());
- EXPECT_EQ(3, L(3).Size<0>());
- }
- {
- using L = Layout<int32_t, int32_t>;
- EXPECT_EQ(0, L::Partial(0).Size<0>());
- EXPECT_EQ(3, L::Partial(3).Size<0>());
- EXPECT_EQ(3, L::Partial(3, 5).Size<0>());
- EXPECT_EQ(5, L::Partial(3, 5).Size<1>());
- EXPECT_EQ(3, L(3, 5).Size<0>());
- EXPECT_EQ(5, L(3, 5).Size<1>());
- }
- {
- using L = Layout<int8_t, int32_t, Int128>;
- EXPECT_EQ(3, L::Partial(3).Size<0>());
- EXPECT_EQ(3, L::Partial(3, 5).Size<0>());
- EXPECT_EQ(5, L::Partial(3, 5).Size<1>());
- EXPECT_EQ(3, L::Partial(3, 5, 7).Size<0>());
- EXPECT_EQ(5, L::Partial(3, 5, 7).Size<1>());
- EXPECT_EQ(7, L::Partial(3, 5, 7).Size<2>());
- EXPECT_EQ(3, L(3, 5, 7).Size<0>());
- EXPECT_EQ(5, L(3, 5, 7).Size<1>());
- EXPECT_EQ(7, L(3, 5, 7).Size<2>());
- }
-}
-
-TEST(Layout, SizeByType) {
- {
- using L = Layout<int32_t>;
- EXPECT_EQ(0, L::Partial(0).Size<int32_t>());
- EXPECT_EQ(3, L::Partial(3).Size<int32_t>());
- EXPECT_EQ(3, L(3).Size<int32_t>());
- }
- {
- using L = Layout<int8_t, int32_t, Int128>;
- EXPECT_EQ(3, L::Partial(3).Size<int8_t>());
- EXPECT_EQ(3, L::Partial(3, 5).Size<int8_t>());
- EXPECT_EQ(5, L::Partial(3, 5).Size<int32_t>());
- EXPECT_EQ(3, L::Partial(3, 5, 7).Size<int8_t>());
- EXPECT_EQ(5, L::Partial(3, 5, 7).Size<int32_t>());
- EXPECT_EQ(7, L::Partial(3, 5, 7).Size<Int128>());
- EXPECT_EQ(3, L(3, 5, 7).Size<int8_t>());
- EXPECT_EQ(5, L(3, 5, 7).Size<int32_t>());
- EXPECT_EQ(7, L(3, 5, 7).Size<Int128>());
- }
-}
-
-TEST(Layout, Sizes) {
- {
- using L = Layout<int32_t>;
- EXPECT_THAT(L::Partial().Sizes(), ElementsAre());
- EXPECT_THAT(L::Partial(3).Sizes(), ElementsAre(3));
- EXPECT_THAT(L(3).Sizes(), ElementsAre(3));
- }
- {
- using L = Layout<int32_t, int32_t>;
- EXPECT_THAT(L::Partial().Sizes(), ElementsAre());
- EXPECT_THAT(L::Partial(3).Sizes(), ElementsAre(3));
- EXPECT_THAT(L::Partial(3, 5).Sizes(), ElementsAre(3, 5));
- EXPECT_THAT(L(3, 5).Sizes(), ElementsAre(3, 5));
- }
- {
- using L = Layout<int8_t, int32_t, Int128>;
- EXPECT_THAT(L::Partial().Sizes(), ElementsAre());
- EXPECT_THAT(L::Partial(3).Sizes(), ElementsAre(3));
- EXPECT_THAT(L::Partial(3, 5).Sizes(), ElementsAre(3, 5));
- EXPECT_THAT(L::Partial(3, 5, 7).Sizes(), ElementsAre(3, 5, 7));
- EXPECT_THAT(L(3, 5, 7).Sizes(), ElementsAre(3, 5, 7));
- }
-}
-
-TEST(Layout, PointerByIndex) {
- alignas(max_align_t) const unsigned char p[100] = {};
- {
- using L = Layout<int32_t>;
- EXPECT_EQ(0, Distance(p, Type<const int32_t*>(L::Partial().Pointer<0>(p))));
- EXPECT_EQ(0,
- Distance(p, Type<const int32_t*>(L::Partial(3).Pointer<0>(p))));
- EXPECT_EQ(0, Distance(p, Type<const int32_t*>(L(3).Pointer<0>(p))));
- }
- {
- using L = Layout<int32_t, int32_t>;
- EXPECT_EQ(0, Distance(p, Type<const int32_t*>(L::Partial().Pointer<0>(p))));
- EXPECT_EQ(0,
- Distance(p, Type<const int32_t*>(L::Partial(3).Pointer<0>(p))));
- EXPECT_EQ(12,
- Distance(p, Type<const int32_t*>(L::Partial(3).Pointer<1>(p))));
- EXPECT_EQ(
- 0, Distance(p, Type<const int32_t*>(L::Partial(3, 5).Pointer<0>(p))));
- EXPECT_EQ(
- 12, Distance(p, Type<const int32_t*>(L::Partial(3, 5).Pointer<1>(p))));
- EXPECT_EQ(0, Distance(p, Type<const int32_t*>(L(3, 5).Pointer<0>(p))));
- EXPECT_EQ(12, Distance(p, Type<const int32_t*>(L(3, 5).Pointer<1>(p))));
- }
- {
- using L = Layout<int8_t, int32_t, Int128>;
- EXPECT_EQ(0, Distance(p, Type<const int8_t*>(L::Partial().Pointer<0>(p))));
- EXPECT_EQ(0, Distance(p, Type<const int8_t*>(L::Partial(0).Pointer<0>(p))));
- EXPECT_EQ(0,
- Distance(p, Type<const int32_t*>(L::Partial(0).Pointer<1>(p))));
- EXPECT_EQ(0, Distance(p, Type<const int8_t*>(L::Partial(1).Pointer<0>(p))));
- EXPECT_EQ(4,
- Distance(p, Type<const int32_t*>(L::Partial(1).Pointer<1>(p))));
- EXPECT_EQ(0, Distance(p, Type<const int8_t*>(L::Partial(5).Pointer<0>(p))));
- EXPECT_EQ(8,
- Distance(p, Type<const int32_t*>(L::Partial(5).Pointer<1>(p))));
- EXPECT_EQ(0,
- Distance(p, Type<const int8_t*>(L::Partial(0, 0).Pointer<0>(p))));
- EXPECT_EQ(
- 0, Distance(p, Type<const int32_t*>(L::Partial(0, 0).Pointer<1>(p))));
- EXPECT_EQ(0,
- Distance(p, Type<const Int128*>(L::Partial(0, 0).Pointer<2>(p))));
- EXPECT_EQ(0,
- Distance(p, Type<const int8_t*>(L::Partial(1, 0).Pointer<0>(p))));
- EXPECT_EQ(
- 4, Distance(p, Type<const int32_t*>(L::Partial(1, 0).Pointer<1>(p))));
- EXPECT_EQ(8,
- Distance(p, Type<const Int128*>(L::Partial(1, 0).Pointer<2>(p))));
- EXPECT_EQ(0,
- Distance(p, Type<const int8_t*>(L::Partial(5, 3).Pointer<0>(p))));
- EXPECT_EQ(
- 8, Distance(p, Type<const int32_t*>(L::Partial(5, 3).Pointer<1>(p))));
- EXPECT_EQ(24,
- Distance(p, Type<const Int128*>(L::Partial(5, 3).Pointer<2>(p))));
- EXPECT_EQ(
- 0, Distance(p, Type<const int8_t*>(L::Partial(0, 0, 0).Pointer<0>(p))));
- EXPECT_EQ(
- 0,
- Distance(p, Type<const int32_t*>(L::Partial(0, 0, 0).Pointer<1>(p))));
- EXPECT_EQ(
- 0, Distance(p, Type<const Int128*>(L::Partial(0, 0, 0).Pointer<2>(p))));
- EXPECT_EQ(
- 0, Distance(p, Type<const int8_t*>(L::Partial(1, 0, 0).Pointer<0>(p))));
- EXPECT_EQ(
- 4,
- Distance(p, Type<const int32_t*>(L::Partial(1, 0, 0).Pointer<1>(p))));
- EXPECT_EQ(
- 8, Distance(p, Type<const Int128*>(L::Partial(1, 0, 0).Pointer<2>(p))));
- EXPECT_EQ(
- 0, Distance(p, Type<const int8_t*>(L::Partial(5, 3, 1).Pointer<0>(p))));
- EXPECT_EQ(
- 24,
- Distance(p, Type<const Int128*>(L::Partial(5, 3, 1).Pointer<2>(p))));
- EXPECT_EQ(
- 8,
- Distance(p, Type<const int32_t*>(L::Partial(5, 3, 1).Pointer<1>(p))));
- EXPECT_EQ(0, Distance(p, Type<const int8_t*>(L(5, 3, 1).Pointer<0>(p))));
- EXPECT_EQ(24, Distance(p, Type<const Int128*>(L(5, 3, 1).Pointer<2>(p))));
- EXPECT_EQ(8, Distance(p, Type<const int32_t*>(L(5, 3, 1).Pointer<1>(p))));
- }
-}
-
-TEST(Layout, PointerByType) {
- alignas(max_align_t) const unsigned char p[100] = {};
- {
- using L = Layout<int32_t>;
- EXPECT_EQ(
- 0, Distance(p, Type<const int32_t*>(L::Partial().Pointer<int32_t>(p))));
- EXPECT_EQ(
- 0,
- Distance(p, Type<const int32_t*>(L::Partial(3).Pointer<int32_t>(p))));
- EXPECT_EQ(0, Distance(p, Type<const int32_t*>(L(3).Pointer<int32_t>(p))));
- }
- {
- using L = Layout<int8_t, int32_t, Int128>;
- EXPECT_EQ(
- 0, Distance(p, Type<const int8_t*>(L::Partial().Pointer<int8_t>(p))));
- EXPECT_EQ(
- 0, Distance(p, Type<const int8_t*>(L::Partial(0).Pointer<int8_t>(p))));
- EXPECT_EQ(
- 0,
- Distance(p, Type<const int32_t*>(L::Partial(0).Pointer<int32_t>(p))));
- EXPECT_EQ(
- 0, Distance(p, Type<const int8_t*>(L::Partial(1).Pointer<int8_t>(p))));
- EXPECT_EQ(
- 4,
- Distance(p, Type<const int32_t*>(L::Partial(1).Pointer<int32_t>(p))));
- EXPECT_EQ(
- 0, Distance(p, Type<const int8_t*>(L::Partial(5).Pointer<int8_t>(p))));
- EXPECT_EQ(
- 8,
- Distance(p, Type<const int32_t*>(L::Partial(5).Pointer<int32_t>(p))));
- EXPECT_EQ(
- 0,
- Distance(p, Type<const int8_t*>(L::Partial(0, 0).Pointer<int8_t>(p))));
- EXPECT_EQ(0, Distance(p, Type<const int32_t*>(
- L::Partial(0, 0).Pointer<int32_t>(p))));
- EXPECT_EQ(
- 0,
- Distance(p, Type<const Int128*>(L::Partial(0, 0).Pointer<Int128>(p))));
- EXPECT_EQ(
- 0,
- Distance(p, Type<const int8_t*>(L::Partial(1, 0).Pointer<int8_t>(p))));
- EXPECT_EQ(4, Distance(p, Type<const int32_t*>(
- L::Partial(1, 0).Pointer<int32_t>(p))));
- EXPECT_EQ(
- 8,
- Distance(p, Type<const Int128*>(L::Partial(1, 0).Pointer<Int128>(p))));
- EXPECT_EQ(
- 0,
- Distance(p, Type<const int8_t*>(L::Partial(5, 3).Pointer<int8_t>(p))));
- EXPECT_EQ(8, Distance(p, Type<const int32_t*>(
- L::Partial(5, 3).Pointer<int32_t>(p))));
- EXPECT_EQ(
- 24,
- Distance(p, Type<const Int128*>(L::Partial(5, 3).Pointer<Int128>(p))));
- EXPECT_EQ(0, Distance(p, Type<const int8_t*>(
- L::Partial(0, 0, 0).Pointer<int8_t>(p))));
- EXPECT_EQ(0, Distance(p, Type<const int32_t*>(
- L::Partial(0, 0, 0).Pointer<int32_t>(p))));
- EXPECT_EQ(0, Distance(p, Type<const Int128*>(
- L::Partial(0, 0, 0).Pointer<Int128>(p))));
- EXPECT_EQ(0, Distance(p, Type<const int8_t*>(
- L::Partial(1, 0, 0).Pointer<int8_t>(p))));
- EXPECT_EQ(4, Distance(p, Type<const int32_t*>(
- L::Partial(1, 0, 0).Pointer<int32_t>(p))));
- EXPECT_EQ(8, Distance(p, Type<const Int128*>(
- L::Partial(1, 0, 0).Pointer<Int128>(p))));
- EXPECT_EQ(0, Distance(p, Type<const int8_t*>(
- L::Partial(5, 3, 1).Pointer<int8_t>(p))));
- EXPECT_EQ(24, Distance(p, Type<const Int128*>(
- L::Partial(5, 3, 1).Pointer<Int128>(p))));
- EXPECT_EQ(8, Distance(p, Type<const int32_t*>(
- L::Partial(5, 3, 1).Pointer<int32_t>(p))));
- EXPECT_EQ(24,
- Distance(p, Type<const Int128*>(L(5, 3, 1).Pointer<Int128>(p))));
- EXPECT_EQ(
- 8, Distance(p, Type<const int32_t*>(L(5, 3, 1).Pointer<int32_t>(p))));
- }
-}
-
-TEST(Layout, MutablePointerByIndex) {
- alignas(max_align_t) unsigned char p[100];
- {
- using L = Layout<int32_t>;
- EXPECT_EQ(0, Distance(p, Type<int32_t*>(L::Partial().Pointer<0>(p))));
- EXPECT_EQ(0, Distance(p, Type<int32_t*>(L::Partial(3).Pointer<0>(p))));
- EXPECT_EQ(0, Distance(p, Type<int32_t*>(L(3).Pointer<0>(p))));
- }
- {
- using L = Layout<int32_t, int32_t>;
- EXPECT_EQ(0, Distance(p, Type<int32_t*>(L::Partial().Pointer<0>(p))));
- EXPECT_EQ(0, Distance(p, Type<int32_t*>(L::Partial(3).Pointer<0>(p))));
- EXPECT_EQ(12, Distance(p, Type<int32_t*>(L::Partial(3).Pointer<1>(p))));
- EXPECT_EQ(0, Distance(p, Type<int32_t*>(L::Partial(3, 5).Pointer<0>(p))));
- EXPECT_EQ(12, Distance(p, Type<int32_t*>(L::Partial(3, 5).Pointer<1>(p))));
- EXPECT_EQ(0, Distance(p, Type<int32_t*>(L(3, 5).Pointer<0>(p))));
- EXPECT_EQ(12, Distance(p, Type<int32_t*>(L(3, 5).Pointer<1>(p))));
- }
- {
- using L = Layout<int8_t, int32_t, Int128>;
- EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial().Pointer<0>(p))));
- EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial(0).Pointer<0>(p))));
- EXPECT_EQ(0, Distance(p, Type<int32_t*>(L::Partial(0).Pointer<1>(p))));
- EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial(1).Pointer<0>(p))));
- EXPECT_EQ(4, Distance(p, Type<int32_t*>(L::Partial(1).Pointer<1>(p))));
- EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial(5).Pointer<0>(p))));
- EXPECT_EQ(8, Distance(p, Type<int32_t*>(L::Partial(5).Pointer<1>(p))));
- EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial(0, 0).Pointer<0>(p))));
- EXPECT_EQ(0, Distance(p, Type<int32_t*>(L::Partial(0, 0).Pointer<1>(p))));
- EXPECT_EQ(0, Distance(p, Type<Int128*>(L::Partial(0, 0).Pointer<2>(p))));
- EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial(1, 0).Pointer<0>(p))));
- EXPECT_EQ(4, Distance(p, Type<int32_t*>(L::Partial(1, 0).Pointer<1>(p))));
- EXPECT_EQ(8, Distance(p, Type<Int128*>(L::Partial(1, 0).Pointer<2>(p))));
- EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial(5, 3).Pointer<0>(p))));
- EXPECT_EQ(8, Distance(p, Type<int32_t*>(L::Partial(5, 3).Pointer<1>(p))));
- EXPECT_EQ(24, Distance(p, Type<Int128*>(L::Partial(5, 3).Pointer<2>(p))));
- EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial(0, 0, 0).Pointer<0>(p))));
- EXPECT_EQ(0,
- Distance(p, Type<int32_t*>(L::Partial(0, 0, 0).Pointer<1>(p))));
- EXPECT_EQ(0, Distance(p, Type<Int128*>(L::Partial(0, 0, 0).Pointer<2>(p))));
- EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial(1, 0, 0).Pointer<0>(p))));
- EXPECT_EQ(4,
- Distance(p, Type<int32_t*>(L::Partial(1, 0, 0).Pointer<1>(p))));
- EXPECT_EQ(8, Distance(p, Type<Int128*>(L::Partial(1, 0, 0).Pointer<2>(p))));
- EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial(5, 3, 1).Pointer<0>(p))));
- EXPECT_EQ(24,
- Distance(p, Type<Int128*>(L::Partial(5, 3, 1).Pointer<2>(p))));
- EXPECT_EQ(8,
- Distance(p, Type<int32_t*>(L::Partial(5, 3, 1).Pointer<1>(p))));
- EXPECT_EQ(0, Distance(p, Type<int8_t*>(L(5, 3, 1).Pointer<0>(p))));
- EXPECT_EQ(24, Distance(p, Type<Int128*>(L(5, 3, 1).Pointer<2>(p))));
- EXPECT_EQ(8, Distance(p, Type<int32_t*>(L(5, 3, 1).Pointer<1>(p))));
- }
-}
-
-TEST(Layout, MutablePointerByType) {
- alignas(max_align_t) unsigned char p[100];
- {
- using L = Layout<int32_t>;
- EXPECT_EQ(0, Distance(p, Type<int32_t*>(L::Partial().Pointer<int32_t>(p))));
- EXPECT_EQ(0,
- Distance(p, Type<int32_t*>(L::Partial(3).Pointer<int32_t>(p))));
- EXPECT_EQ(0, Distance(p, Type<int32_t*>(L(3).Pointer<int32_t>(p))));
- }
- {
- using L = Layout<int8_t, int32_t, Int128>;
- EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial().Pointer<int8_t>(p))));
- EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial(0).Pointer<int8_t>(p))));
- EXPECT_EQ(0,
- Distance(p, Type<int32_t*>(L::Partial(0).Pointer<int32_t>(p))));
- EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial(1).Pointer<int8_t>(p))));
- EXPECT_EQ(4,
- Distance(p, Type<int32_t*>(L::Partial(1).Pointer<int32_t>(p))));
- EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial(5).Pointer<int8_t>(p))));
- EXPECT_EQ(8,
- Distance(p, Type<int32_t*>(L::Partial(5).Pointer<int32_t>(p))));
- EXPECT_EQ(0,
- Distance(p, Type<int8_t*>(L::Partial(0, 0).Pointer<int8_t>(p))));
- EXPECT_EQ(
- 0, Distance(p, Type<int32_t*>(L::Partial(0, 0).Pointer<int32_t>(p))));
- EXPECT_EQ(0,
- Distance(p, Type<Int128*>(L::Partial(0, 0).Pointer<Int128>(p))));
- EXPECT_EQ(0,
- Distance(p, Type<int8_t*>(L::Partial(1, 0).Pointer<int8_t>(p))));
- EXPECT_EQ(
- 4, Distance(p, Type<int32_t*>(L::Partial(1, 0).Pointer<int32_t>(p))));
- EXPECT_EQ(8,
- Distance(p, Type<Int128*>(L::Partial(1, 0).Pointer<Int128>(p))));
- EXPECT_EQ(0,
- Distance(p, Type<int8_t*>(L::Partial(5, 3).Pointer<int8_t>(p))));
- EXPECT_EQ(
- 8, Distance(p, Type<int32_t*>(L::Partial(5, 3).Pointer<int32_t>(p))));
- EXPECT_EQ(24,
- Distance(p, Type<Int128*>(L::Partial(5, 3).Pointer<Int128>(p))));
- EXPECT_EQ(
- 0, Distance(p, Type<int8_t*>(L::Partial(0, 0, 0).Pointer<int8_t>(p))));
- EXPECT_EQ(
- 0,
- Distance(p, Type<int32_t*>(L::Partial(0, 0, 0).Pointer<int32_t>(p))));
- EXPECT_EQ(
- 0, Distance(p, Type<Int128*>(L::Partial(0, 0, 0).Pointer<Int128>(p))));
- EXPECT_EQ(
- 0, Distance(p, Type<int8_t*>(L::Partial(1, 0, 0).Pointer<int8_t>(p))));
- EXPECT_EQ(
- 4,
- Distance(p, Type<int32_t*>(L::Partial(1, 0, 0).Pointer<int32_t>(p))));
- EXPECT_EQ(
- 8, Distance(p, Type<Int128*>(L::Partial(1, 0, 0).Pointer<Int128>(p))));
- EXPECT_EQ(
- 0, Distance(p, Type<int8_t*>(L::Partial(5, 3, 1).Pointer<int8_t>(p))));
- EXPECT_EQ(
- 24, Distance(p, Type<Int128*>(L::Partial(5, 3, 1).Pointer<Int128>(p))));
- EXPECT_EQ(
- 8,
- Distance(p, Type<int32_t*>(L::Partial(5, 3, 1).Pointer<int32_t>(p))));
- EXPECT_EQ(0, Distance(p, Type<int8_t*>(L(5, 3, 1).Pointer<int8_t>(p))));
- EXPECT_EQ(24, Distance(p, Type<Int128*>(L(5, 3, 1).Pointer<Int128>(p))));
- EXPECT_EQ(8, Distance(p, Type<int32_t*>(L(5, 3, 1).Pointer<int32_t>(p))));
- }
-}
-
-TEST(Layout, Pointers) {
- alignas(max_align_t) const unsigned char p[100] = {};
- using L = Layout<int8_t, int8_t, Int128>;
- {
- const auto x = L::Partial();
- EXPECT_EQ(std::make_tuple(x.Pointer<0>(p)),
- Type<std::tuple<const int8_t*>>(x.Pointers(p)));
- }
- {
- const auto x = L::Partial(1);
- EXPECT_EQ(std::make_tuple(x.Pointer<0>(p), x.Pointer<1>(p)),
- (Type<std::tuple<const int8_t*, const int8_t*>>(x.Pointers(p))));
- }
- {
- const auto x = L::Partial(1, 2);
- EXPECT_EQ(
- std::make_tuple(x.Pointer<0>(p), x.Pointer<1>(p), x.Pointer<2>(p)),
- (Type<std::tuple<const int8_t*, const int8_t*, const Int128*>>(
- x.Pointers(p))));
- }
- {
- const auto x = L::Partial(1, 2, 3);
- EXPECT_EQ(
- std::make_tuple(x.Pointer<0>(p), x.Pointer<1>(p), x.Pointer<2>(p)),
- (Type<std::tuple<const int8_t*, const int8_t*, const Int128*>>(
- x.Pointers(p))));
- }
- {
- const L x(1, 2, 3);
- EXPECT_EQ(
- std::make_tuple(x.Pointer<0>(p), x.Pointer<1>(p), x.Pointer<2>(p)),
- (Type<std::tuple<const int8_t*, const int8_t*, const Int128*>>(
- x.Pointers(p))));
- }
-}
-
-TEST(Layout, MutablePointers) {
- alignas(max_align_t) unsigned char p[100];
- using L = Layout<int8_t, int8_t, Int128>;
- {
- const auto x = L::Partial();
- EXPECT_EQ(std::make_tuple(x.Pointer<0>(p)),
- Type<std::tuple<int8_t*>>(x.Pointers(p)));
- }
- {
- const auto x = L::Partial(1);
- EXPECT_EQ(std::make_tuple(x.Pointer<0>(p), x.Pointer<1>(p)),
- (Type<std::tuple<int8_t*, int8_t*>>(x.Pointers(p))));
- }
- {
- const auto x = L::Partial(1, 2);
- EXPECT_EQ(
- std::make_tuple(x.Pointer<0>(p), x.Pointer<1>(p), x.Pointer<2>(p)),
- (Type<std::tuple<int8_t*, int8_t*, Int128*>>(x.Pointers(p))));
- }
- {
- const auto x = L::Partial(1, 2, 3);
- EXPECT_EQ(
- std::make_tuple(x.Pointer<0>(p), x.Pointer<1>(p), x.Pointer<2>(p)),
- (Type<std::tuple<int8_t*, int8_t*, Int128*>>(x.Pointers(p))));
- }
- {
- const L x(1, 2, 3);
- EXPECT_EQ(
- std::make_tuple(x.Pointer<0>(p), x.Pointer<1>(p), x.Pointer<2>(p)),
- (Type<std::tuple<int8_t*, int8_t*, Int128*>>(x.Pointers(p))));
- }
-}
-
-TEST(Layout, SliceByIndexSize) {
- alignas(max_align_t) const unsigned char p[100] = {};
- {
- using L = Layout<int32_t>;
- EXPECT_EQ(0, L::Partial(0).Slice<0>(p).size());
- EXPECT_EQ(3, L::Partial(3).Slice<0>(p).size());
- EXPECT_EQ(3, L(3).Slice<0>(p).size());
- }
- {
- using L = Layout<int32_t, int32_t>;
- EXPECT_EQ(3, L::Partial(3).Slice<0>(p).size());
- EXPECT_EQ(5, L::Partial(3, 5).Slice<1>(p).size());
- EXPECT_EQ(5, L(3, 5).Slice<1>(p).size());
- }
- {
- using L = Layout<int8_t, int32_t, Int128>;
- EXPECT_EQ(3, L::Partial(3).Slice<0>(p).size());
- EXPECT_EQ(3, L::Partial(3, 5).Slice<0>(p).size());
- EXPECT_EQ(5, L::Partial(3, 5).Slice<1>(p).size());
- EXPECT_EQ(3, L::Partial(3, 5, 7).Slice<0>(p).size());
- EXPECT_EQ(5, L::Partial(3, 5, 7).Slice<1>(p).size());
- EXPECT_EQ(7, L::Partial(3, 5, 7).Slice<2>(p).size());
- EXPECT_EQ(3, L(3, 5, 7).Slice<0>(p).size());
- EXPECT_EQ(5, L(3, 5, 7).Slice<1>(p).size());
- EXPECT_EQ(7, L(3, 5, 7).Slice<2>(p).size());
- }
-}
-
-TEST(Layout, SliceByTypeSize) {
- alignas(max_align_t) const unsigned char p[100] = {};
- {
- using L = Layout<int32_t>;
- EXPECT_EQ(0, L::Partial(0).Slice<int32_t>(p).size());
- EXPECT_EQ(3, L::Partial(3).Slice<int32_t>(p).size());
- EXPECT_EQ(3, L(3).Slice<int32_t>(p).size());
- }
- {
- using L = Layout<int8_t, int32_t, Int128>;
- EXPECT_EQ(3, L::Partial(3).Slice<int8_t>(p).size());
- EXPECT_EQ(3, L::Partial(3, 5).Slice<int8_t>(p).size());
- EXPECT_EQ(5, L::Partial(3, 5).Slice<int32_t>(p).size());
- EXPECT_EQ(3, L::Partial(3, 5, 7).Slice<int8_t>(p).size());
- EXPECT_EQ(5, L::Partial(3, 5, 7).Slice<int32_t>(p).size());
- EXPECT_EQ(7, L::Partial(3, 5, 7).Slice<Int128>(p).size());
- EXPECT_EQ(3, L(3, 5, 7).Slice<int8_t>(p).size());
- EXPECT_EQ(5, L(3, 5, 7).Slice<int32_t>(p).size());
- EXPECT_EQ(7, L(3, 5, 7).Slice<Int128>(p).size());
- }
-}
-
-TEST(Layout, MutableSliceByIndexSize) {
- alignas(max_align_t) unsigned char p[100];
- {
- using L = Layout<int32_t>;
- EXPECT_EQ(0, L::Partial(0).Slice<0>(p).size());
- EXPECT_EQ(3, L::Partial(3).Slice<0>(p).size());
- EXPECT_EQ(3, L(3).Slice<0>(p).size());
- }
- {
- using L = Layout<int32_t, int32_t>;
- EXPECT_EQ(3, L::Partial(3).Slice<0>(p).size());
- EXPECT_EQ(5, L::Partial(3, 5).Slice<1>(p).size());
- EXPECT_EQ(5, L(3, 5).Slice<1>(p).size());
- }
- {
- using L = Layout<int8_t, int32_t, Int128>;
- EXPECT_EQ(3, L::Partial(3).Slice<0>(p).size());
- EXPECT_EQ(3, L::Partial(3, 5).Slice<0>(p).size());
- EXPECT_EQ(5, L::Partial(3, 5).Slice<1>(p).size());
- EXPECT_EQ(3, L::Partial(3, 5, 7).Slice<0>(p).size());
- EXPECT_EQ(5, L::Partial(3, 5, 7).Slice<1>(p).size());
- EXPECT_EQ(7, L::Partial(3, 5, 7).Slice<2>(p).size());
- EXPECT_EQ(3, L(3, 5, 7).Slice<0>(p).size());
- EXPECT_EQ(5, L(3, 5, 7).Slice<1>(p).size());
- EXPECT_EQ(7, L(3, 5, 7).Slice<2>(p).size());
- }
-}
-
-TEST(Layout, MutableSliceByTypeSize) {
- alignas(max_align_t) unsigned char p[100];
- {
- using L = Layout<int32_t>;
- EXPECT_EQ(0, L::Partial(0).Slice<int32_t>(p).size());
- EXPECT_EQ(3, L::Partial(3).Slice<int32_t>(p).size());
- EXPECT_EQ(3, L(3).Slice<int32_t>(p).size());
- }
- {
- using L = Layout<int8_t, int32_t, Int128>;
- EXPECT_EQ(3, L::Partial(3).Slice<int8_t>(p).size());
- EXPECT_EQ(3, L::Partial(3, 5).Slice<int8_t>(p).size());
- EXPECT_EQ(5, L::Partial(3, 5).Slice<int32_t>(p).size());
- EXPECT_EQ(3, L::Partial(3, 5, 7).Slice<int8_t>(p).size());
- EXPECT_EQ(5, L::Partial(3, 5, 7).Slice<int32_t>(p).size());
- EXPECT_EQ(7, L::Partial(3, 5, 7).Slice<Int128>(p).size());
- EXPECT_EQ(3, L(3, 5, 7).Slice<int8_t>(p).size());
- EXPECT_EQ(5, L(3, 5, 7).Slice<int32_t>(p).size());
- EXPECT_EQ(7, L(3, 5, 7).Slice<Int128>(p).size());
- }
-}
-
-TEST(Layout, SliceByIndexData) {
- alignas(max_align_t) const unsigned char p[100] = {};
- {
- using L = Layout<int32_t>;
- EXPECT_EQ(
- 0, Distance(
- p, Type<Span<const int32_t>>(L::Partial(0).Slice<0>(p)).data()));
- EXPECT_EQ(
- 0, Distance(
- p, Type<Span<const int32_t>>(L::Partial(3).Slice<0>(p)).data()));
- EXPECT_EQ(0,
- Distance(p, Type<Span<const int32_t>>(L(3).Slice<0>(p)).data()));
- }
- {
- using L = Layout<int32_t, int32_t>;
- EXPECT_EQ(
- 0, Distance(
- p, Type<Span<const int32_t>>(L::Partial(3).Slice<0>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(
- p, Type<Span<const int32_t>>(L::Partial(3, 5).Slice<0>(p)).data()));
- EXPECT_EQ(
- 12,
- Distance(
- p, Type<Span<const int32_t>>(L::Partial(3, 5).Slice<1>(p)).data()));
- EXPECT_EQ(
- 0, Distance(p, Type<Span<const int32_t>>(L(3, 5).Slice<0>(p)).data()));
- EXPECT_EQ(
- 12, Distance(p, Type<Span<const int32_t>>(L(3, 5).Slice<1>(p)).data()));
- }
- {
- using L = Layout<int8_t, int32_t, Int128>;
- EXPECT_EQ(
- 0, Distance(
- p, Type<Span<const int8_t>>(L::Partial(0).Slice<0>(p)).data()));
- EXPECT_EQ(
- 0, Distance(
- p, Type<Span<const int8_t>>(L::Partial(1).Slice<0>(p)).data()));
- EXPECT_EQ(
- 0, Distance(
- p, Type<Span<const int8_t>>(L::Partial(5).Slice<0>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(
- p, Type<Span<const int8_t>>(L::Partial(0, 0).Slice<0>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(
- p, Type<Span<const int32_t>>(L::Partial(0, 0).Slice<1>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(
- p, Type<Span<const int8_t>>(L::Partial(1, 0).Slice<0>(p)).data()));
- EXPECT_EQ(
- 4,
- Distance(
- p, Type<Span<const int32_t>>(L::Partial(1, 0).Slice<1>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(
- p, Type<Span<const int8_t>>(L::Partial(5, 3).Slice<0>(p)).data()));
- EXPECT_EQ(
- 8,
- Distance(
- p, Type<Span<const int32_t>>(L::Partial(5, 3).Slice<1>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(
- p,
- Type<Span<const int8_t>>(L::Partial(0, 0, 0).Slice<0>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(
- p,
- Type<Span<const int32_t>>(L::Partial(0, 0, 0).Slice<1>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(
- p,
- Type<Span<const Int128>>(L::Partial(0, 0, 0).Slice<2>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(
- p,
- Type<Span<const int8_t>>(L::Partial(1, 0, 0).Slice<0>(p)).data()));
- EXPECT_EQ(
- 4,
- Distance(
- p,
- Type<Span<const int32_t>>(L::Partial(1, 0, 0).Slice<1>(p)).data()));
- EXPECT_EQ(
- 8,
- Distance(
- p,
- Type<Span<const Int128>>(L::Partial(1, 0, 0).Slice<2>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(
- p,
- Type<Span<const int8_t>>(L::Partial(5, 3, 1).Slice<0>(p)).data()));
- EXPECT_EQ(
- 24,
- Distance(
- p,
- Type<Span<const Int128>>(L::Partial(5, 3, 1).Slice<2>(p)).data()));
- EXPECT_EQ(
- 8,
- Distance(
- p,
- Type<Span<const int32_t>>(L::Partial(5, 3, 1).Slice<1>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(p, Type<Span<const int8_t>>(L(5, 3, 1).Slice<0>(p)).data()));
- EXPECT_EQ(
- 24,
- Distance(p, Type<Span<const Int128>>(L(5, 3, 1).Slice<2>(p)).data()));
- EXPECT_EQ(
- 8,
- Distance(p, Type<Span<const int32_t>>(L(5, 3, 1).Slice<1>(p)).data()));
- }
-}
-
-TEST(Layout, SliceByTypeData) {
- alignas(max_align_t) const unsigned char p[100] = {};
- {
- using L = Layout<int32_t>;
- EXPECT_EQ(
- 0,
- Distance(
- p,
- Type<Span<const int32_t>>(L::Partial(0).Slice<int32_t>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(
- p,
- Type<Span<const int32_t>>(L::Partial(3).Slice<int32_t>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(p, Type<Span<const int32_t>>(L(3).Slice<int32_t>(p)).data()));
- }
- {
- using L = Layout<int8_t, int32_t, Int128>;
- EXPECT_EQ(
- 0,
- Distance(
- p,
- Type<Span<const int8_t>>(L::Partial(0).Slice<int8_t>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(
- p,
- Type<Span<const int8_t>>(L::Partial(1).Slice<int8_t>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(
- p,
- Type<Span<const int8_t>>(L::Partial(5).Slice<int8_t>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(p, Type<Span<const int8_t>>(L::Partial(0, 0).Slice<int8_t>(p))
- .data()));
- EXPECT_EQ(0, Distance(p, Type<Span<const int32_t>>(
- L::Partial(0, 0).Slice<int32_t>(p))
- .data()));
- EXPECT_EQ(
- 0,
- Distance(p, Type<Span<const int8_t>>(L::Partial(1, 0).Slice<int8_t>(p))
- .data()));
- EXPECT_EQ(4, Distance(p, Type<Span<const int32_t>>(
- L::Partial(1, 0).Slice<int32_t>(p))
- .data()));
- EXPECT_EQ(
- 0,
- Distance(p, Type<Span<const int8_t>>(L::Partial(5, 3).Slice<int8_t>(p))
- .data()));
- EXPECT_EQ(8, Distance(p, Type<Span<const int32_t>>(
- L::Partial(5, 3).Slice<int32_t>(p))
- .data()));
- EXPECT_EQ(0, Distance(p, Type<Span<const int8_t>>(
- L::Partial(0, 0, 0).Slice<int8_t>(p))
- .data()));
- EXPECT_EQ(0, Distance(p, Type<Span<const int32_t>>(
- L::Partial(0, 0, 0).Slice<int32_t>(p))
- .data()));
- EXPECT_EQ(0, Distance(p, Type<Span<const Int128>>(
- L::Partial(0, 0, 0).Slice<Int128>(p))
- .data()));
- EXPECT_EQ(0, Distance(p, Type<Span<const int8_t>>(
- L::Partial(1, 0, 0).Slice<int8_t>(p))
- .data()));
- EXPECT_EQ(4, Distance(p, Type<Span<const int32_t>>(
- L::Partial(1, 0, 0).Slice<int32_t>(p))
- .data()));
- EXPECT_EQ(8, Distance(p, Type<Span<const Int128>>(
- L::Partial(1, 0, 0).Slice<Int128>(p))
- .data()));
- EXPECT_EQ(0, Distance(p, Type<Span<const int8_t>>(
- L::Partial(5, 3, 1).Slice<int8_t>(p))
- .data()));
- EXPECT_EQ(24, Distance(p, Type<Span<const Int128>>(
- L::Partial(5, 3, 1).Slice<Int128>(p))
- .data()));
- EXPECT_EQ(8, Distance(p, Type<Span<const int32_t>>(
- L::Partial(5, 3, 1).Slice<int32_t>(p))
- .data()));
- EXPECT_EQ(
- 0,
- Distance(p,
- Type<Span<const int8_t>>(L(5, 3, 1).Slice<int8_t>(p)).data()));
- EXPECT_EQ(
- 24,
- Distance(p,
- Type<Span<const Int128>>(L(5, 3, 1).Slice<Int128>(p)).data()));
- EXPECT_EQ(
- 8,
- Distance(
- p, Type<Span<const int32_t>>(L(5, 3, 1).Slice<int32_t>(p)).data()));
- }
-}
-
-TEST(Layout, MutableSliceByIndexData) {
- alignas(max_align_t) unsigned char p[100];
- {
- using L = Layout<int32_t>;
- EXPECT_EQ(
- 0, Distance(p, Type<Span<int32_t>>(L::Partial(0).Slice<0>(p)).data()));
- EXPECT_EQ(
- 0, Distance(p, Type<Span<int32_t>>(L::Partial(3).Slice<0>(p)).data()));
- EXPECT_EQ(0, Distance(p, Type<Span<int32_t>>(L(3).Slice<0>(p)).data()));
- }
- {
- using L = Layout<int32_t, int32_t>;
- EXPECT_EQ(
- 0, Distance(p, Type<Span<int32_t>>(L::Partial(3).Slice<0>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(p, Type<Span<int32_t>>(L::Partial(3, 5).Slice<0>(p)).data()));
- EXPECT_EQ(
- 12,
- Distance(p, Type<Span<int32_t>>(L::Partial(3, 5).Slice<1>(p)).data()));
- EXPECT_EQ(0, Distance(p, Type<Span<int32_t>>(L(3, 5).Slice<0>(p)).data()));
- EXPECT_EQ(12, Distance(p, Type<Span<int32_t>>(L(3, 5).Slice<1>(p)).data()));
- }
- {
- using L = Layout<int8_t, int32_t, Int128>;
- EXPECT_EQ(
- 0, Distance(p, Type<Span<int8_t>>(L::Partial(0).Slice<0>(p)).data()));
- EXPECT_EQ(
- 0, Distance(p, Type<Span<int8_t>>(L::Partial(1).Slice<0>(p)).data()));
- EXPECT_EQ(
- 0, Distance(p, Type<Span<int8_t>>(L::Partial(5).Slice<0>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(p, Type<Span<int8_t>>(L::Partial(0, 0).Slice<0>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(p, Type<Span<int32_t>>(L::Partial(0, 0).Slice<1>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(p, Type<Span<int8_t>>(L::Partial(1, 0).Slice<0>(p)).data()));
- EXPECT_EQ(
- 4,
- Distance(p, Type<Span<int32_t>>(L::Partial(1, 0).Slice<1>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(p, Type<Span<int8_t>>(L::Partial(5, 3).Slice<0>(p)).data()));
- EXPECT_EQ(
- 8,
- Distance(p, Type<Span<int32_t>>(L::Partial(5, 3).Slice<1>(p)).data()));
- EXPECT_EQ(
- 0, Distance(
- p, Type<Span<int8_t>>(L::Partial(0, 0, 0).Slice<0>(p)).data()));
- EXPECT_EQ(
- 0, Distance(
- p, Type<Span<int32_t>>(L::Partial(0, 0, 0).Slice<1>(p)).data()));
- EXPECT_EQ(
- 0, Distance(
- p, Type<Span<Int128>>(L::Partial(0, 0, 0).Slice<2>(p)).data()));
- EXPECT_EQ(
- 0, Distance(
- p, Type<Span<int8_t>>(L::Partial(1, 0, 0).Slice<0>(p)).data()));
- EXPECT_EQ(
- 4, Distance(
- p, Type<Span<int32_t>>(L::Partial(1, 0, 0).Slice<1>(p)).data()));
- EXPECT_EQ(
- 8, Distance(
- p, Type<Span<Int128>>(L::Partial(1, 0, 0).Slice<2>(p)).data()));
- EXPECT_EQ(
- 0, Distance(
- p, Type<Span<int8_t>>(L::Partial(5, 3, 1).Slice<0>(p)).data()));
- EXPECT_EQ(
- 24, Distance(
- p, Type<Span<Int128>>(L::Partial(5, 3, 1).Slice<2>(p)).data()));
- EXPECT_EQ(
- 8, Distance(
- p, Type<Span<int32_t>>(L::Partial(5, 3, 1).Slice<1>(p)).data()));
- EXPECT_EQ(0,
- Distance(p, Type<Span<int8_t>>(L(5, 3, 1).Slice<0>(p)).data()));
- EXPECT_EQ(24,
- Distance(p, Type<Span<Int128>>(L(5, 3, 1).Slice<2>(p)).data()));
- EXPECT_EQ(8,
- Distance(p, Type<Span<int32_t>>(L(5, 3, 1).Slice<1>(p)).data()));
- }
-}
-
-TEST(Layout, MutableSliceByTypeData) {
- alignas(max_align_t) unsigned char p[100];
- {
- using L = Layout<int32_t>;
- EXPECT_EQ(
- 0, Distance(
- p, Type<Span<int32_t>>(L::Partial(0).Slice<int32_t>(p)).data()));
- EXPECT_EQ(
- 0, Distance(
- p, Type<Span<int32_t>>(L::Partial(3).Slice<int32_t>(p)).data()));
- EXPECT_EQ(0,
- Distance(p, Type<Span<int32_t>>(L(3).Slice<int32_t>(p)).data()));
- }
- {
- using L = Layout<int8_t, int32_t, Int128>;
- EXPECT_EQ(
- 0,
- Distance(p, Type<Span<int8_t>>(L::Partial(0).Slice<int8_t>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(p, Type<Span<int8_t>>(L::Partial(1).Slice<int8_t>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(p, Type<Span<int8_t>>(L::Partial(5).Slice<int8_t>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(p,
- Type<Span<int8_t>>(L::Partial(0, 0).Slice<int8_t>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(
- p, Type<Span<int32_t>>(L::Partial(0, 0).Slice<int32_t>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(p,
- Type<Span<int8_t>>(L::Partial(1, 0).Slice<int8_t>(p)).data()));
- EXPECT_EQ(
- 4,
- Distance(
- p, Type<Span<int32_t>>(L::Partial(1, 0).Slice<int32_t>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(p,
- Type<Span<int8_t>>(L::Partial(5, 3).Slice<int8_t>(p)).data()));
- EXPECT_EQ(
- 8,
- Distance(
- p, Type<Span<int32_t>>(L::Partial(5, 3).Slice<int32_t>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(
- p,
- Type<Span<int8_t>>(L::Partial(0, 0, 0).Slice<int8_t>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(
- p,
- Type<Span<int32_t>>(L::Partial(0, 0, 0).Slice<int32_t>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(
- p,
- Type<Span<Int128>>(L::Partial(0, 0, 0).Slice<Int128>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(
- p,
- Type<Span<int8_t>>(L::Partial(1, 0, 0).Slice<int8_t>(p)).data()));
- EXPECT_EQ(
- 4,
- Distance(
- p,
- Type<Span<int32_t>>(L::Partial(1, 0, 0).Slice<int32_t>(p)).data()));
- EXPECT_EQ(
- 8,
- Distance(
- p,
- Type<Span<Int128>>(L::Partial(1, 0, 0).Slice<Int128>(p)).data()));
- EXPECT_EQ(
- 0,
- Distance(
- p,
- Type<Span<int8_t>>(L::Partial(5, 3, 1).Slice<int8_t>(p)).data()));
- EXPECT_EQ(
- 24,
- Distance(
- p,
- Type<Span<Int128>>(L::Partial(5, 3, 1).Slice<Int128>(p)).data()));
- EXPECT_EQ(
- 8,
- Distance(
- p,
- Type<Span<int32_t>>(L::Partial(5, 3, 1).Slice<int32_t>(p)).data()));
- EXPECT_EQ(
- 0, Distance(p, Type<Span<int8_t>>(L(5, 3, 1).Slice<int8_t>(p)).data()));
- EXPECT_EQ(
- 24,
- Distance(p, Type<Span<Int128>>(L(5, 3, 1).Slice<Int128>(p)).data()));
- EXPECT_EQ(
- 8,
- Distance(p, Type<Span<int32_t>>(L(5, 3, 1).Slice<int32_t>(p)).data()));
- }
-}
-
-MATCHER_P(IsSameSlice, slice, "") {
- return arg.size() == slice.size() && arg.data() == slice.data();
-}
-
-template <typename... M>
-class TupleMatcher {
- public:
- explicit TupleMatcher(M... matchers) : matchers_(std::move(matchers)...) {}
-
- template <typename Tuple>
- bool MatchAndExplain(const Tuple& p,
- testing::MatchResultListener* /* listener */) const {
- static_assert(std::tuple_size<Tuple>::value == sizeof...(M), "");
- return MatchAndExplainImpl(
- p, absl::make_index_sequence<std::tuple_size<Tuple>::value>{});
- }
-
- // For the matcher concept. Left empty as we don't really need the diagnostics
- // right now.
- void DescribeTo(::std::ostream* os) const {}
- void DescribeNegationTo(::std::ostream* os) const {}
-
- private:
- template <typename Tuple, size_t... Is>
- bool MatchAndExplainImpl(const Tuple& p, absl::index_sequence<Is...>) const {
- // Using std::min as a simple variadic "and".
- return std::min(
- {true, testing::SafeMatcherCast<
- const typename std::tuple_element<Is, Tuple>::type&>(
- std::get<Is>(matchers_))
- .Matches(std::get<Is>(p))...});
- }
-
- std::tuple<M...> matchers_;
-};
-
-template <typename... M>
-testing::PolymorphicMatcher<TupleMatcher<M...>> Tuple(M... matchers) {
- return testing::MakePolymorphicMatcher(
- TupleMatcher<M...>(std::move(matchers)...));
-}
-
-TEST(Layout, Slices) {
- alignas(max_align_t) const unsigned char p[100] = {};
- using L = Layout<int8_t, int8_t, Int128>;
- {
- const auto x = L::Partial();
- EXPECT_THAT(Type<std::tuple<>>(x.Slices(p)), Tuple());
- }
- {
- const auto x = L::Partial(1);
- EXPECT_THAT(Type<std::tuple<Span<const int8_t>>>(x.Slices(p)),
- Tuple(IsSameSlice(x.Slice<0>(p))));
- }
- {
- const auto x = L::Partial(1, 2);
- EXPECT_THAT(
- (Type<std::tuple<Span<const int8_t>, Span<const int8_t>>>(x.Slices(p))),
- Tuple(IsSameSlice(x.Slice<0>(p)), IsSameSlice(x.Slice<1>(p))));
- }
- {
- const auto x = L::Partial(1, 2, 3);
- EXPECT_THAT((Type<std::tuple<Span<const int8_t>, Span<const int8_t>,
- Span<const Int128>>>(x.Slices(p))),
- Tuple(IsSameSlice(x.Slice<0>(p)), IsSameSlice(x.Slice<1>(p)),
- IsSameSlice(x.Slice<2>(p))));
- }
- {
- const L x(1, 2, 3);
- EXPECT_THAT((Type<std::tuple<Span<const int8_t>, Span<const int8_t>,
- Span<const Int128>>>(x.Slices(p))),
- Tuple(IsSameSlice(x.Slice<0>(p)), IsSameSlice(x.Slice<1>(p)),
- IsSameSlice(x.Slice<2>(p))));
- }
-}
-
-TEST(Layout, MutableSlices) {
- alignas(max_align_t) unsigned char p[100] = {};
- using L = Layout<int8_t, int8_t, Int128>;
- {
- const auto x = L::Partial();
- EXPECT_THAT(Type<std::tuple<>>(x.Slices(p)), Tuple());
- }
- {
- const auto x = L::Partial(1);
- EXPECT_THAT(Type<std::tuple<Span<int8_t>>>(x.Slices(p)),
- Tuple(IsSameSlice(x.Slice<0>(p))));
- }
- {
- const auto x = L::Partial(1, 2);
- EXPECT_THAT((Type<std::tuple<Span<int8_t>, Span<int8_t>>>(x.Slices(p))),
- Tuple(IsSameSlice(x.Slice<0>(p)), IsSameSlice(x.Slice<1>(p))));
- }
- {
- const auto x = L::Partial(1, 2, 3);
- EXPECT_THAT((Type<std::tuple<Span<int8_t>, Span<int8_t>, Span<Int128>>>(
- x.Slices(p))),
- Tuple(IsSameSlice(x.Slice<0>(p)), IsSameSlice(x.Slice<1>(p)),
- IsSameSlice(x.Slice<2>(p))));
- }
- {
- const L x(1, 2, 3);
- EXPECT_THAT((Type<std::tuple<Span<int8_t>, Span<int8_t>, Span<Int128>>>(
- x.Slices(p))),
- Tuple(IsSameSlice(x.Slice<0>(p)), IsSameSlice(x.Slice<1>(p)),
- IsSameSlice(x.Slice<2>(p))));
- }
-}
-
-TEST(Layout, UnalignedTypes) {
- constexpr Layout<unsigned char, unsigned char, unsigned char> x(1, 2, 3);
- alignas(max_align_t) unsigned char p[x.AllocSize() + 1];
- EXPECT_THAT(x.Pointers(p + 1), Tuple(p + 1, p + 2, p + 4));
-}
-
-TEST(Layout, CustomAlignment) {
- constexpr Layout<unsigned char, Aligned<unsigned char, 8>> x(1, 2);
- alignas(max_align_t) unsigned char p[x.AllocSize()];
- EXPECT_EQ(10, x.AllocSize());
- EXPECT_THAT(x.Pointers(p), Tuple(p + 0, p + 8));
-}
-
-TEST(Layout, OverAligned) {
- constexpr size_t M = alignof(max_align_t);
- constexpr Layout<unsigned char, Aligned<unsigned char, 2 * M>> x(1, 3);
-#ifdef __GNUC__
- // Using __attribute__ ((aligned ())) instead of alignas to bypass a gcc bug:
- // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=89357
- __attribute__((aligned(2 * M))) unsigned char p[x.AllocSize()];
-#else
- alignas(2 * M) unsigned char p[x.AllocSize()];
-#endif
- EXPECT_EQ(2 * M + 3, x.AllocSize());
- EXPECT_THAT(x.Pointers(p), Tuple(p + 0, p + 2 * M));
-}
-
-TEST(Layout, Alignment) {
- static_assert(Layout<int8_t>::Alignment() == 1, "");
- static_assert(Layout<int32_t>::Alignment() == 4, "");
- static_assert(Layout<Int64>::Alignment() == 8, "");
- static_assert(Layout<Aligned<int8_t, 64>>::Alignment() == 64, "");
- static_assert(Layout<int8_t, int32_t, Int64>::Alignment() == 8, "");
- static_assert(Layout<int8_t, Int64, int32_t>::Alignment() == 8, "");
- static_assert(Layout<int32_t, int8_t, Int64>::Alignment() == 8, "");
- static_assert(Layout<int32_t, Int64, int8_t>::Alignment() == 8, "");
- static_assert(Layout<Int64, int8_t, int32_t>::Alignment() == 8, "");
- static_assert(Layout<Int64, int32_t, int8_t>::Alignment() == 8, "");
-}
-
-TEST(Layout, ConstexprPartial) {
- constexpr size_t M = alignof(max_align_t);
- constexpr Layout<unsigned char, Aligned<unsigned char, 2 * M>> x(1, 3);
- static_assert(x.Partial(1).template Offset<1>() == 2 * M, "");
-}
-// [from, to)
-struct Region {
- size_t from;
- size_t to;
-};
-
-void ExpectRegionPoisoned(const unsigned char* p, size_t n, bool poisoned) {
-#ifdef ABSL_HAVE_ADDRESS_SANITIZER
- for (size_t i = 0; i != n; ++i) {
- EXPECT_EQ(poisoned, __asan_address_is_poisoned(p + i));
- }
-#endif
-}
-
-template <size_t N>
-void ExpectPoisoned(const unsigned char (&buf)[N],
- std::initializer_list<Region> reg) {
- size_t prev = 0;
- for (const Region& r : reg) {
- ExpectRegionPoisoned(buf + prev, r.from - prev, false);
- ExpectRegionPoisoned(buf + r.from, r.to - r.from, true);
- prev = r.to;
- }
- ExpectRegionPoisoned(buf + prev, N - prev, false);
-}
-
-TEST(Layout, PoisonPadding) {
- using L = Layout<int8_t, Int64, int32_t, Int128>;
-
- constexpr size_t n = L::Partial(1, 2, 3, 4).AllocSize();
- {
- constexpr auto x = L::Partial();
- alignas(max_align_t) const unsigned char c[n] = {};
- x.PoisonPadding(c);
- EXPECT_EQ(x.Slices(c), x.Slices(c));
- ExpectPoisoned(c, {});
- }
- {
- constexpr auto x = L::Partial(1);
- alignas(max_align_t) const unsigned char c[n] = {};
- x.PoisonPadding(c);
- EXPECT_EQ(x.Slices(c), x.Slices(c));
- ExpectPoisoned(c, {{1, 8}});
- }
- {
- constexpr auto x = L::Partial(1, 2);
- alignas(max_align_t) const unsigned char c[n] = {};
- x.PoisonPadding(c);
- EXPECT_EQ(x.Slices(c), x.Slices(c));
- ExpectPoisoned(c, {{1, 8}});
- }
- {
- constexpr auto x = L::Partial(1, 2, 3);
- alignas(max_align_t) const unsigned char c[n] = {};
- x.PoisonPadding(c);
- EXPECT_EQ(x.Slices(c), x.Slices(c));
- ExpectPoisoned(c, {{1, 8}, {36, 40}});
- }
- {
- constexpr auto x = L::Partial(1, 2, 3, 4);
- alignas(max_align_t) const unsigned char c[n] = {};
- x.PoisonPadding(c);
- EXPECT_EQ(x.Slices(c), x.Slices(c));
- ExpectPoisoned(c, {{1, 8}, {36, 40}});
- }
- {
- constexpr L x(1, 2, 3, 4);
- alignas(max_align_t) const unsigned char c[n] = {};
- x.PoisonPadding(c);
- EXPECT_EQ(x.Slices(c), x.Slices(c));
- ExpectPoisoned(c, {{1, 8}, {36, 40}});
- }
-}
-
-TEST(Layout, DebugString) {
- {
- constexpr auto x = Layout<int8_t, int32_t, int8_t, Int128>::Partial();
- EXPECT_EQ("@0<signed char>(1)", x.DebugString());
- }
- {
- constexpr auto x = Layout<int8_t, int32_t, int8_t, Int128>::Partial(1);
- EXPECT_EQ("@0<signed char>(1)[1]; @4<int>(4)", x.DebugString());
- }
- {
- constexpr auto x = Layout<int8_t, int32_t, int8_t, Int128>::Partial(1, 2);
- EXPECT_EQ("@0<signed char>(1)[1]; @4<int>(4)[2]; @12<signed char>(1)",
- x.DebugString());
- }
- {
- constexpr auto x =
- Layout<int8_t, int32_t, int8_t, Int128>::Partial(1, 2, 3);
- EXPECT_EQ(
- "@0<signed char>(1)[1]; @4<int>(4)[2]; @12<signed char>(1)[3]; "
- "@16" +
- Int128::Name() + "(16)",
- x.DebugString());
- }
- {
- constexpr auto x =
- Layout<int8_t, int32_t, int8_t, Int128>::Partial(1, 2, 3, 4);
- EXPECT_EQ(
- "@0<signed char>(1)[1]; @4<int>(4)[2]; @12<signed char>(1)[3]; "
- "@16" +
- Int128::Name() + "(16)[4]",
- x.DebugString());
- }
- {
- constexpr Layout<int8_t, int32_t, int8_t, Int128> x(1, 2, 3, 4);
- EXPECT_EQ(
- "@0<signed char>(1)[1]; @4<int>(4)[2]; @12<signed char>(1)[3]; "
- "@16" +
- Int128::Name() + "(16)[4]",
- x.DebugString());
- }
-}
-
-TEST(Layout, CharTypes) {
- constexpr Layout<int32_t> x(1);
- alignas(max_align_t) char c[x.AllocSize()] = {};
- alignas(max_align_t) unsigned char uc[x.AllocSize()] = {};
- alignas(max_align_t) signed char sc[x.AllocSize()] = {};
- alignas(max_align_t) const char cc[x.AllocSize()] = {};
- alignas(max_align_t) const unsigned char cuc[x.AllocSize()] = {};
- alignas(max_align_t) const signed char csc[x.AllocSize()] = {};
-
- Type<int32_t*>(x.Pointer<0>(c));
- Type<int32_t*>(x.Pointer<0>(uc));
- Type<int32_t*>(x.Pointer<0>(sc));
- Type<const int32_t*>(x.Pointer<0>(cc));
- Type<const int32_t*>(x.Pointer<0>(cuc));
- Type<const int32_t*>(x.Pointer<0>(csc));
-
- Type<int32_t*>(x.Pointer<int32_t>(c));
- Type<int32_t*>(x.Pointer<int32_t>(uc));
- Type<int32_t*>(x.Pointer<int32_t>(sc));
- Type<const int32_t*>(x.Pointer<int32_t>(cc));
- Type<const int32_t*>(x.Pointer<int32_t>(cuc));
- Type<const int32_t*>(x.Pointer<int32_t>(csc));
-
- Type<std::tuple<int32_t*>>(x.Pointers(c));
- Type<std::tuple<int32_t*>>(x.Pointers(uc));
- Type<std::tuple<int32_t*>>(x.Pointers(sc));
- Type<std::tuple<const int32_t*>>(x.Pointers(cc));
- Type<std::tuple<const int32_t*>>(x.Pointers(cuc));
- Type<std::tuple<const int32_t*>>(x.Pointers(csc));
-
- Type<Span<int32_t>>(x.Slice<0>(c));
- Type<Span<int32_t>>(x.Slice<0>(uc));
- Type<Span<int32_t>>(x.Slice<0>(sc));
- Type<Span<const int32_t>>(x.Slice<0>(cc));
- Type<Span<const int32_t>>(x.Slice<0>(cuc));
- Type<Span<const int32_t>>(x.Slice<0>(csc));
-
- Type<std::tuple<Span<int32_t>>>(x.Slices(c));
- Type<std::tuple<Span<int32_t>>>(x.Slices(uc));
- Type<std::tuple<Span<int32_t>>>(x.Slices(sc));
- Type<std::tuple<Span<const int32_t>>>(x.Slices(cc));
- Type<std::tuple<Span<const int32_t>>>(x.Slices(cuc));
- Type<std::tuple<Span<const int32_t>>>(x.Slices(csc));
-}
-
-TEST(Layout, ConstElementType) {
- constexpr Layout<const int32_t> x(1);
- alignas(int32_t) char c[x.AllocSize()] = {};
- const char* cc = c;
- const int32_t* p = reinterpret_cast<const int32_t*>(cc);
-
- EXPECT_EQ(alignof(int32_t), x.Alignment());
-
- EXPECT_EQ(0, x.Offset<0>());
- EXPECT_EQ(0, x.Offset<const int32_t>());
-
- EXPECT_THAT(x.Offsets(), ElementsAre(0));
-
- EXPECT_EQ(1, x.Size<0>());
- EXPECT_EQ(1, x.Size<const int32_t>());
-
- EXPECT_THAT(x.Sizes(), ElementsAre(1));
-
- EXPECT_EQ(sizeof(int32_t), x.AllocSize());
-
- EXPECT_EQ(p, Type<const int32_t*>(x.Pointer<0>(c)));
- EXPECT_EQ(p, Type<const int32_t*>(x.Pointer<0>(cc)));
-
- EXPECT_EQ(p, Type<const int32_t*>(x.Pointer<const int32_t>(c)));
- EXPECT_EQ(p, Type<const int32_t*>(x.Pointer<const int32_t>(cc)));
-
- EXPECT_THAT(Type<std::tuple<const int32_t*>>(x.Pointers(c)), Tuple(p));
- EXPECT_THAT(Type<std::tuple<const int32_t*>>(x.Pointers(cc)), Tuple(p));
-
- EXPECT_THAT(Type<Span<const int32_t>>(x.Slice<0>(c)),
- IsSameSlice(Span<const int32_t>(p, 1)));
- EXPECT_THAT(Type<Span<const int32_t>>(x.Slice<0>(cc)),
- IsSameSlice(Span<const int32_t>(p, 1)));
-
- EXPECT_THAT(Type<Span<const int32_t>>(x.Slice<const int32_t>(c)),
- IsSameSlice(Span<const int32_t>(p, 1)));
- EXPECT_THAT(Type<Span<const int32_t>>(x.Slice<const int32_t>(cc)),
- IsSameSlice(Span<const int32_t>(p, 1)));
-
- EXPECT_THAT(Type<std::tuple<Span<const int32_t>>>(x.Slices(c)),
- Tuple(IsSameSlice(Span<const int32_t>(p, 1))));
- EXPECT_THAT(Type<std::tuple<Span<const int32_t>>>(x.Slices(cc)),
- Tuple(IsSameSlice(Span<const int32_t>(p, 1))));
-}
-
-namespace example {
-
-// Immutable move-only string with sizeof equal to sizeof(void*). The string
-// size and the characters are kept in the same heap allocation.
-class CompactString {
- public:
- CompactString(const char* s = "") { // NOLINT
- const size_t size = strlen(s);
- // size_t[1], followed by char[size + 1].
- // This statement doesn't allocate memory.
- const L layout(1, size + 1);
- // AllocSize() tells us how much memory we need to allocate for all our
- // data.
- p_.reset(new unsigned char[layout.AllocSize()]);
- // If running under ASAN, mark the padding bytes, if any, to catch memory
- // errors.
- layout.PoisonPadding(p_.get());
- // Store the size in the allocation.
- // Pointer<size_t>() is a synonym for Pointer<0>().
- *layout.Pointer<size_t>(p_.get()) = size;
- // Store the characters in the allocation.
- memcpy(layout.Pointer<char>(p_.get()), s, size + 1);
- }
-
- size_t size() const {
- // Equivalent to reinterpret_cast<size_t&>(*p).
- return *L::Partial().Pointer<size_t>(p_.get());
- }
-
- const char* c_str() const {
- // Equivalent to reinterpret_cast<char*>(p.get() + sizeof(size_t)).
- // The argument in Partial(1) specifies that we have size_t[1] in front of
- // the characters.
- return L::Partial(1).Pointer<char>(p_.get());
- }
-
- private:
- // Our heap allocation contains a size_t followed by an array of chars.
- using L = Layout<size_t, char>;
- std::unique_ptr<unsigned char[]> p_;
-};
-
-TEST(CompactString, Works) {
- CompactString s = "hello";
- EXPECT_EQ(5, s.size());
- EXPECT_STREQ("hello", s.c_str());
-}
-
-} // namespace example
-
-} // namespace
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/container/internal/node_slot_policy.h b/third_party/abseil-cpp/absl/container/internal/node_slot_policy.h
deleted file mode 100644
index baba574..0000000
--- a/third_party/abseil-cpp/absl/container/internal/node_slot_policy.h
+++ /dev/null
@@ -1,92 +0,0 @@
-// Copyright 2018 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.
-//
-// Adapts a policy for nodes.
-//
-// The node policy should model:
-//
-// struct Policy {
-// // Returns a new node allocated and constructed using the allocator, using
-// // the specified arguments.
-// template <class Alloc, class... Args>
-// value_type* new_element(Alloc* alloc, Args&&... args) const;
-//
-// // Destroys and deallocates node using the allocator.
-// template <class Alloc>
-// void delete_element(Alloc* alloc, value_type* node) const;
-// };
-//
-// It may also optionally define `value()` and `apply()`. For documentation on
-// these, see hash_policy_traits.h.
-
-#ifndef ABSL_CONTAINER_INTERNAL_NODE_SLOT_POLICY_H_
-#define ABSL_CONTAINER_INTERNAL_NODE_SLOT_POLICY_H_
-
-#include <cassert>
-#include <cstddef>
-#include <memory>
-#include <type_traits>
-#include <utility>
-
-#include "absl/base/config.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-
-template <class Reference, class Policy>
-struct node_slot_policy {
- static_assert(std::is_lvalue_reference<Reference>::value, "");
-
- using slot_type = typename std::remove_cv<
- typename std::remove_reference<Reference>::type>::type*;
-
- template <class Alloc, class... Args>
- static void construct(Alloc* alloc, slot_type* slot, Args&&... args) {
- *slot = Policy::new_element(alloc, std::forward<Args>(args)...);
- }
-
- template <class Alloc>
- static void destroy(Alloc* alloc, slot_type* slot) {
- Policy::delete_element(alloc, *slot);
- }
-
- template <class Alloc>
- static void transfer(Alloc*, slot_type* new_slot, slot_type* old_slot) {
- *new_slot = *old_slot;
- }
-
- static size_t space_used(const slot_type* slot) {
- if (slot == nullptr) return Policy::element_space_used(nullptr);
- return Policy::element_space_used(*slot);
- }
-
- static Reference element(slot_type* slot) { return **slot; }
-
- template <class T, class P = Policy>
- static auto value(T* elem) -> decltype(P::value(elem)) {
- return P::value(elem);
- }
-
- template <class... Ts, class P = Policy>
- static auto apply(Ts&&... ts) -> decltype(P::apply(std::forward<Ts>(ts)...)) {
- return P::apply(std::forward<Ts>(ts)...);
- }
-};
-
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_INTERNAL_NODE_SLOT_POLICY_H_
diff --git a/third_party/abseil-cpp/absl/container/internal/node_slot_policy_test.cc b/third_party/abseil-cpp/absl/container/internal/node_slot_policy_test.cc
deleted file mode 100644
index 51b7467..0000000
--- a/third_party/abseil-cpp/absl/container/internal/node_slot_policy_test.cc
+++ /dev/null
@@ -1,69 +0,0 @@
-// Copyright 2018 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/container/internal/node_slot_policy.h"
-
-#include <memory>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/container/internal/hash_policy_traits.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-namespace {
-
-using ::testing::Pointee;
-
-struct Policy : node_slot_policy<int&, Policy> {
- using key_type = int;
- using init_type = int;
-
- template <class Alloc>
- static int* new_element(Alloc* alloc, int value) {
- return new int(value);
- }
-
- template <class Alloc>
- static void delete_element(Alloc* alloc, int* elem) {
- delete elem;
- }
-};
-
-using NodePolicy = hash_policy_traits<Policy>;
-
-struct NodeTest : ::testing::Test {
- std::allocator<int> alloc;
- int n = 53;
- int* a = &n;
-};
-
-TEST_F(NodeTest, ConstructDestroy) {
- NodePolicy::construct(&alloc, &a, 42);
- EXPECT_THAT(a, Pointee(42));
- NodePolicy::destroy(&alloc, &a);
-}
-
-TEST_F(NodeTest, transfer) {
- int s = 42;
- int* b = &s;
- NodePolicy::transfer(&alloc, &a, &b);
- EXPECT_EQ(&s, a);
-}
-
-} // namespace
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/container/internal/raw_hash_map.h b/third_party/abseil-cpp/absl/container/internal/raw_hash_map.h
deleted file mode 100644
index c7df2ef..0000000
--- a/third_party/abseil-cpp/absl/container/internal/raw_hash_map.h
+++ /dev/null
@@ -1,198 +0,0 @@
-// Copyright 2018 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_CONTAINER_INTERNAL_RAW_HASH_MAP_H_
-#define ABSL_CONTAINER_INTERNAL_RAW_HASH_MAP_H_
-
-#include <tuple>
-#include <type_traits>
-#include <utility>
-
-#include "absl/base/internal/throw_delegate.h"
-#include "absl/container/internal/container_memory.h"
-#include "absl/container/internal/raw_hash_set.h" // IWYU pragma: export
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-
-template <class Policy, class Hash, class Eq, class Alloc>
-class raw_hash_map : public raw_hash_set<Policy, Hash, Eq, Alloc> {
- // P is Policy. It's passed as a template argument to support maps that have
- // incomplete types as values, as in unordered_map<K, IncompleteType>.
- // MappedReference<> may be a non-reference type.
- template <class P>
- using MappedReference = decltype(P::value(
- std::addressof(std::declval<typename raw_hash_map::reference>())));
-
- // MappedConstReference<> may be a non-reference type.
- template <class P>
- using MappedConstReference = decltype(P::value(
- std::addressof(std::declval<typename raw_hash_map::const_reference>())));
-
- using KeyArgImpl =
- KeyArg<IsTransparent<Eq>::value && IsTransparent<Hash>::value>;
-
- public:
- using key_type = typename Policy::key_type;
- using mapped_type = typename Policy::mapped_type;
- template <class K>
- using key_arg = typename KeyArgImpl::template type<K, key_type>;
-
- static_assert(!std::is_reference<key_type>::value, "");
-
- // TODO(b/187807849): Evaluate whether to support reference mapped_type and
- // remove this assertion if/when it is supported.
- static_assert(!std::is_reference<mapped_type>::value, "");
-
- using iterator = typename raw_hash_map::raw_hash_set::iterator;
- using const_iterator = typename raw_hash_map::raw_hash_set::const_iterator;
-
- raw_hash_map() {}
- using raw_hash_map::raw_hash_set::raw_hash_set;
-
- // The last two template parameters ensure that both arguments are rvalues
- // (lvalue arguments are handled by the overloads below). This is necessary
- // for supporting bitfield arguments.
- //
- // union { int n : 1; };
- // flat_hash_map<int, int> m;
- // m.insert_or_assign(n, n);
- template <class K = key_type, class V = mapped_type, K* = nullptr,
- V* = nullptr>
- std::pair<iterator, bool> insert_or_assign(key_arg<K>&& k, V&& v) {
- return insert_or_assign_impl(std::forward<K>(k), std::forward<V>(v));
- }
-
- template <class K = key_type, class V = mapped_type, K* = nullptr>
- std::pair<iterator, bool> insert_or_assign(key_arg<K>&& k, const V& v) {
- return insert_or_assign_impl(std::forward<K>(k), v);
- }
-
- template <class K = key_type, class V = mapped_type, V* = nullptr>
- std::pair<iterator, bool> insert_or_assign(const key_arg<K>& k, V&& v) {
- return insert_or_assign_impl(k, std::forward<V>(v));
- }
-
- template <class K = key_type, class V = mapped_type>
- std::pair<iterator, bool> insert_or_assign(const key_arg<K>& k, const V& v) {
- return insert_or_assign_impl(k, v);
- }
-
- template <class K = key_type, class V = mapped_type, K* = nullptr,
- V* = nullptr>
- iterator insert_or_assign(const_iterator, key_arg<K>&& k, V&& v) {
- return insert_or_assign(std::forward<K>(k), std::forward<V>(v)).first;
- }
-
- template <class K = key_type, class V = mapped_type, K* = nullptr>
- iterator insert_or_assign(const_iterator, key_arg<K>&& k, const V& v) {
- return insert_or_assign(std::forward<K>(k), v).first;
- }
-
- template <class K = key_type, class V = mapped_type, V* = nullptr>
- iterator insert_or_assign(const_iterator, const key_arg<K>& k, V&& v) {
- return insert_or_assign(k, std::forward<V>(v)).first;
- }
-
- template <class K = key_type, class V = mapped_type>
- iterator insert_or_assign(const_iterator, const key_arg<K>& k, const V& v) {
- return insert_or_assign(k, v).first;
- }
-
- // All `try_emplace()` overloads make the same guarantees regarding rvalue
- // arguments as `std::unordered_map::try_emplace()`, namely that these
- // functions will not move from rvalue arguments if insertions do not happen.
- template <class K = key_type, class... Args,
- typename std::enable_if<
- !std::is_convertible<K, const_iterator>::value, int>::type = 0,
- K* = nullptr>
- std::pair<iterator, bool> try_emplace(key_arg<K>&& k, Args&&... args) {
- return try_emplace_impl(std::forward<K>(k), std::forward<Args>(args)...);
- }
-
- template <class K = key_type, class... Args,
- typename std::enable_if<
- !std::is_convertible<K, const_iterator>::value, int>::type = 0>
- std::pair<iterator, bool> try_emplace(const key_arg<K>& k, Args&&... args) {
- return try_emplace_impl(k, std::forward<Args>(args)...);
- }
-
- template <class K = key_type, class... Args, K* = nullptr>
- iterator try_emplace(const_iterator, key_arg<K>&& k, Args&&... args) {
- return try_emplace(std::forward<K>(k), std::forward<Args>(args)...).first;
- }
-
- template <class K = key_type, class... Args>
- iterator try_emplace(const_iterator, const key_arg<K>& k, Args&&... args) {
- return try_emplace(k, std::forward<Args>(args)...).first;
- }
-
- template <class K = key_type, class P = Policy>
- MappedReference<P> at(const key_arg<K>& key) {
- auto it = this->find(key);
- if (it == this->end()) {
- base_internal::ThrowStdOutOfRange(
- "absl::container_internal::raw_hash_map<>::at");
- }
- return Policy::value(&*it);
- }
-
- template <class K = key_type, class P = Policy>
- MappedConstReference<P> at(const key_arg<K>& key) const {
- auto it = this->find(key);
- if (it == this->end()) {
- base_internal::ThrowStdOutOfRange(
- "absl::container_internal::raw_hash_map<>::at");
- }
- return Policy::value(&*it);
- }
-
- template <class K = key_type, class P = Policy, K* = nullptr>
- MappedReference<P> operator[](key_arg<K>&& key) {
- return Policy::value(&*try_emplace(std::forward<K>(key)).first);
- }
-
- template <class K = key_type, class P = Policy>
- MappedReference<P> operator[](const key_arg<K>& key) {
- return Policy::value(&*try_emplace(key).first);
- }
-
- private:
- template <class K, class V>
- std::pair<iterator, bool> insert_or_assign_impl(K&& k, V&& v) {
- auto res = this->find_or_prepare_insert(k);
- if (res.second)
- this->emplace_at(res.first, std::forward<K>(k), std::forward<V>(v));
- else
- Policy::value(&*this->iterator_at(res.first)) = std::forward<V>(v);
- return {this->iterator_at(res.first), res.second};
- }
-
- template <class K = key_type, class... Args>
- std::pair<iterator, bool> try_emplace_impl(K&& k, Args&&... args) {
- auto res = this->find_or_prepare_insert(k);
- if (res.second)
- this->emplace_at(res.first, std::piecewise_construct,
- std::forward_as_tuple(std::forward<K>(k)),
- std::forward_as_tuple(std::forward<Args>(args)...));
- return {this->iterator_at(res.first), res.second};
- }
-};
-
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_INTERNAL_RAW_HASH_MAP_H_
diff --git a/third_party/abseil-cpp/absl/container/internal/raw_hash_set.cc b/third_party/abseil-cpp/absl/container/internal/raw_hash_set.cc
deleted file mode 100644
index c63a2e0..0000000
--- a/third_party/abseil-cpp/absl/container/internal/raw_hash_set.cc
+++ /dev/null
@@ -1,71 +0,0 @@
-// Copyright 2018 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/container/internal/raw_hash_set.h"
-
-#include <atomic>
-#include <cstddef>
-
-#include "absl/base/config.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-
-// A single block of empty control bytes for tables without any slots allocated.
-// This enables removing a branch in the hot path of find().
-alignas(16) ABSL_CONST_INIT ABSL_DLL const ctrl_t kEmptyGroup[16] = {
- ctrl_t::kSentinel, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty,
- ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty,
- ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty,
- ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty};
-
-#ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL
-constexpr size_t Group::kWidth;
-#endif
-
-// Returns "random" seed.
-inline size_t RandomSeed() {
-#ifdef ABSL_HAVE_THREAD_LOCAL
- static thread_local size_t counter = 0;
- size_t value = ++counter;
-#else // ABSL_HAVE_THREAD_LOCAL
- static std::atomic<size_t> counter(0);
- size_t value = counter.fetch_add(1, std::memory_order_relaxed);
-#endif // ABSL_HAVE_THREAD_LOCAL
- return value ^ static_cast<size_t>(reinterpret_cast<uintptr_t>(&counter));
-}
-
-bool ShouldInsertBackwards(size_t hash, const ctrl_t* ctrl) {
- // To avoid problems with weak hashes and single bit tests, we use % 13.
- // TODO(kfm,sbenza): revisit after we do unconditional mixing
- return (H1(hash, ctrl) ^ RandomSeed()) % 13 > 6;
-}
-
-void ConvertDeletedToEmptyAndFullToDeleted(ctrl_t* ctrl, size_t capacity) {
- assert(ctrl[capacity] == ctrl_t::kSentinel);
- assert(IsValidCapacity(capacity));
- for (ctrl_t* pos = ctrl; pos < ctrl + capacity; pos += Group::kWidth) {
- Group{pos}.ConvertSpecialToEmptyAndFullToDeleted(pos);
- }
- // Copy the cloned ctrl bytes.
- std::memcpy(ctrl + capacity + 1, ctrl, NumClonedBytes());
- ctrl[capacity] = ctrl_t::kSentinel;
-}
-// Extern template instantiotion for inline function.
-template FindInfo find_first_non_full(const ctrl_t*, size_t, size_t);
-
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/container/internal/raw_hash_set.h b/third_party/abseil-cpp/absl/container/internal/raw_hash_set.h
deleted file mode 100644
index 676cebd..0000000
--- a/third_party/abseil-cpp/absl/container/internal/raw_hash_set.h
+++ /dev/null
@@ -1,2372 +0,0 @@
-// Copyright 2018 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.
-//
-// An open-addressing
-// hashtable with quadratic probing.
-//
-// This is a low level hashtable on top of which different interfaces can be
-// implemented, like flat_hash_set, node_hash_set, string_hash_set, etc.
-//
-// The table interface is similar to that of std::unordered_set. Notable
-// differences are that most member functions support heterogeneous keys when
-// BOTH the hash and eq functions are marked as transparent. They do so by
-// providing a typedef called `is_transparent`.
-//
-// When heterogeneous lookup is enabled, functions that take key_type act as if
-// they have an overload set like:
-//
-// iterator find(const key_type& key);
-// template <class K>
-// iterator find(const K& key);
-//
-// size_type erase(const key_type& key);
-// template <class K>
-// size_type erase(const K& key);
-//
-// std::pair<iterator, iterator> equal_range(const key_type& key);
-// template <class K>
-// std::pair<iterator, iterator> equal_range(const K& key);
-//
-// When heterogeneous lookup is disabled, only the explicit `key_type` overloads
-// exist.
-//
-// find() also supports passing the hash explicitly:
-//
-// iterator find(const key_type& key, size_t hash);
-// template <class U>
-// iterator find(const U& key, size_t hash);
-//
-// In addition the pointer to element and iterator stability guarantees are
-// weaker: all iterators and pointers are invalidated after a new element is
-// inserted.
-//
-// IMPLEMENTATION DETAILS
-//
-// # Table Layout
-//
-// A raw_hash_set's backing array consists of control bytes followed by slots
-// that may or may not contain objects.
-//
-// The layout of the backing array, for `capacity` slots, is thus, as a
-// pseudo-struct:
-//
-// struct BackingArray {
-// // Control bytes for the "real" slots.
-// ctrl_t ctrl[capacity];
-// // Always `ctrl_t::kSentinel`. This is used by iterators to find when to
-// // stop and serves no other purpose.
-// ctrl_t sentinel;
-// // A copy of the first `kWidth - 1` elements of `ctrl`. This is used so
-// // that if a probe sequence picks a value near the end of `ctrl`,
-// // `Group` will have valid control bytes to look at.
-// ctrl_t clones[kWidth - 1];
-// // The actual slot data.
-// slot_type slots[capacity];
-// };
-//
-// The length of this array is computed by `AllocSize()` below.
-//
-// Control bytes (`ctrl_t`) are bytes (collected into groups of a
-// platform-specific size) that define the state of the corresponding slot in
-// the slot array. Group manipulation is tightly optimized to be as efficient
-// as possible: SSE and friends on x86, clever bit operations on other arches.
-//
-// Group 1 Group 2 Group 3
-// +---------------+---------------+---------------+
-// | | | | | | | | | | | | | | | | | | | | | | | | |
-// +---------------+---------------+---------------+
-//
-// Each control byte is either a special value for empty slots, deleted slots
-// (sometimes called *tombstones*), and a special end-of-table marker used by
-// iterators, or, if occupied, seven bits (H2) from the hash of the value in the
-// corresponding slot.
-//
-// Storing control bytes in a separate array also has beneficial cache effects,
-// since more logical slots will fit into a cache line.
-//
-// # Hashing
-//
-// We compute two separate hashes, `H1` and `H2`, from the hash of an object.
-// `H1(hash(x))` is an index into `slots`, and essentially the starting point
-// for the probe sequence. `H2(hash(x))` is a 7-bit value used to filter out
-// objects that cannot possibly be the one we are looking for.
-//
-// # Table operations.
-//
-// The key operations are `insert`, `find`, and `erase`.
-//
-// Since `insert` and `erase` are implemented in terms of `find`, we describe
-// `find` first. To `find` a value `x`, we compute `hash(x)`. From
-// `H1(hash(x))` and the capacity, we construct a `probe_seq` that visits every
-// group of slots in some interesting order.
-//
-// We now walk through these indices. At each index, we select the entire group
-// starting with that index and extract potential candidates: occupied slots
-// with a control byte equal to `H2(hash(x))`. If we find an empty slot in the
-// group, we stop and return an error. Each candidate slot `y` is compared with
-// `x`; if `x == y`, we are done and return `&y`; otherwise we contine to the
-// next probe index. Tombstones effectively behave like full slots that never
-// match the value we're looking for.
-//
-// The `H2` bits ensure when we compare a slot to an object with `==`, we are
-// likely to have actually found the object. That is, the chance is low that
-// `==` is called and returns `false`. Thus, when we search for an object, we
-// are unlikely to call `==` many times. This likelyhood can be analyzed as
-// follows (assuming that H2 is a random enough hash function).
-//
-// Let's assume that there are `k` "wrong" objects that must be examined in a
-// probe sequence. For example, when doing a `find` on an object that is in the
-// table, `k` is the number of objects between the start of the probe sequence
-// and the final found object (not including the final found object). The
-// expected number of objects with an H2 match is then `k/128`. Measurements
-// and analysis indicate that even at high load factors, `k` is less than 32,
-// meaning that the number of "false positive" comparisons we must perform is
-// less than 1/8 per `find`.
-
-// `insert` is implemented in terms of `unchecked_insert`, which inserts a
-// value presumed to not be in the table (violating this requirement will cause
-// the table to behave erratically). Given `x` and its hash `hash(x)`, to insert
-// it, we construct a `probe_seq` once again, and use it to find the first
-// group with an unoccupied (empty *or* deleted) slot. We place `x` into the
-// first such slot in the group and mark it as full with `x`'s H2.
-//
-// To `insert`, we compose `unchecked_insert` with `find`. We compute `h(x)` and
-// perform a `find` to see if it's already present; if it is, we're done. If
-// it's not, we may decide the table is getting overcrowded (i.e. the load
-// factor is greater than 7/8 for big tables; `is_small()` tables use a max load
-// factor of 1); in this case, we allocate a bigger array, `unchecked_insert`
-// each element of the table into the new array (we know that no insertion here
-// will insert an already-present value), and discard the old backing array. At
-// this point, we may `unchecked_insert` the value `x`.
-//
-// Below, `unchecked_insert` is partly implemented by `prepare_insert`, which
-// presents a viable, initialized slot pointee to the caller.
-//
-// `erase` is implemented in terms of `erase_at`, which takes an index to a
-// slot. Given an offset, we simply create a tombstone and destroy its contents.
-// If we can prove that the slot would not appear in a probe sequence, we can
-// make the slot as empty, instead. We can prove this by observing that if a
-// group has any empty slots, it has never been full (assuming we never create
-// an empty slot in a group with no empties, which this heuristic guarantees we
-// never do) and find would stop at this group anyways (since it does not probe
-// beyond groups with empties).
-//
-// `erase` is `erase_at` composed with `find`: if we
-// have a value `x`, we can perform a `find`, and then `erase_at` the resulting
-// slot.
-//
-// To iterate, we simply traverse the array, skipping empty and deleted slots
-// and stopping when we hit a `kSentinel`.
-
-#ifndef ABSL_CONTAINER_INTERNAL_RAW_HASH_SET_H_
-#define ABSL_CONTAINER_INTERNAL_RAW_HASH_SET_H_
-
-#include <algorithm>
-#include <cmath>
-#include <cstdint>
-#include <cstring>
-#include <iterator>
-#include <limits>
-#include <memory>
-#include <tuple>
-#include <type_traits>
-#include <utility>
-
-#include "absl/base/config.h"
-#include "absl/base/internal/endian.h"
-#include "absl/base/internal/prefetch.h"
-#include "absl/base/optimization.h"
-#include "absl/base/port.h"
-#include "absl/container/internal/common.h"
-#include "absl/container/internal/compressed_tuple.h"
-#include "absl/container/internal/container_memory.h"
-#include "absl/container/internal/hash_policy_traits.h"
-#include "absl/container/internal/hashtable_debug_hooks.h"
-#include "absl/container/internal/hashtablez_sampler.h"
-#include "absl/memory/memory.h"
-#include "absl/meta/type_traits.h"
-#include "absl/numeric/bits.h"
-#include "absl/utility/utility.h"
-
-#ifdef ABSL_INTERNAL_HAVE_SSE2
-#include <emmintrin.h>
-#endif
-
-#ifdef ABSL_INTERNAL_HAVE_SSSE3
-#include <tmmintrin.h>
-#endif
-
-#ifdef _MSC_VER
-#include <intrin.h>
-#endif
-
-#ifdef ABSL_INTERNAL_HAVE_ARM_NEON
-#include <arm_neon.h>
-#endif
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-
-template <typename AllocType>
-void SwapAlloc(AllocType& lhs, AllocType& rhs,
- std::true_type /* propagate_on_container_swap */) {
- using std::swap;
- swap(lhs, rhs);
-}
-template <typename AllocType>
-void SwapAlloc(AllocType& /*lhs*/, AllocType& /*rhs*/,
- std::false_type /* propagate_on_container_swap */) {}
-
-// The state for a probe sequence.
-//
-// Currently, the sequence is a triangular progression of the form
-//
-// p(i) := Width * (i^2 + i)/2 + hash (mod mask + 1)
-//
-// The use of `Width` ensures that each probe step does not overlap groups;
-// the sequence effectively outputs the addresses of *groups* (although not
-// necessarily aligned to any boundary). The `Group` machinery allows us
-// to check an entire group with minimal branching.
-//
-// Wrapping around at `mask + 1` is important, but not for the obvious reason.
-// As described above, the first few entries of the control byte array
-// are mirrored at the end of the array, which `Group` will find and use
-// for selecting candidates. However, when those candidates' slots are
-// actually inspected, there are no corresponding slots for the cloned bytes,
-// so we need to make sure we've treated those offsets as "wrapping around".
-//
-// It turns out that this probe sequence visits every group exactly once if the
-// number of groups is a power of two, since (i^2+i)/2 is a bijection in
-// Z/(2^m). See https://en.wikipedia.org/wiki/Quadratic_probing
-template <size_t Width>
-class probe_seq {
- public:
- // Creates a new probe sequence using `hash` as the initial value of the
- // sequence and `mask` (usually the capacity of the table) as the mask to
- // apply to each value in the progression.
- probe_seq(size_t hash, size_t mask) {
- assert(((mask + 1) & mask) == 0 && "not a mask");
- mask_ = mask;
- offset_ = hash & mask_;
- }
-
- // The offset within the table, i.e., the value `p(i)` above.
- size_t offset() const { return offset_; }
- size_t offset(size_t i) const { return (offset_ + i) & mask_; }
-
- void next() {
- index_ += Width;
- offset_ += index_;
- offset_ &= mask_;
- }
- // 0-based probe index, a multiple of `Width`.
- size_t index() const { return index_; }
-
- private:
- size_t mask_;
- size_t offset_;
- size_t index_ = 0;
-};
-
-template <class ContainerKey, class Hash, class Eq>
-struct RequireUsableKey {
- template <class PassedKey, class... Args>
- std::pair<
- decltype(std::declval<const Hash&>()(std::declval<const PassedKey&>())),
- decltype(std::declval<const Eq&>()(std::declval<const ContainerKey&>(),
- std::declval<const PassedKey&>()))>*
- operator()(const PassedKey&, const Args&...) const;
-};
-
-template <class E, class Policy, class Hash, class Eq, class... Ts>
-struct IsDecomposable : std::false_type {};
-
-template <class Policy, class Hash, class Eq, class... Ts>
-struct IsDecomposable<
- absl::void_t<decltype(Policy::apply(
- RequireUsableKey<typename Policy::key_type, Hash, Eq>(),
- std::declval<Ts>()...))>,
- Policy, Hash, Eq, Ts...> : std::true_type {};
-
-// TODO(alkis): Switch to std::is_nothrow_swappable when gcc/clang supports it.
-template <class T>
-constexpr bool IsNoThrowSwappable(std::true_type = {} /* is_swappable */) {
- using std::swap;
- return noexcept(swap(std::declval<T&>(), std::declval<T&>()));
-}
-template <class T>
-constexpr bool IsNoThrowSwappable(std::false_type /* is_swappable */) {
- return false;
-}
-
-template <typename T>
-uint32_t TrailingZeros(T x) {
- ABSL_ASSUME(x != 0);
- return static_cast<uint32_t>(countr_zero(x));
-}
-
-// An abstract bitmask, such as that emitted by a SIMD instruction.
-//
-// Specifically, this type implements a simple bitset whose representation is
-// controlled by `SignificantBits` and `Shift`. `SignificantBits` is the number
-// of abstract bits in the bitset, while `Shift` is the log-base-two of the
-// width of an abstract bit in the representation.
-// This mask provides operations for any number of real bits set in an abstract
-// bit. To add iteration on top of that, implementation must guarantee no more
-// than one real bit is set in an abstract bit.
-template <class T, int SignificantBits, int Shift = 0>
-class NonIterableBitMask {
- public:
- explicit NonIterableBitMask(T mask) : mask_(mask) {}
-
- explicit operator bool() const { return this->mask_ != 0; }
-
- // Returns the index of the lowest *abstract* bit set in `self`.
- uint32_t LowestBitSet() const {
- return container_internal::TrailingZeros(mask_) >> Shift;
- }
-
- // Returns the index of the highest *abstract* bit set in `self`.
- uint32_t HighestBitSet() const {
- return static_cast<uint32_t>((bit_width(mask_) - 1) >> Shift);
- }
-
- // Return the number of trailing zero *abstract* bits.
- uint32_t TrailingZeros() const {
- return container_internal::TrailingZeros(mask_) >> Shift;
- }
-
- // Return the number of leading zero *abstract* bits.
- uint32_t LeadingZeros() const {
- constexpr int total_significant_bits = SignificantBits << Shift;
- constexpr int extra_bits = sizeof(T) * 8 - total_significant_bits;
- return static_cast<uint32_t>(countl_zero(mask_ << extra_bits)) >> Shift;
- }
-
- T mask_;
-};
-
-// Mask that can be iterable
-//
-// For example, when `SignificantBits` is 16 and `Shift` is zero, this is just
-// an ordinary 16-bit bitset occupying the low 16 bits of `mask`. When
-// `SignificantBits` is 8 and `Shift` is 3, abstract bits are represented as
-// the bytes `0x00` and `0x80`, and it occupies all 64 bits of the bitmask.
-//
-// For example:
-// for (int i : BitMask<uint32_t, 16>(0b101)) -> yields 0, 2
-// for (int i : BitMask<uint64_t, 8, 3>(0x0000000080800000)) -> yields 2, 3
-template <class T, int SignificantBits, int Shift = 0>
-class BitMask : public NonIterableBitMask<T, SignificantBits, Shift> {
- using Base = NonIterableBitMask<T, SignificantBits, Shift>;
- static_assert(std::is_unsigned<T>::value, "");
- static_assert(Shift == 0 || Shift == 3, "");
-
- public:
- explicit BitMask(T mask) : Base(mask) {}
- // BitMask is an iterator over the indices of its abstract bits.
- using value_type = int;
- using iterator = BitMask;
- using const_iterator = BitMask;
-
- BitMask& operator++() {
- this->mask_ &= (this->mask_ - 1);
- return *this;
- }
-
- uint32_t operator*() const { return Base::LowestBitSet(); }
-
- BitMask begin() const { return *this; }
- BitMask end() const { return BitMask(0); }
-
- private:
- friend bool operator==(const BitMask& a, const BitMask& b) {
- return a.mask_ == b.mask_;
- }
- friend bool operator!=(const BitMask& a, const BitMask& b) {
- return a.mask_ != b.mask_;
- }
-};
-
-using h2_t = uint8_t;
-
-// The values here are selected for maximum performance. See the static asserts
-// below for details.
-
-// A `ctrl_t` is a single control byte, which can have one of four
-// states: empty, deleted, full (which has an associated seven-bit h2_t value)
-// and the sentinel. They have the following bit patterns:
-//
-// empty: 1 0 0 0 0 0 0 0
-// deleted: 1 1 1 1 1 1 1 0
-// full: 0 h h h h h h h // h represents the hash bits.
-// sentinel: 1 1 1 1 1 1 1 1
-//
-// These values are specifically tuned for SSE-flavored SIMD.
-// The static_asserts below detail the source of these choices.
-//
-// We use an enum class so that when strict aliasing is enabled, the compiler
-// knows ctrl_t doesn't alias other types.
-enum class ctrl_t : int8_t {
- kEmpty = -128, // 0b10000000
- kDeleted = -2, // 0b11111110
- kSentinel = -1, // 0b11111111
-};
-static_assert(
- (static_cast<int8_t>(ctrl_t::kEmpty) &
- static_cast<int8_t>(ctrl_t::kDeleted) &
- static_cast<int8_t>(ctrl_t::kSentinel) & 0x80) != 0,
- "Special markers need to have the MSB to make checking for them efficient");
-static_assert(
- ctrl_t::kEmpty < ctrl_t::kSentinel && ctrl_t::kDeleted < ctrl_t::kSentinel,
- "ctrl_t::kEmpty and ctrl_t::kDeleted must be smaller than "
- "ctrl_t::kSentinel to make the SIMD test of IsEmptyOrDeleted() efficient");
-static_assert(
- ctrl_t::kSentinel == static_cast<ctrl_t>(-1),
- "ctrl_t::kSentinel must be -1 to elide loading it from memory into SIMD "
- "registers (pcmpeqd xmm, xmm)");
-static_assert(ctrl_t::kEmpty == static_cast<ctrl_t>(-128),
- "ctrl_t::kEmpty must be -128 to make the SIMD check for its "
- "existence efficient (psignb xmm, xmm)");
-static_assert(
- (~static_cast<int8_t>(ctrl_t::kEmpty) &
- ~static_cast<int8_t>(ctrl_t::kDeleted) &
- static_cast<int8_t>(ctrl_t::kSentinel) & 0x7F) != 0,
- "ctrl_t::kEmpty and ctrl_t::kDeleted must share an unset bit that is not "
- "shared by ctrl_t::kSentinel to make the scalar test for "
- "MaskEmptyOrDeleted() efficient");
-static_assert(ctrl_t::kDeleted == static_cast<ctrl_t>(-2),
- "ctrl_t::kDeleted must be -2 to make the implementation of "
- "ConvertSpecialToEmptyAndFullToDeleted efficient");
-
-ABSL_DLL extern const ctrl_t kEmptyGroup[16];
-
-// Returns a pointer to a control byte group that can be used by empty tables.
-inline ctrl_t* EmptyGroup() {
- // Const must be cast away here; no uses of this function will actually write
- // to it, because it is only used for empty tables.
- return const_cast<ctrl_t*>(kEmptyGroup);
-}
-
-// Mixes a randomly generated per-process seed with `hash` and `ctrl` to
-// randomize insertion order within groups.
-bool ShouldInsertBackwards(size_t hash, const ctrl_t* ctrl);
-
-// Returns a per-table, hash salt, which changes on resize. This gets mixed into
-// H1 to randomize iteration order per-table.
-//
-// The seed consists of the ctrl_ pointer, which adds enough entropy to ensure
-// non-determinism of iteration order in most cases.
-inline size_t PerTableSalt(const ctrl_t* ctrl) {
- // The low bits of the pointer have little or no entropy because of
- // alignment. We shift the pointer to try to use higher entropy bits. A
- // good number seems to be 12 bits, because that aligns with page size.
- return reinterpret_cast<uintptr_t>(ctrl) >> 12;
-}
-// Extracts the H1 portion of a hash: 57 bits mixed with a per-table salt.
-inline size_t H1(size_t hash, const ctrl_t* ctrl) {
- return (hash >> 7) ^ PerTableSalt(ctrl);
-}
-
-// Extracts the H2 portion of a hash: the 7 bits not used for H1.
-//
-// These are used as an occupied control byte.
-inline h2_t H2(size_t hash) { return hash & 0x7F; }
-
-// Helpers for checking the state of a control byte.
-inline bool IsEmpty(ctrl_t c) { return c == ctrl_t::kEmpty; }
-inline bool IsFull(ctrl_t c) { return c >= static_cast<ctrl_t>(0); }
-inline bool IsDeleted(ctrl_t c) { return c == ctrl_t::kDeleted; }
-inline bool IsEmptyOrDeleted(ctrl_t c) { return c < ctrl_t::kSentinel; }
-
-#ifdef ABSL_INTERNAL_HAVE_SSE2
-// Quick reference guide for intrinsics used below:
-//
-// * __m128i: An XMM (128-bit) word.
-//
-// * _mm_setzero_si128: Returns a zero vector.
-// * _mm_set1_epi8: Returns a vector with the same i8 in each lane.
-//
-// * _mm_subs_epi8: Saturating-subtracts two i8 vectors.
-// * _mm_and_si128: Ands two i128s together.
-// * _mm_or_si128: Ors two i128s together.
-// * _mm_andnot_si128: And-nots two i128s together.
-//
-// * _mm_cmpeq_epi8: Component-wise compares two i8 vectors for equality,
-// filling each lane with 0x00 or 0xff.
-// * _mm_cmpgt_epi8: Same as above, but using > rather than ==.
-//
-// * _mm_loadu_si128: Performs an unaligned load of an i128.
-// * _mm_storeu_si128: Performs an unaligned store of an i128.
-//
-// * _mm_sign_epi8: Retains, negates, or zeroes each i8 lane of the first
-// argument if the corresponding lane of the second
-// argument is positive, negative, or zero, respectively.
-// * _mm_movemask_epi8: Selects the sign bit out of each i8 lane and produces a
-// bitmask consisting of those bits.
-// * _mm_shuffle_epi8: Selects i8s from the first argument, using the low
-// four bits of each i8 lane in the second argument as
-// indices.
-
-// https://github.com/abseil/abseil-cpp/issues/209
-// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=87853
-// _mm_cmpgt_epi8 is broken under GCC with -funsigned-char
-// Work around this by using the portable implementation of Group
-// when using -funsigned-char under GCC.
-inline __m128i _mm_cmpgt_epi8_fixed(__m128i a, __m128i b) {
-#if defined(__GNUC__) && !defined(__clang__)
- if (std::is_unsigned<char>::value) {
- const __m128i mask = _mm_set1_epi8(0x80);
- const __m128i diff = _mm_subs_epi8(b, a);
- return _mm_cmpeq_epi8(_mm_and_si128(diff, mask), mask);
- }
-#endif
- return _mm_cmpgt_epi8(a, b);
-}
-
-struct GroupSse2Impl {
- static constexpr size_t kWidth = 16; // the number of slots per group
-
- explicit GroupSse2Impl(const ctrl_t* pos) {
- ctrl = _mm_loadu_si128(reinterpret_cast<const __m128i*>(pos));
- }
-
- // Returns a bitmask representing the positions of slots that match hash.
- BitMask<uint32_t, kWidth> Match(h2_t hash) const {
- auto match = _mm_set1_epi8(static_cast<char>(hash));
- return BitMask<uint32_t, kWidth>(
- static_cast<uint32_t>(_mm_movemask_epi8(_mm_cmpeq_epi8(match, ctrl))));
- }
-
- // Returns a bitmask representing the positions of empty slots.
- NonIterableBitMask<uint32_t, kWidth> MaskEmpty() const {
-#ifdef ABSL_INTERNAL_HAVE_SSSE3
- // This only works because ctrl_t::kEmpty is -128.
- return NonIterableBitMask<uint32_t, kWidth>(
- static_cast<uint32_t>(_mm_movemask_epi8(_mm_sign_epi8(ctrl, ctrl))));
-#else
- auto match = _mm_set1_epi8(static_cast<char>(ctrl_t::kEmpty));
- return NonIterableBitMask<uint32_t, kWidth>(
- static_cast<uint32_t>(_mm_movemask_epi8(_mm_cmpeq_epi8(match, ctrl))));
-#endif
- }
-
- // Returns a bitmask representing the positions of empty or deleted slots.
- NonIterableBitMask<uint32_t, kWidth> MaskEmptyOrDeleted() const {
- auto special = _mm_set1_epi8(static_cast<char>(ctrl_t::kSentinel));
- return NonIterableBitMask<uint32_t, kWidth>(static_cast<uint32_t>(
- _mm_movemask_epi8(_mm_cmpgt_epi8_fixed(special, ctrl))));
- }
-
- // Returns the number of trailing empty or deleted elements in the group.
- uint32_t CountLeadingEmptyOrDeleted() const {
- auto special = _mm_set1_epi8(static_cast<char>(ctrl_t::kSentinel));
- return TrailingZeros(static_cast<uint32_t>(
- _mm_movemask_epi8(_mm_cmpgt_epi8_fixed(special, ctrl)) + 1));
- }
-
- void ConvertSpecialToEmptyAndFullToDeleted(ctrl_t* dst) const {
- auto msbs = _mm_set1_epi8(static_cast<char>(-128));
- auto x126 = _mm_set1_epi8(126);
-#ifdef ABSL_INTERNAL_HAVE_SSSE3
- auto res = _mm_or_si128(_mm_shuffle_epi8(x126, ctrl), msbs);
-#else
- auto zero = _mm_setzero_si128();
- auto special_mask = _mm_cmpgt_epi8_fixed(zero, ctrl);
- auto res = _mm_or_si128(msbs, _mm_andnot_si128(special_mask, x126));
-#endif
- _mm_storeu_si128(reinterpret_cast<__m128i*>(dst), res);
- }
-
- __m128i ctrl;
-};
-#endif // ABSL_INTERNAL_RAW_HASH_SET_HAVE_SSE2
-
-#if defined(ABSL_INTERNAL_HAVE_ARM_NEON) && defined(ABSL_IS_LITTLE_ENDIAN)
-struct GroupAArch64Impl {
- static constexpr size_t kWidth = 8;
-
- explicit GroupAArch64Impl(const ctrl_t* pos) {
- ctrl = vld1_u8(reinterpret_cast<const uint8_t*>(pos));
- }
-
- BitMask<uint64_t, kWidth, 3> Match(h2_t hash) const {
- uint8x8_t dup = vdup_n_u8(hash);
- auto mask = vceq_u8(ctrl, dup);
- constexpr uint64_t msbs = 0x8080808080808080ULL;
- return BitMask<uint64_t, kWidth, 3>(
- vget_lane_u64(vreinterpret_u64_u8(mask), 0) & msbs);
- }
-
- NonIterableBitMask<uint64_t, kWidth, 3> MaskEmpty() const {
- uint64_t mask =
- vget_lane_u64(vreinterpret_u64_u8(vceq_s8(
- vdup_n_s8(static_cast<int8_t>(ctrl_t::kEmpty)),
- vreinterpret_s8_u8(ctrl))),
- 0);
- return NonIterableBitMask<uint64_t, kWidth, 3>(mask);
- }
-
- NonIterableBitMask<uint64_t, kWidth, 3> MaskEmptyOrDeleted() const {
- uint64_t mask =
- vget_lane_u64(vreinterpret_u64_u8(vcgt_s8(
- vdup_n_s8(static_cast<int8_t>(ctrl_t::kSentinel)),
- vreinterpret_s8_u8(ctrl))),
- 0);
- return NonIterableBitMask<uint64_t, kWidth, 3>(mask);
- }
-
- uint32_t CountLeadingEmptyOrDeleted() const {
- uint64_t mask = vget_lane_u64(vreinterpret_u64_u8(ctrl), 0);
- // ctrl | ~(ctrl >> 7) will have the lowest bit set to zero for kEmpty and
- // kDeleted. We lower all other bits and count number of trailing zeros.
- // Clang and GCC optimize countr_zero to rbit+clz without any check for 0,
- // so we should be fine.
- constexpr uint64_t bits = 0x0101010101010101ULL;
- return static_cast<uint32_t>(countr_zero((mask | ~(mask >> 7)) & bits) >>
- 3);
- }
-
- void ConvertSpecialToEmptyAndFullToDeleted(ctrl_t* dst) const {
- uint64_t mask = vget_lane_u64(vreinterpret_u64_u8(ctrl), 0);
- constexpr uint64_t msbs = 0x8080808080808080ULL;
- constexpr uint64_t lsbs = 0x0101010101010101ULL;
- auto x = mask & msbs;
- auto res = (~x + (x >> 7)) & ~lsbs;
- little_endian::Store64(dst, res);
- }
-
- uint8x8_t ctrl;
-};
-#endif // ABSL_INTERNAL_HAVE_ARM_NEON && ABSL_IS_LITTLE_ENDIAN
-
-struct GroupPortableImpl {
- static constexpr size_t kWidth = 8;
-
- explicit GroupPortableImpl(const ctrl_t* pos)
- : ctrl(little_endian::Load64(pos)) {}
-
- BitMask<uint64_t, kWidth, 3> Match(h2_t hash) const {
- // For the technique, see:
- // http://graphics.stanford.edu/~seander/bithacks.html##ValueInWord
- // (Determine if a word has a byte equal to n).
- //
- // Caveat: there are false positives but:
- // - they only occur if there is a real match
- // - they never occur on ctrl_t::kEmpty, ctrl_t::kDeleted, ctrl_t::kSentinel
- // - they will be handled gracefully by subsequent checks in code
- //
- // Example:
- // v = 0x1716151413121110
- // hash = 0x12
- // retval = (v - lsbs) & ~v & msbs = 0x0000000080800000
- constexpr uint64_t msbs = 0x8080808080808080ULL;
- constexpr uint64_t lsbs = 0x0101010101010101ULL;
- auto x = ctrl ^ (lsbs * hash);
- return BitMask<uint64_t, kWidth, 3>((x - lsbs) & ~x & msbs);
- }
-
- NonIterableBitMask<uint64_t, kWidth, 3> MaskEmpty() const {
- constexpr uint64_t msbs = 0x8080808080808080ULL;
- return NonIterableBitMask<uint64_t, kWidth, 3>((ctrl & (~ctrl << 6)) &
- msbs);
- }
-
- NonIterableBitMask<uint64_t, kWidth, 3> MaskEmptyOrDeleted() const {
- constexpr uint64_t msbs = 0x8080808080808080ULL;
- return NonIterableBitMask<uint64_t, kWidth, 3>((ctrl & (~ctrl << 7)) &
- msbs);
- }
-
- uint32_t CountLeadingEmptyOrDeleted() const {
- // ctrl | ~(ctrl >> 7) will have the lowest bit set to zero for kEmpty and
- // kDeleted. We lower all other bits and count number of trailing zeros.
- constexpr uint64_t bits = 0x0101010101010101ULL;
- return static_cast<uint32_t>(countr_zero((ctrl | ~(ctrl >> 7)) & bits) >>
- 3);
- }
-
- void ConvertSpecialToEmptyAndFullToDeleted(ctrl_t* dst) const {
- constexpr uint64_t msbs = 0x8080808080808080ULL;
- constexpr uint64_t lsbs = 0x0101010101010101ULL;
- auto x = ctrl & msbs;
- auto res = (~x + (x >> 7)) & ~lsbs;
- little_endian::Store64(dst, res);
- }
-
- uint64_t ctrl;
-};
-
-#ifdef ABSL_INTERNAL_HAVE_SSE2
-using Group = GroupSse2Impl;
-#elif defined(ABSL_INTERNAL_HAVE_ARM_NEON) && defined(ABSL_IS_LITTLE_ENDIAN)
-using Group = GroupAArch64Impl;
-#else
-using Group = GroupPortableImpl;
-#endif
-
-// Returns he number of "cloned control bytes".
-//
-// This is the number of control bytes that are present both at the beginning
-// of the control byte array and at the end, such that we can create a
-// `Group::kWidth`-width probe window starting from any control byte.
-constexpr size_t NumClonedBytes() { return Group::kWidth - 1; }
-
-template <class Policy, class Hash, class Eq, class Alloc>
-class raw_hash_set;
-
-// Returns whether `n` is a valid capacity (i.e., number of slots).
-//
-// A valid capacity is a non-zero integer `2^m - 1`.
-inline bool IsValidCapacity(size_t n) { return ((n + 1) & n) == 0 && n > 0; }
-
-// Applies the following mapping to every byte in the control array:
-// * kDeleted -> kEmpty
-// * kEmpty -> kEmpty
-// * _ -> kDeleted
-// PRECONDITION:
-// IsValidCapacity(capacity)
-// ctrl[capacity] == ctrl_t::kSentinel
-// ctrl[i] != ctrl_t::kSentinel for all i < capacity
-void ConvertDeletedToEmptyAndFullToDeleted(ctrl_t* ctrl, size_t capacity);
-
-// Converts `n` into the next valid capacity, per `IsValidCapacity`.
-inline size_t NormalizeCapacity(size_t n) {
- return n ? ~size_t{} >> countl_zero(n) : 1;
-}
-
-// General notes on capacity/growth methods below:
-// - We use 7/8th as maximum load factor. For 16-wide groups, that gives an
-// average of two empty slots per group.
-// - For (capacity+1) >= Group::kWidth, growth is 7/8*capacity.
-// - For (capacity+1) < Group::kWidth, growth == capacity. In this case, we
-// never need to probe (the whole table fits in one group) so we don't need a
-// load factor less than 1.
-
-// Given `capacity`, applies the load factor; i.e., it returns the maximum
-// number of values we should put into the table before a resizing rehash.
-inline size_t CapacityToGrowth(size_t capacity) {
- assert(IsValidCapacity(capacity));
- // `capacity*7/8`
- if (Group::kWidth == 8 && capacity == 7) {
- // x-x/8 does not work when x==7.
- return 6;
- }
- return capacity - capacity / 8;
-}
-
-// Given `growth`, "unapplies" the load factor to find how large the capacity
-// should be to stay within the load factor.
-//
-// This might not be a valid capacity and `NormalizeCapacity()` should be
-// called on this.
-inline size_t GrowthToLowerboundCapacity(size_t growth) {
- // `growth*8/7`
- if (Group::kWidth == 8 && growth == 7) {
- // x+(x-1)/7 does not work when x==7.
- return 8;
- }
- return growth + static_cast<size_t>((static_cast<int64_t>(growth) - 1) / 7);
-}
-
-template <class InputIter>
-size_t SelectBucketCountForIterRange(InputIter first, InputIter last,
- size_t bucket_count) {
- if (bucket_count != 0) {
- return bucket_count;
- }
- using InputIterCategory =
- typename std::iterator_traits<InputIter>::iterator_category;
- if (std::is_base_of<std::random_access_iterator_tag,
- InputIterCategory>::value) {
- return GrowthToLowerboundCapacity(
- static_cast<size_t>(std::distance(first, last)));
- }
- return 0;
-}
-
-#define ABSL_INTERNAL_ASSERT_IS_FULL(ctrl, operation) \
- do { \
- ABSL_HARDENING_ASSERT( \
- (ctrl != nullptr) && operation \
- " called on invalid iterator. The iterator might be an end() " \
- "iterator or may have been default constructed."); \
- ABSL_HARDENING_ASSERT( \
- (IsFull(*ctrl)) && operation \
- " called on invalid iterator. The element might have been erased or " \
- "the table might have rehashed."); \
- } while (0)
-
-inline void AssertIsValid(ctrl_t* ctrl) {
- ABSL_HARDENING_ASSERT((ctrl == nullptr || IsFull(*ctrl)) &&
- "Invalid operation on iterator. The element might have "
- "been erased or the table might have rehashed.");
-}
-
-struct FindInfo {
- size_t offset;
- size_t probe_length;
-};
-
-// Whether a table is "small". A small table fits entirely into a probing
-// group, i.e., has a capacity < `Group::kWidth`.
-//
-// In small mode we are able to use the whole capacity. The extra control
-// bytes give us at least one "empty" control byte to stop the iteration.
-// This is important to make 1 a valid capacity.
-//
-// In small mode only the first `capacity` control bytes after the sentinel
-// are valid. The rest contain dummy ctrl_t::kEmpty values that do not
-// represent a real slot. This is important to take into account on
-// `find_first_non_full()`, where we never try
-// `ShouldInsertBackwards()` for small tables.
-inline bool is_small(size_t capacity) { return capacity < Group::kWidth - 1; }
-
-// Begins a probing operation on `ctrl`, using `hash`.
-inline probe_seq<Group::kWidth> probe(const ctrl_t* ctrl, size_t hash,
- size_t capacity) {
- return probe_seq<Group::kWidth>(H1(hash, ctrl), capacity);
-}
-
-// Probes an array of control bits using a probe sequence derived from `hash`,
-// and returns the offset corresponding to the first deleted or empty slot.
-//
-// Behavior when the entire table is full is undefined.
-//
-// NOTE: this function must work with tables having both empty and deleted
-// slots in the same group. Such tables appear during `erase()`.
-template <typename = void>
-inline FindInfo find_first_non_full(const ctrl_t* ctrl, size_t hash,
- size_t capacity) {
- auto seq = probe(ctrl, hash, capacity);
- while (true) {
- Group g{ctrl + seq.offset()};
- auto mask = g.MaskEmptyOrDeleted();
- if (mask) {
-#if !defined(NDEBUG)
- // We want to add entropy even when ASLR is not enabled.
- // In debug build we will randomly insert in either the front or back of
- // the group.
- // TODO(kfm,sbenza): revisit after we do unconditional mixing
- if (!is_small(capacity) && ShouldInsertBackwards(hash, ctrl)) {
- return {seq.offset(mask.HighestBitSet()), seq.index()};
- }
-#endif
- return {seq.offset(mask.LowestBitSet()), seq.index()};
- }
- seq.next();
- assert(seq.index() <= capacity && "full table!");
- }
-}
-
-// Extern template for inline function keep possibility of inlining.
-// When compiler decided to not inline, no symbols will be added to the
-// corresponding translation unit.
-extern template FindInfo find_first_non_full(const ctrl_t*, size_t, size_t);
-
-// Sets `ctrl` to `{kEmpty, kSentinel, ..., kEmpty}`, marking the entire
-// array as marked as empty.
-inline void ResetCtrl(size_t capacity, ctrl_t* ctrl, const void* slot,
- size_t slot_size) {
- std::memset(ctrl, static_cast<int8_t>(ctrl_t::kEmpty),
- capacity + 1 + NumClonedBytes());
- ctrl[capacity] = ctrl_t::kSentinel;
- SanitizerPoisonMemoryRegion(slot, slot_size * capacity);
-}
-
-// Sets `ctrl[i]` to `h`.
-//
-// Unlike setting it directly, this function will perform bounds checks and
-// mirror the value to the cloned tail if necessary.
-inline void SetCtrl(size_t i, ctrl_t h, size_t capacity, ctrl_t* ctrl,
- const void* slot, size_t slot_size) {
- assert(i < capacity);
-
- auto* slot_i = static_cast<const char*>(slot) + i * slot_size;
- if (IsFull(h)) {
- SanitizerUnpoisonMemoryRegion(slot_i, slot_size);
- } else {
- SanitizerPoisonMemoryRegion(slot_i, slot_size);
- }
-
- ctrl[i] = h;
- ctrl[((i - NumClonedBytes()) & capacity) + (NumClonedBytes() & capacity)] = h;
-}
-
-// Overload for setting to an occupied `h2_t` rather than a special `ctrl_t`.
-inline void SetCtrl(size_t i, h2_t h, size_t capacity, ctrl_t* ctrl,
- const void* slot, size_t slot_size) {
- SetCtrl(i, static_cast<ctrl_t>(h), capacity, ctrl, slot, slot_size);
-}
-
-// Given the capacity of a table, computes the offset (from the start of the
-// backing allocation) at which the slots begin.
-inline size_t SlotOffset(size_t capacity, size_t slot_align) {
- assert(IsValidCapacity(capacity));
- const size_t num_control_bytes = capacity + 1 + NumClonedBytes();
- return (num_control_bytes + slot_align - 1) & (~slot_align + 1);
-}
-
-// Given the capacity of a table, computes the total size of the backing
-// array.
-inline size_t AllocSize(size_t capacity, size_t slot_size, size_t slot_align) {
- return SlotOffset(capacity, slot_align) + capacity * slot_size;
-}
-
-// A SwissTable.
-//
-// Policy: a policy defines how to perform different operations on
-// the slots of the hashtable (see hash_policy_traits.h for the full interface
-// of policy).
-//
-// Hash: a (possibly polymorphic) functor that hashes keys of the hashtable. The
-// functor should accept a key and return size_t as hash. For best performance
-// it is important that the hash function provides high entropy across all bits
-// of the hash.
-//
-// Eq: a (possibly polymorphic) functor that compares two keys for equality. It
-// should accept two (of possibly different type) keys and return a bool: true
-// if they are equal, false if they are not. If two keys compare equal, then
-// their hash values as defined by Hash MUST be equal.
-//
-// Allocator: an Allocator
-// [https://en.cppreference.com/w/cpp/named_req/Allocator] with which
-// the storage of the hashtable will be allocated and the elements will be
-// constructed and destroyed.
-template <class Policy, class Hash, class Eq, class Alloc>
-class raw_hash_set {
- using PolicyTraits = hash_policy_traits<Policy>;
- using KeyArgImpl =
- KeyArg<IsTransparent<Eq>::value && IsTransparent<Hash>::value>;
-
- public:
- using init_type = typename PolicyTraits::init_type;
- using key_type = typename PolicyTraits::key_type;
- // TODO(sbenza): Hide slot_type as it is an implementation detail. Needs user
- // code fixes!
- using slot_type = typename PolicyTraits::slot_type;
- using allocator_type = Alloc;
- using size_type = size_t;
- using difference_type = ptrdiff_t;
- using hasher = Hash;
- using key_equal = Eq;
- using policy_type = Policy;
- using value_type = typename PolicyTraits::value_type;
- using reference = value_type&;
- using const_reference = const value_type&;
- using pointer = typename absl::allocator_traits<
- allocator_type>::template rebind_traits<value_type>::pointer;
- using const_pointer = typename absl::allocator_traits<
- allocator_type>::template rebind_traits<value_type>::const_pointer;
-
- // Alias used for heterogeneous lookup functions.
- // `key_arg<K>` evaluates to `K` when the functors are transparent and to
- // `key_type` otherwise. It permits template argument deduction on `K` for the
- // transparent case.
- template <class K>
- using key_arg = typename KeyArgImpl::template type<K, key_type>;
-
- private:
- // Give an early error when key_type is not hashable/eq.
- auto KeyTypeCanBeHashed(const Hash& h, const key_type& k) -> decltype(h(k));
- auto KeyTypeCanBeEq(const Eq& eq, const key_type& k) -> decltype(eq(k, k));
-
- using AllocTraits = absl::allocator_traits<allocator_type>;
- using SlotAlloc = typename absl::allocator_traits<
- allocator_type>::template rebind_alloc<slot_type>;
- using SlotAllocTraits = typename absl::allocator_traits<
- allocator_type>::template rebind_traits<slot_type>;
-
- static_assert(std::is_lvalue_reference<reference>::value,
- "Policy::element() must return a reference");
-
- template <typename T>
- struct SameAsElementReference
- : std::is_same<typename std::remove_cv<
- typename std::remove_reference<reference>::type>::type,
- typename std::remove_cv<
- typename std::remove_reference<T>::type>::type> {};
-
- // An enabler for insert(T&&): T must be convertible to init_type or be the
- // same as [cv] value_type [ref].
- // Note: we separate SameAsElementReference into its own type to avoid using
- // reference unless we need to. MSVC doesn't seem to like it in some
- // cases.
- template <class T>
- using RequiresInsertable = typename std::enable_if<
- absl::disjunction<std::is_convertible<T, init_type>,
- SameAsElementReference<T>>::value,
- int>::type;
-
- // RequiresNotInit is a workaround for gcc prior to 7.1.
- // See https://godbolt.org/g/Y4xsUh.
- template <class T>
- using RequiresNotInit =
- typename std::enable_if<!std::is_same<T, init_type>::value, int>::type;
-
- template <class... Ts>
- using IsDecomposable = IsDecomposable<void, PolicyTraits, Hash, Eq, Ts...>;
-
- public:
- static_assert(std::is_same<pointer, value_type*>::value,
- "Allocators with custom pointer types are not supported");
- static_assert(std::is_same<const_pointer, const value_type*>::value,
- "Allocators with custom pointer types are not supported");
-
- class iterator {
- friend class raw_hash_set;
-
- public:
- using iterator_category = std::forward_iterator_tag;
- using value_type = typename raw_hash_set::value_type;
- using reference =
- absl::conditional_t<PolicyTraits::constant_iterators::value,
- const value_type&, value_type&>;
- using pointer = absl::remove_reference_t<reference>*;
- using difference_type = typename raw_hash_set::difference_type;
-
- iterator() {}
-
- // PRECONDITION: not an end() iterator.
- reference operator*() const {
- ABSL_INTERNAL_ASSERT_IS_FULL(ctrl_, "operator*()");
- return PolicyTraits::element(slot_);
- }
-
- // PRECONDITION: not an end() iterator.
- pointer operator->() const {
- ABSL_INTERNAL_ASSERT_IS_FULL(ctrl_, "operator->");
- return &operator*();
- }
-
- // PRECONDITION: not an end() iterator.
- iterator& operator++() {
- ABSL_INTERNAL_ASSERT_IS_FULL(ctrl_, "operator++");
- ++ctrl_;
- ++slot_;
- skip_empty_or_deleted();
- return *this;
- }
- // PRECONDITION: not an end() iterator.
- iterator operator++(int) {
- auto tmp = *this;
- ++*this;
- return tmp;
- }
-
- friend bool operator==(const iterator& a, const iterator& b) {
- AssertIsValid(a.ctrl_);
- AssertIsValid(b.ctrl_);
- return a.ctrl_ == b.ctrl_;
- }
- friend bool operator!=(const iterator& a, const iterator& b) {
- return !(a == b);
- }
-
- private:
- iterator(ctrl_t* ctrl, slot_type* slot) : ctrl_(ctrl), slot_(slot) {
- // This assumption helps the compiler know that any non-end iterator is
- // not equal to any end iterator.
- ABSL_ASSUME(ctrl != nullptr);
- }
-
- // Fixes up `ctrl_` to point to a full by advancing it and `slot_` until
- // they reach one.
- //
- // If a sentinel is reached, we null `ctrl_` out instead.
- void skip_empty_or_deleted() {
- while (IsEmptyOrDeleted(*ctrl_)) {
- uint32_t shift = Group{ctrl_}.CountLeadingEmptyOrDeleted();
- ctrl_ += shift;
- slot_ += shift;
- }
- if (ABSL_PREDICT_FALSE(*ctrl_ == ctrl_t::kSentinel)) ctrl_ = nullptr;
- }
-
- ctrl_t* ctrl_ = nullptr;
- // To avoid uninitialized member warnings, put slot_ in an anonymous union.
- // The member is not initialized on singleton and end iterators.
- union {
- slot_type* slot_;
- };
- };
-
- class const_iterator {
- friend class raw_hash_set;
-
- public:
- using iterator_category = typename iterator::iterator_category;
- using value_type = typename raw_hash_set::value_type;
- using reference = typename raw_hash_set::const_reference;
- using pointer = typename raw_hash_set::const_pointer;
- using difference_type = typename raw_hash_set::difference_type;
-
- const_iterator() {}
- // Implicit construction from iterator.
- const_iterator(iterator i) : inner_(std::move(i)) {}
-
- reference operator*() const { return *inner_; }
- pointer operator->() const { return inner_.operator->(); }
-
- const_iterator& operator++() {
- ++inner_;
- return *this;
- }
- const_iterator operator++(int) { return inner_++; }
-
- friend bool operator==(const const_iterator& a, const const_iterator& b) {
- return a.inner_ == b.inner_;
- }
- friend bool operator!=(const const_iterator& a, const const_iterator& b) {
- return !(a == b);
- }
-
- private:
- const_iterator(const ctrl_t* ctrl, const slot_type* slot)
- : inner_(const_cast<ctrl_t*>(ctrl), const_cast<slot_type*>(slot)) {}
-
- iterator inner_;
- };
-
- using node_type = node_handle<Policy, hash_policy_traits<Policy>, Alloc>;
- using insert_return_type = InsertReturnType<iterator, node_type>;
-
- raw_hash_set() noexcept(
- std::is_nothrow_default_constructible<hasher>::value&&
- std::is_nothrow_default_constructible<key_equal>::value&&
- std::is_nothrow_default_constructible<allocator_type>::value) {}
-
- explicit raw_hash_set(size_t bucket_count,
- const hasher& hash = hasher(),
- const key_equal& eq = key_equal(),
- const allocator_type& alloc = allocator_type())
- : ctrl_(EmptyGroup()),
- settings_(0u, HashtablezInfoHandle(), hash, eq, alloc) {
- if (bucket_count) {
- capacity_ = NormalizeCapacity(bucket_count);
- initialize_slots();
- }
- }
-
- raw_hash_set(size_t bucket_count, const hasher& hash,
- const allocator_type& alloc)
- : raw_hash_set(bucket_count, hash, key_equal(), alloc) {}
-
- raw_hash_set(size_t bucket_count, const allocator_type& alloc)
- : raw_hash_set(bucket_count, hasher(), key_equal(), alloc) {}
-
- explicit raw_hash_set(const allocator_type& alloc)
- : raw_hash_set(0, hasher(), key_equal(), alloc) {}
-
- template <class InputIter>
- raw_hash_set(InputIter first, InputIter last, size_t bucket_count = 0,
- const hasher& hash = hasher(), const key_equal& eq = key_equal(),
- const allocator_type& alloc = allocator_type())
- : raw_hash_set(SelectBucketCountForIterRange(first, last, bucket_count),
- hash, eq, alloc) {
- insert(first, last);
- }
-
- template <class InputIter>
- raw_hash_set(InputIter first, InputIter last, size_t bucket_count,
- const hasher& hash, const allocator_type& alloc)
- : raw_hash_set(first, last, bucket_count, hash, key_equal(), alloc) {}
-
- template <class InputIter>
- raw_hash_set(InputIter first, InputIter last, size_t bucket_count,
- const allocator_type& alloc)
- : raw_hash_set(first, last, bucket_count, hasher(), key_equal(), alloc) {}
-
- template <class InputIter>
- raw_hash_set(InputIter first, InputIter last, const allocator_type& alloc)
- : raw_hash_set(first, last, 0, hasher(), key_equal(), alloc) {}
-
- // Instead of accepting std::initializer_list<value_type> as the first
- // argument like std::unordered_set<value_type> does, we have two overloads
- // that accept std::initializer_list<T> and std::initializer_list<init_type>.
- // This is advantageous for performance.
- //
- // // Turns {"abc", "def"} into std::initializer_list<std::string>, then
- // // copies the strings into the set.
- // std::unordered_set<std::string> s = {"abc", "def"};
- //
- // // Turns {"abc", "def"} into std::initializer_list<const char*>, then
- // // copies the strings into the set.
- // absl::flat_hash_set<std::string> s = {"abc", "def"};
- //
- // The same trick is used in insert().
- //
- // The enabler is necessary to prevent this constructor from triggering where
- // the copy constructor is meant to be called.
- //
- // absl::flat_hash_set<int> a, b{a};
- //
- // RequiresNotInit<T> is a workaround for gcc prior to 7.1.
- template <class T, RequiresNotInit<T> = 0, RequiresInsertable<T> = 0>
- raw_hash_set(std::initializer_list<T> init, size_t bucket_count = 0,
- const hasher& hash = hasher(), const key_equal& eq = key_equal(),
- const allocator_type& alloc = allocator_type())
- : raw_hash_set(init.begin(), init.end(), bucket_count, hash, eq, alloc) {}
-
- raw_hash_set(std::initializer_list<init_type> init, size_t bucket_count = 0,
- const hasher& hash = hasher(), const key_equal& eq = key_equal(),
- const allocator_type& alloc = allocator_type())
- : raw_hash_set(init.begin(), init.end(), bucket_count, hash, eq, alloc) {}
-
- template <class T, RequiresNotInit<T> = 0, RequiresInsertable<T> = 0>
- raw_hash_set(std::initializer_list<T> init, size_t bucket_count,
- const hasher& hash, const allocator_type& alloc)
- : raw_hash_set(init, bucket_count, hash, key_equal(), alloc) {}
-
- raw_hash_set(std::initializer_list<init_type> init, size_t bucket_count,
- const hasher& hash, const allocator_type& alloc)
- : raw_hash_set(init, bucket_count, hash, key_equal(), alloc) {}
-
- template <class T, RequiresNotInit<T> = 0, RequiresInsertable<T> = 0>
- raw_hash_set(std::initializer_list<T> init, size_t bucket_count,
- const allocator_type& alloc)
- : raw_hash_set(init, bucket_count, hasher(), key_equal(), alloc) {}
-
- raw_hash_set(std::initializer_list<init_type> init, size_t bucket_count,
- const allocator_type& alloc)
- : raw_hash_set(init, bucket_count, hasher(), key_equal(), alloc) {}
-
- template <class T, RequiresNotInit<T> = 0, RequiresInsertable<T> = 0>
- raw_hash_set(std::initializer_list<T> init, const allocator_type& alloc)
- : raw_hash_set(init, 0, hasher(), key_equal(), alloc) {}
-
- raw_hash_set(std::initializer_list<init_type> init,
- const allocator_type& alloc)
- : raw_hash_set(init, 0, hasher(), key_equal(), alloc) {}
-
- raw_hash_set(const raw_hash_set& that)
- : raw_hash_set(that, AllocTraits::select_on_container_copy_construction(
- that.alloc_ref())) {}
-
- raw_hash_set(const raw_hash_set& that, const allocator_type& a)
- : raw_hash_set(0, that.hash_ref(), that.eq_ref(), a) {
- reserve(that.size());
- // Because the table is guaranteed to be empty, we can do something faster
- // than a full `insert`.
- for (const auto& v : that) {
- const size_t hash = PolicyTraits::apply(HashElement{hash_ref()}, v);
- auto target = find_first_non_full(ctrl_, hash, capacity_);
- SetCtrl(target.offset, H2(hash), capacity_, ctrl_, slots_,
- sizeof(slot_type));
- emplace_at(target.offset, v);
- infoz().RecordInsert(hash, target.probe_length);
- }
- size_ = that.size();
- growth_left() -= that.size();
- }
-
- raw_hash_set(raw_hash_set&& that) noexcept(
- std::is_nothrow_copy_constructible<hasher>::value&&
- std::is_nothrow_copy_constructible<key_equal>::value&&
- std::is_nothrow_copy_constructible<allocator_type>::value)
- : ctrl_(absl::exchange(that.ctrl_, EmptyGroup())),
- slots_(absl::exchange(that.slots_, nullptr)),
- size_(absl::exchange(that.size_, size_t{0})),
- capacity_(absl::exchange(that.capacity_, size_t{0})),
- // Hash, equality and allocator are copied instead of moved because
- // `that` must be left valid. If Hash is std::function<Key>, moving it
- // would create a nullptr functor that cannot be called.
- settings_(absl::exchange(that.growth_left(), size_t{0}),
- absl::exchange(that.infoz(), HashtablezInfoHandle()),
- that.hash_ref(),
- that.eq_ref(),
- that.alloc_ref()) {}
-
- raw_hash_set(raw_hash_set&& that, const allocator_type& a)
- : ctrl_(EmptyGroup()),
- slots_(nullptr),
- size_(0),
- capacity_(0),
- settings_(0, HashtablezInfoHandle(), that.hash_ref(), that.eq_ref(),
- a) {
- if (a == that.alloc_ref()) {
- std::swap(ctrl_, that.ctrl_);
- std::swap(slots_, that.slots_);
- std::swap(size_, that.size_);
- std::swap(capacity_, that.capacity_);
- std::swap(growth_left(), that.growth_left());
- std::swap(infoz(), that.infoz());
- } else {
- reserve(that.size());
- // Note: this will copy elements of dense_set and unordered_set instead of
- // moving them. This can be fixed if it ever becomes an issue.
- for (auto& elem : that) insert(std::move(elem));
- }
- }
-
- raw_hash_set& operator=(const raw_hash_set& that) {
- raw_hash_set tmp(that,
- AllocTraits::propagate_on_container_copy_assignment::value
- ? that.alloc_ref()
- : alloc_ref());
- swap(tmp);
- return *this;
- }
-
- raw_hash_set& operator=(raw_hash_set&& that) noexcept(
- absl::allocator_traits<allocator_type>::is_always_equal::value&&
- std::is_nothrow_move_assignable<hasher>::value&&
- std::is_nothrow_move_assignable<key_equal>::value) {
- // TODO(sbenza): We should only use the operations from the noexcept clause
- // to make sure we actually adhere to that contract.
- return move_assign(
- std::move(that),
- typename AllocTraits::propagate_on_container_move_assignment());
- }
-
- ~raw_hash_set() { destroy_slots(); }
-
- iterator begin() {
- auto it = iterator_at(0);
- it.skip_empty_or_deleted();
- return it;
- }
- iterator end() { return {}; }
-
- const_iterator begin() const {
- return const_cast<raw_hash_set*>(this)->begin();
- }
- const_iterator end() const { return {}; }
- const_iterator cbegin() const { return begin(); }
- const_iterator cend() const { return end(); }
-
- bool empty() const { return !size(); }
- size_t size() const { return size_; }
- size_t capacity() const { return capacity_; }
- size_t max_size() const { return (std::numeric_limits<size_t>::max)(); }
-
- ABSL_ATTRIBUTE_REINITIALIZES void clear() {
- // Iterating over this container is O(bucket_count()). When bucket_count()
- // is much greater than size(), iteration becomes prohibitively expensive.
- // For clear() it is more important to reuse the allocated array when the
- // container is small because allocation takes comparatively long time
- // compared to destruction of the elements of the container. So we pick the
- // largest bucket_count() threshold for which iteration is still fast and
- // past that we simply deallocate the array.
- if (capacity_ > 127) {
- destroy_slots();
-
- infoz().RecordClearedReservation();
- } else if (capacity_) {
- for (size_t i = 0; i != capacity_; ++i) {
- if (IsFull(ctrl_[i])) {
- PolicyTraits::destroy(&alloc_ref(), slots_ + i);
- }
- }
- size_ = 0;
- ResetCtrl(capacity_, ctrl_, slots_, sizeof(slot_type));
- reset_growth_left();
- }
- assert(empty());
- infoz().RecordStorageChanged(0, capacity_);
- }
-
- // This overload kicks in when the argument is an rvalue of insertable and
- // decomposable type other than init_type.
- //
- // flat_hash_map<std::string, int> m;
- // m.insert(std::make_pair("abc", 42));
- // TODO(cheshire): A type alias T2 is introduced as a workaround for the nvcc
- // bug.
- template <class T, RequiresInsertable<T> = 0, class T2 = T,
- typename std::enable_if<IsDecomposable<T2>::value, int>::type = 0,
- T* = nullptr>
- std::pair<iterator, bool> insert(T&& value) {
- return emplace(std::forward<T>(value));
- }
-
- // This overload kicks in when the argument is a bitfield or an lvalue of
- // insertable and decomposable type.
- //
- // union { int n : 1; };
- // flat_hash_set<int> s;
- // s.insert(n);
- //
- // flat_hash_set<std::string> s;
- // const char* p = "hello";
- // s.insert(p);
- //
- // TODO(romanp): Once we stop supporting gcc 5.1 and below, replace
- // RequiresInsertable<T> with RequiresInsertable<const T&>.
- // We are hitting this bug: https://godbolt.org/g/1Vht4f.
- template <
- class T, RequiresInsertable<T> = 0,
- typename std::enable_if<IsDecomposable<const T&>::value, int>::type = 0>
- std::pair<iterator, bool> insert(const T& value) {
- return emplace(value);
- }
-
- // This overload kicks in when the argument is an rvalue of init_type. Its
- // purpose is to handle brace-init-list arguments.
- //
- // flat_hash_map<std::string, int> s;
- // s.insert({"abc", 42});
- std::pair<iterator, bool> insert(init_type&& value) {
- return emplace(std::move(value));
- }
-
- // TODO(cheshire): A type alias T2 is introduced as a workaround for the nvcc
- // bug.
- template <class T, RequiresInsertable<T> = 0, class T2 = T,
- typename std::enable_if<IsDecomposable<T2>::value, int>::type = 0,
- T* = nullptr>
- iterator insert(const_iterator, T&& value) {
- return insert(std::forward<T>(value)).first;
- }
-
- // TODO(romanp): Once we stop supporting gcc 5.1 and below, replace
- // RequiresInsertable<T> with RequiresInsertable<const T&>.
- // We are hitting this bug: https://godbolt.org/g/1Vht4f.
- template <
- class T, RequiresInsertable<T> = 0,
- typename std::enable_if<IsDecomposable<const T&>::value, int>::type = 0>
- iterator insert(const_iterator, const T& value) {
- return insert(value).first;
- }
-
- iterator insert(const_iterator, init_type&& value) {
- return insert(std::move(value)).first;
- }
-
- template <class InputIt>
- void insert(InputIt first, InputIt last) {
- for (; first != last; ++first) emplace(*first);
- }
-
- template <class T, RequiresNotInit<T> = 0, RequiresInsertable<const T&> = 0>
- void insert(std::initializer_list<T> ilist) {
- insert(ilist.begin(), ilist.end());
- }
-
- void insert(std::initializer_list<init_type> ilist) {
- insert(ilist.begin(), ilist.end());
- }
-
- insert_return_type insert(node_type&& node) {
- if (!node) return {end(), false, node_type()};
- const auto& elem = PolicyTraits::element(CommonAccess::GetSlot(node));
- auto res = PolicyTraits::apply(
- InsertSlot<false>{*this, std::move(*CommonAccess::GetSlot(node))},
- elem);
- if (res.second) {
- CommonAccess::Reset(&node);
- return {res.first, true, node_type()};
- } else {
- return {res.first, false, std::move(node)};
- }
- }
-
- iterator insert(const_iterator, node_type&& node) {
- auto res = insert(std::move(node));
- node = std::move(res.node);
- return res.position;
- }
-
- // This overload kicks in if we can deduce the key from args. This enables us
- // to avoid constructing value_type if an entry with the same key already
- // exists.
- //
- // For example:
- //
- // flat_hash_map<std::string, std::string> m = {{"abc", "def"}};
- // // Creates no std::string copies and makes no heap allocations.
- // m.emplace("abc", "xyz");
- template <class... Args, typename std::enable_if<
- IsDecomposable<Args...>::value, int>::type = 0>
- std::pair<iterator, bool> emplace(Args&&... args) {
- return PolicyTraits::apply(EmplaceDecomposable{*this},
- std::forward<Args>(args)...);
- }
-
- // This overload kicks in if we cannot deduce the key from args. It constructs
- // value_type unconditionally and then either moves it into the table or
- // destroys.
- template <class... Args, typename std::enable_if<
- !IsDecomposable<Args...>::value, int>::type = 0>
- std::pair<iterator, bool> emplace(Args&&... args) {
- alignas(slot_type) unsigned char raw[sizeof(slot_type)];
- slot_type* slot = reinterpret_cast<slot_type*>(&raw);
-
- PolicyTraits::construct(&alloc_ref(), slot, std::forward<Args>(args)...);
- const auto& elem = PolicyTraits::element(slot);
- return PolicyTraits::apply(InsertSlot<true>{*this, std::move(*slot)}, elem);
- }
-
- template <class... Args>
- iterator emplace_hint(const_iterator, Args&&... args) {
- return emplace(std::forward<Args>(args)...).first;
- }
-
- // Extension API: support for lazy emplace.
- //
- // Looks up key in the table. If found, returns the iterator to the element.
- // Otherwise calls `f` with one argument of type `raw_hash_set::constructor`.
- //
- // `f` must abide by several restrictions:
- // - it MUST call `raw_hash_set::constructor` with arguments as if a
- // `raw_hash_set::value_type` is constructed,
- // - it MUST NOT access the container before the call to
- // `raw_hash_set::constructor`, and
- // - it MUST NOT erase the lazily emplaced element.
- // Doing any of these is undefined behavior.
- //
- // For example:
- //
- // std::unordered_set<ArenaString> s;
- // // Makes ArenaStr even if "abc" is in the map.
- // s.insert(ArenaString(&arena, "abc"));
- //
- // flat_hash_set<ArenaStr> s;
- // // Makes ArenaStr only if "abc" is not in the map.
- // s.lazy_emplace("abc", [&](const constructor& ctor) {
- // ctor(&arena, "abc");
- // });
- //
- // WARNING: This API is currently experimental. If there is a way to implement
- // the same thing with the rest of the API, prefer that.
- class constructor {
- friend class raw_hash_set;
-
- public:
- template <class... Args>
- void operator()(Args&&... args) const {
- assert(*slot_);
- PolicyTraits::construct(alloc_, *slot_, std::forward<Args>(args)...);
- *slot_ = nullptr;
- }
-
- private:
- constructor(allocator_type* a, slot_type** slot) : alloc_(a), slot_(slot) {}
-
- allocator_type* alloc_;
- slot_type** slot_;
- };
-
- template <class K = key_type, class F>
- iterator lazy_emplace(const key_arg<K>& key, F&& f) {
- auto res = find_or_prepare_insert(key);
- if (res.second) {
- slot_type* slot = slots_ + res.first;
- std::forward<F>(f)(constructor(&alloc_ref(), &slot));
- assert(!slot);
- }
- return iterator_at(res.first);
- }
-
- // Extension API: support for heterogeneous keys.
- //
- // std::unordered_set<std::string> s;
- // // Turns "abc" into std::string.
- // s.erase("abc");
- //
- // flat_hash_set<std::string> s;
- // // Uses "abc" directly without copying it into std::string.
- // s.erase("abc");
- template <class K = key_type>
- size_type erase(const key_arg<K>& key) {
- auto it = find(key);
- if (it == end()) return 0;
- erase(it);
- return 1;
- }
-
- // Erases the element pointed to by `it`. Unlike `std::unordered_set::erase`,
- // this method returns void to reduce algorithmic complexity to O(1). The
- // iterator is invalidated, so any increment should be done before calling
- // erase. In order to erase while iterating across a map, use the following
- // idiom (which also works for standard containers):
- //
- // for (auto it = m.begin(), end = m.end(); it != end;) {
- // // `erase()` will invalidate `it`, so advance `it` first.
- // auto copy_it = it++;
- // if (<pred>) {
- // m.erase(copy_it);
- // }
- // }
- void erase(const_iterator cit) { erase(cit.inner_); }
-
- // This overload is necessary because otherwise erase<K>(const K&) would be
- // a better match if non-const iterator is passed as an argument.
- void erase(iterator it) {
- ABSL_INTERNAL_ASSERT_IS_FULL(it.ctrl_, "erase()");
- PolicyTraits::destroy(&alloc_ref(), it.slot_);
- erase_meta_only(it);
- }
-
- iterator erase(const_iterator first, const_iterator last) {
- while (first != last) {
- erase(first++);
- }
- return last.inner_;
- }
-
- // Moves elements from `src` into `this`.
- // If the element already exists in `this`, it is left unmodified in `src`.
- template <typename H, typename E>
- void merge(raw_hash_set<Policy, H, E, Alloc>& src) { // NOLINT
- assert(this != &src);
- for (auto it = src.begin(), e = src.end(); it != e;) {
- auto next = std::next(it);
- if (PolicyTraits::apply(InsertSlot<false>{*this, std::move(*it.slot_)},
- PolicyTraits::element(it.slot_))
- .second) {
- src.erase_meta_only(it);
- }
- it = next;
- }
- }
-
- template <typename H, typename E>
- void merge(raw_hash_set<Policy, H, E, Alloc>&& src) {
- merge(src);
- }
-
- node_type extract(const_iterator position) {
- ABSL_INTERNAL_ASSERT_IS_FULL(position.inner_.ctrl_, "extract()");
- auto node =
- CommonAccess::Transfer<node_type>(alloc_ref(), position.inner_.slot_);
- erase_meta_only(position);
- return node;
- }
-
- template <
- class K = key_type,
- typename std::enable_if<!std::is_same<K, iterator>::value, int>::type = 0>
- node_type extract(const key_arg<K>& key) {
- auto it = find(key);
- return it == end() ? node_type() : extract(const_iterator{it});
- }
-
- void swap(raw_hash_set& that) noexcept(
- IsNoThrowSwappable<hasher>() && IsNoThrowSwappable<key_equal>() &&
- IsNoThrowSwappable<allocator_type>(
- typename AllocTraits::propagate_on_container_swap{})) {
- using std::swap;
- swap(ctrl_, that.ctrl_);
- swap(slots_, that.slots_);
- swap(size_, that.size_);
- swap(capacity_, that.capacity_);
- swap(growth_left(), that.growth_left());
- swap(hash_ref(), that.hash_ref());
- swap(eq_ref(), that.eq_ref());
- swap(infoz(), that.infoz());
- SwapAlloc(alloc_ref(), that.alloc_ref(),
- typename AllocTraits::propagate_on_container_swap{});
- }
-
- void rehash(size_t n) {
- if (n == 0 && capacity_ == 0) return;
- if (n == 0 && size_ == 0) {
- destroy_slots();
- infoz().RecordStorageChanged(0, 0);
- infoz().RecordClearedReservation();
- return;
- }
-
- // bitor is a faster way of doing `max` here. We will round up to the next
- // power-of-2-minus-1, so bitor is good enough.
- auto m = NormalizeCapacity(n | GrowthToLowerboundCapacity(size()));
- // n == 0 unconditionally rehashes as per the standard.
- if (n == 0 || m > capacity_) {
- resize(m);
-
- // This is after resize, to ensure that we have completed the allocation
- // and have potentially sampled the hashtable.
- infoz().RecordReservation(n);
- }
- }
-
- void reserve(size_t n) {
- if (n > size() + growth_left()) {
- size_t m = GrowthToLowerboundCapacity(n);
- resize(NormalizeCapacity(m));
-
- // This is after resize, to ensure that we have completed the allocation
- // and have potentially sampled the hashtable.
- infoz().RecordReservation(n);
- }
- }
-
- // Extension API: support for heterogeneous keys.
- //
- // std::unordered_set<std::string> s;
- // // Turns "abc" into std::string.
- // s.count("abc");
- //
- // ch_set<std::string> s;
- // // Uses "abc" directly without copying it into std::string.
- // s.count("abc");
- template <class K = key_type>
- size_t count(const key_arg<K>& key) const {
- return find(key) == end() ? 0 : 1;
- }
-
- // Issues CPU prefetch instructions for the memory needed to find or insert
- // a key. Like all lookup functions, this support heterogeneous keys.
- //
- // NOTE: This is a very low level operation and should not be used without
- // specific benchmarks indicating its importance.
- template <class K = key_type>
- void prefetch(const key_arg<K>& key) const {
- (void)key;
- // Avoid probing if we won't be able to prefetch the addresses received.
-#ifdef ABSL_INTERNAL_HAVE_PREFETCH
- prefetch_heap_block();
- auto seq = probe(ctrl_, hash_ref()(key), capacity_);
- base_internal::PrefetchT0(ctrl_ + seq.offset());
- base_internal::PrefetchT0(slots_ + seq.offset());
-#endif // ABSL_INTERNAL_HAVE_PREFETCH
- }
-
- // The API of find() has two extensions.
- //
- // 1. The hash can be passed by the user. It must be equal to the hash of the
- // key.
- //
- // 2. The type of the key argument doesn't have to be key_type. This is so
- // called heterogeneous key support.
- template <class K = key_type>
- iterator find(const key_arg<K>& key, size_t hash) {
- auto seq = probe(ctrl_, hash, capacity_);
- while (true) {
- Group g{ctrl_ + seq.offset()};
- for (uint32_t i : g.Match(H2(hash))) {
- if (ABSL_PREDICT_TRUE(PolicyTraits::apply(
- EqualElement<K>{key, eq_ref()},
- PolicyTraits::element(slots_ + seq.offset(i)))))
- return iterator_at(seq.offset(i));
- }
- if (ABSL_PREDICT_TRUE(g.MaskEmpty())) return end();
- seq.next();
- assert(seq.index() <= capacity_ && "full table!");
- }
- }
- template <class K = key_type>
- iterator find(const key_arg<K>& key) {
- prefetch_heap_block();
- return find(key, hash_ref()(key));
- }
-
- template <class K = key_type>
- const_iterator find(const key_arg<K>& key, size_t hash) const {
- return const_cast<raw_hash_set*>(this)->find(key, hash);
- }
- template <class K = key_type>
- const_iterator find(const key_arg<K>& key) const {
- prefetch_heap_block();
- return find(key, hash_ref()(key));
- }
-
- template <class K = key_type>
- bool contains(const key_arg<K>& key) const {
- return find(key) != end();
- }
-
- template <class K = key_type>
- std::pair<iterator, iterator> equal_range(const key_arg<K>& key) {
- auto it = find(key);
- if (it != end()) return {it, std::next(it)};
- return {it, it};
- }
- template <class K = key_type>
- std::pair<const_iterator, const_iterator> equal_range(
- const key_arg<K>& key) const {
- auto it = find(key);
- if (it != end()) return {it, std::next(it)};
- return {it, it};
- }
-
- size_t bucket_count() const { return capacity_; }
- float load_factor() const {
- return capacity_ ? static_cast<double>(size()) / capacity_ : 0.0;
- }
- float max_load_factor() const { return 1.0f; }
- void max_load_factor(float) {
- // Does nothing.
- }
-
- hasher hash_function() const { return hash_ref(); }
- key_equal key_eq() const { return eq_ref(); }
- allocator_type get_allocator() const { return alloc_ref(); }
-
- friend bool operator==(const raw_hash_set& a, const raw_hash_set& b) {
- if (a.size() != b.size()) return false;
- const raw_hash_set* outer = &a;
- const raw_hash_set* inner = &b;
- if (outer->capacity() > inner->capacity()) std::swap(outer, inner);
- for (const value_type& elem : *outer)
- if (!inner->has_element(elem)) return false;
- return true;
- }
-
- friend bool operator!=(const raw_hash_set& a, const raw_hash_set& b) {
- return !(a == b);
- }
-
- template <typename H>
- friend typename std::enable_if<H::template is_hashable<value_type>::value,
- H>::type
- AbslHashValue(H h, const raw_hash_set& s) {
- return H::combine(H::combine_unordered(std::move(h), s.begin(), s.end()),
- s.size());
- }
-
- friend void swap(raw_hash_set& a,
- raw_hash_set& b) noexcept(noexcept(a.swap(b))) {
- a.swap(b);
- }
-
- private:
- template <class Container, typename Enabler>
- friend struct absl::container_internal::hashtable_debug_internal::
- HashtableDebugAccess;
-
- struct FindElement {
- template <class K, class... Args>
- const_iterator operator()(const K& key, Args&&...) const {
- return s.find(key);
- }
- const raw_hash_set& s;
- };
-
- struct HashElement {
- template <class K, class... Args>
- size_t operator()(const K& key, Args&&...) const {
- return h(key);
- }
- const hasher& h;
- };
-
- template <class K1>
- struct EqualElement {
- template <class K2, class... Args>
- bool operator()(const K2& lhs, Args&&...) const {
- return eq(lhs, rhs);
- }
- const K1& rhs;
- const key_equal& eq;
- };
-
- struct EmplaceDecomposable {
- template <class K, class... Args>
- std::pair<iterator, bool> operator()(const K& key, Args&&... args) const {
- auto res = s.find_or_prepare_insert(key);
- if (res.second) {
- s.emplace_at(res.first, std::forward<Args>(args)...);
- }
- return {s.iterator_at(res.first), res.second};
- }
- raw_hash_set& s;
- };
-
- template <bool do_destroy>
- struct InsertSlot {
- template <class K, class... Args>
- std::pair<iterator, bool> operator()(const K& key, Args&&...) && {
- auto res = s.find_or_prepare_insert(key);
- if (res.second) {
- PolicyTraits::transfer(&s.alloc_ref(), s.slots_ + res.first, &slot);
- } else if (do_destroy) {
- PolicyTraits::destroy(&s.alloc_ref(), &slot);
- }
- return {s.iterator_at(res.first), res.second};
- }
- raw_hash_set& s;
- // Constructed slot. Either moved into place or destroyed.
- slot_type&& slot;
- };
-
- // Erases, but does not destroy, the value pointed to by `it`.
- //
- // This merely updates the pertinent control byte. This can be used in
- // conjunction with Policy::transfer to move the object to another place.
- void erase_meta_only(const_iterator it) {
- assert(IsFull(*it.inner_.ctrl_) && "erasing a dangling iterator");
- --size_;
- const size_t index = static_cast<size_t>(it.inner_.ctrl_ - ctrl_);
- const size_t index_before = (index - Group::kWidth) & capacity_;
- const auto empty_after = Group(it.inner_.ctrl_).MaskEmpty();
- const auto empty_before = Group(ctrl_ + index_before).MaskEmpty();
-
- // We count how many consecutive non empties we have to the right and to the
- // left of `it`. If the sum is >= kWidth then there is at least one probe
- // window that might have seen a full group.
- bool was_never_full =
- empty_before && empty_after &&
- static_cast<size_t>(empty_after.TrailingZeros() +
- empty_before.LeadingZeros()) < Group::kWidth;
-
- SetCtrl(index, was_never_full ? ctrl_t::kEmpty : ctrl_t::kDeleted,
- capacity_, ctrl_, slots_, sizeof(slot_type));
- growth_left() += was_never_full;
- infoz().RecordErase();
- }
-
- // Allocates a backing array for `self` and initializes its control bytes.
- // This reads `capacity_` and updates all other fields based on the result of
- // the allocation.
- //
- // This does not free the currently held array; `capacity_` must be nonzero.
- void initialize_slots() {
- assert(capacity_);
- // Folks with custom allocators often make unwarranted assumptions about the
- // behavior of their classes vis-a-vis trivial destructability and what
- // calls they will or wont make. Avoid sampling for people with custom
- // allocators to get us out of this mess. This is not a hard guarantee but
- // a workaround while we plan the exact guarantee we want to provide.
- //
- // People are often sloppy with the exact type of their allocator (sometimes
- // it has an extra const or is missing the pair, but rebinds made it work
- // anyway). To avoid the ambiguity, we work off SlotAlloc which we have
- // bound more carefully.
- if (std::is_same<SlotAlloc, std::allocator<slot_type>>::value &&
- slots_ == nullptr) {
- infoz() = Sample(sizeof(slot_type));
- }
-
- char* mem = static_cast<char*>(Allocate<alignof(slot_type)>(
- &alloc_ref(),
- AllocSize(capacity_, sizeof(slot_type), alignof(slot_type))));
- ctrl_ = reinterpret_cast<ctrl_t*>(mem);
- slots_ = reinterpret_cast<slot_type*>(
- mem + SlotOffset(capacity_, alignof(slot_type)));
- ResetCtrl(capacity_, ctrl_, slots_, sizeof(slot_type));
- reset_growth_left();
- infoz().RecordStorageChanged(size_, capacity_);
- }
-
- // Destroys all slots in the backing array, frees the backing array, and
- // clears all top-level book-keeping data.
- //
- // This essentially implements `map = raw_hash_set();`.
- void destroy_slots() {
- if (!capacity_) return;
- for (size_t i = 0; i != capacity_; ++i) {
- if (IsFull(ctrl_[i])) {
- PolicyTraits::destroy(&alloc_ref(), slots_ + i);
- }
- }
-
- // Unpoison before returning the memory to the allocator.
- SanitizerUnpoisonMemoryRegion(slots_, sizeof(slot_type) * capacity_);
- Deallocate<alignof(slot_type)>(
- &alloc_ref(), ctrl_,
- AllocSize(capacity_, sizeof(slot_type), alignof(slot_type)));
- ctrl_ = EmptyGroup();
- slots_ = nullptr;
- size_ = 0;
- capacity_ = 0;
- growth_left() = 0;
- }
-
- void resize(size_t new_capacity) {
- assert(IsValidCapacity(new_capacity));
- auto* old_ctrl = ctrl_;
- auto* old_slots = slots_;
- const size_t old_capacity = capacity_;
- capacity_ = new_capacity;
- initialize_slots();
-
- size_t total_probe_length = 0;
- for (size_t i = 0; i != old_capacity; ++i) {
- if (IsFull(old_ctrl[i])) {
- size_t hash = PolicyTraits::apply(HashElement{hash_ref()},
- PolicyTraits::element(old_slots + i));
- auto target = find_first_non_full(ctrl_, hash, capacity_);
- size_t new_i = target.offset;
- total_probe_length += target.probe_length;
- SetCtrl(new_i, H2(hash), capacity_, ctrl_, slots_, sizeof(slot_type));
- PolicyTraits::transfer(&alloc_ref(), slots_ + new_i, old_slots + i);
- }
- }
- if (old_capacity) {
- SanitizerUnpoisonMemoryRegion(old_slots,
- sizeof(slot_type) * old_capacity);
- Deallocate<alignof(slot_type)>(
- &alloc_ref(), old_ctrl,
- AllocSize(old_capacity, sizeof(slot_type), alignof(slot_type)));
- }
- infoz().RecordRehash(total_probe_length);
- }
-
- // Prunes control bytes to remove as many tombstones as possible.
- //
- // See the comment on `rehash_and_grow_if_necessary()`.
- void drop_deletes_without_resize() ABSL_ATTRIBUTE_NOINLINE {
- assert(IsValidCapacity(capacity_));
- assert(!is_small(capacity_));
- // Algorithm:
- // - mark all DELETED slots as EMPTY
- // - mark all FULL slots as DELETED
- // - for each slot marked as DELETED
- // hash = Hash(element)
- // target = find_first_non_full(hash)
- // if target is in the same group
- // mark slot as FULL
- // else if target is EMPTY
- // transfer element to target
- // mark slot as EMPTY
- // mark target as FULL
- // else if target is DELETED
- // swap current element with target element
- // mark target as FULL
- // repeat procedure for current slot with moved from element (target)
- ConvertDeletedToEmptyAndFullToDeleted(ctrl_, capacity_);
- alignas(slot_type) unsigned char raw[sizeof(slot_type)];
- size_t total_probe_length = 0;
- slot_type* slot = reinterpret_cast<slot_type*>(&raw);
- for (size_t i = 0; i != capacity_; ++i) {
- if (!IsDeleted(ctrl_[i])) continue;
- const size_t hash = PolicyTraits::apply(
- HashElement{hash_ref()}, PolicyTraits::element(slots_ + i));
- const FindInfo target = find_first_non_full(ctrl_, hash, capacity_);
- const size_t new_i = target.offset;
- total_probe_length += target.probe_length;
-
- // Verify if the old and new i fall within the same group wrt the hash.
- // If they do, we don't need to move the object as it falls already in the
- // best probe we can.
- const size_t probe_offset = probe(ctrl_, hash, capacity_).offset();
- const auto probe_index = [probe_offset, this](size_t pos) {
- return ((pos - probe_offset) & capacity_) / Group::kWidth;
- };
-
- // Element doesn't move.
- if (ABSL_PREDICT_TRUE(probe_index(new_i) == probe_index(i))) {
- SetCtrl(i, H2(hash), capacity_, ctrl_, slots_, sizeof(slot_type));
- continue;
- }
- if (IsEmpty(ctrl_[new_i])) {
- // Transfer element to the empty spot.
- // SetCtrl poisons/unpoisons the slots so we have to call it at the
- // right time.
- SetCtrl(new_i, H2(hash), capacity_, ctrl_, slots_, sizeof(slot_type));
- PolicyTraits::transfer(&alloc_ref(), slots_ + new_i, slots_ + i);
- SetCtrl(i, ctrl_t::kEmpty, capacity_, ctrl_, slots_, sizeof(slot_type));
- } else {
- assert(IsDeleted(ctrl_[new_i]));
- SetCtrl(new_i, H2(hash), capacity_, ctrl_, slots_, sizeof(slot_type));
- // Until we are done rehashing, DELETED marks previously FULL slots.
- // Swap i and new_i elements.
- PolicyTraits::transfer(&alloc_ref(), slot, slots_ + i);
- PolicyTraits::transfer(&alloc_ref(), slots_ + i, slots_ + new_i);
- PolicyTraits::transfer(&alloc_ref(), slots_ + new_i, slot);
- --i; // repeat
- }
- }
- reset_growth_left();
- infoz().RecordRehash(total_probe_length);
- }
-
- // Called whenever the table *might* need to conditionally grow.
- //
- // This function is an optimization opportunity to perform a rehash even when
- // growth is unnecessary, because vacating tombstones is beneficial for
- // performance in the long-run.
- void rehash_and_grow_if_necessary() {
- if (capacity_ == 0) {
- resize(1);
- } else if (capacity_ > Group::kWidth &&
- // Do these calcuations in 64-bit to avoid overflow.
- size() * uint64_t{32} <= capacity_ * uint64_t{25}) {
- // Squash DELETED without growing if there is enough capacity.
- //
- // Rehash in place if the current size is <= 25/32 of capacity_.
- // Rationale for such a high factor: 1) drop_deletes_without_resize() is
- // faster than resize, and 2) it takes quite a bit of work to add
- // tombstones. In the worst case, seems to take approximately 4
- // insert/erase pairs to create a single tombstone and so if we are
- // rehashing because of tombstones, we can afford to rehash-in-place as
- // long as we are reclaiming at least 1/8 the capacity without doing more
- // than 2X the work. (Where "work" is defined to be size() for rehashing
- // or rehashing in place, and 1 for an insert or erase.) But rehashing in
- // place is faster per operation than inserting or even doubling the size
- // of the table, so we actually afford to reclaim even less space from a
- // resize-in-place. The decision is to rehash in place if we can reclaim
- // at about 1/8th of the usable capacity (specifically 3/28 of the
- // capacity) which means that the total cost of rehashing will be a small
- // fraction of the total work.
- //
- // Here is output of an experiment using the BM_CacheInSteadyState
- // benchmark running the old case (where we rehash-in-place only if we can
- // reclaim at least 7/16*capacity_) vs. this code (which rehashes in place
- // if we can recover 3/32*capacity_).
- //
- // Note that although in the worst-case number of rehashes jumped up from
- // 15 to 190, but the number of operations per second is almost the same.
- //
- // Abridged output of running BM_CacheInSteadyState benchmark from
- // raw_hash_set_benchmark. N is the number of insert/erase operations.
- //
- // | OLD (recover >= 7/16 | NEW (recover >= 3/32)
- // size | N/s LoadFactor NRehashes | N/s LoadFactor NRehashes
- // 448 | 145284 0.44 18 | 140118 0.44 19
- // 493 | 152546 0.24 11 | 151417 0.48 28
- // 538 | 151439 0.26 11 | 151152 0.53 38
- // 583 | 151765 0.28 11 | 150572 0.57 50
- // 628 | 150241 0.31 11 | 150853 0.61 66
- // 672 | 149602 0.33 12 | 150110 0.66 90
- // 717 | 149998 0.35 12 | 149531 0.70 129
- // 762 | 149836 0.37 13 | 148559 0.74 190
- // 807 | 149736 0.39 14 | 151107 0.39 14
- // 852 | 150204 0.42 15 | 151019 0.42 15
- drop_deletes_without_resize();
- } else {
- // Otherwise grow the container.
- resize(capacity_ * 2 + 1);
- }
- }
-
- bool has_element(const value_type& elem) const {
- size_t hash = PolicyTraits::apply(HashElement{hash_ref()}, elem);
- auto seq = probe(ctrl_, hash, capacity_);
- while (true) {
- Group g{ctrl_ + seq.offset()};
- for (uint32_t i : g.Match(H2(hash))) {
- if (ABSL_PREDICT_TRUE(PolicyTraits::element(slots_ + seq.offset(i)) ==
- elem))
- return true;
- }
- if (ABSL_PREDICT_TRUE(g.MaskEmpty())) return false;
- seq.next();
- assert(seq.index() <= capacity_ && "full table!");
- }
- return false;
- }
-
- // TODO(alkis): Optimize this assuming *this and that don't overlap.
- raw_hash_set& move_assign(raw_hash_set&& that, std::true_type) {
- raw_hash_set tmp(std::move(that));
- swap(tmp);
- return *this;
- }
- raw_hash_set& move_assign(raw_hash_set&& that, std::false_type) {
- raw_hash_set tmp(std::move(that), alloc_ref());
- swap(tmp);
- return *this;
- }
-
- protected:
- // Attempts to find `key` in the table; if it isn't found, returns a slot that
- // the value can be inserted into, with the control byte already set to
- // `key`'s H2.
- template <class K>
- std::pair<size_t, bool> find_or_prepare_insert(const K& key) {
- prefetch_heap_block();
- auto hash = hash_ref()(key);
- auto seq = probe(ctrl_, hash, capacity_);
- while (true) {
- Group g{ctrl_ + seq.offset()};
- for (uint32_t i : g.Match(H2(hash))) {
- if (ABSL_PREDICT_TRUE(PolicyTraits::apply(
- EqualElement<K>{key, eq_ref()},
- PolicyTraits::element(slots_ + seq.offset(i)))))
- return {seq.offset(i), false};
- }
- if (ABSL_PREDICT_TRUE(g.MaskEmpty())) break;
- seq.next();
- assert(seq.index() <= capacity_ && "full table!");
- }
- return {prepare_insert(hash), true};
- }
-
- // Given the hash of a value not currently in the table, finds the next
- // viable slot index to insert it at.
- //
- // REQUIRES: At least one non-full slot available.
- size_t prepare_insert(size_t hash) ABSL_ATTRIBUTE_NOINLINE {
- auto target = find_first_non_full(ctrl_, hash, capacity_);
- if (ABSL_PREDICT_FALSE(growth_left() == 0 &&
- !IsDeleted(ctrl_[target.offset]))) {
- rehash_and_grow_if_necessary();
- target = find_first_non_full(ctrl_, hash, capacity_);
- }
- ++size_;
- growth_left() -= IsEmpty(ctrl_[target.offset]);
- SetCtrl(target.offset, H2(hash), capacity_, ctrl_, slots_,
- sizeof(slot_type));
- infoz().RecordInsert(hash, target.probe_length);
- return target.offset;
- }
-
- // Constructs the value in the space pointed by the iterator. This only works
- // after an unsuccessful find_or_prepare_insert() and before any other
- // modifications happen in the raw_hash_set.
- //
- // PRECONDITION: i is an index returned from find_or_prepare_insert(k), where
- // k is the key decomposed from `forward<Args>(args)...`, and the bool
- // returned by find_or_prepare_insert(k) was true.
- // POSTCONDITION: *m.iterator_at(i) == value_type(forward<Args>(args)...).
- template <class... Args>
- void emplace_at(size_t i, Args&&... args) {
- PolicyTraits::construct(&alloc_ref(), slots_ + i,
- std::forward<Args>(args)...);
-
- assert(PolicyTraits::apply(FindElement{*this}, *iterator_at(i)) ==
- iterator_at(i) &&
- "constructed value does not match the lookup key");
- }
-
- iterator iterator_at(size_t i) { return {ctrl_ + i, slots_ + i}; }
- const_iterator iterator_at(size_t i) const { return {ctrl_ + i, slots_ + i}; }
-
- private:
- friend struct RawHashSetTestOnlyAccess;
-
- void reset_growth_left() {
- growth_left() = CapacityToGrowth(capacity()) - size_;
- }
-
- // The number of slots we can still fill without needing to rehash.
- //
- // This is stored separately due to tombstones: we do not include tombstones
- // in the growth capacity, because we'd like to rehash when the table is
- // otherwise filled with tombstones: otherwise, probe sequences might get
- // unacceptably long without triggering a rehash. Callers can also force a
- // rehash via the standard `rehash(0)`, which will recompute this value as a
- // side-effect.
- //
- // See `CapacityToGrowth()`.
- size_t& growth_left() { return settings_.template get<0>(); }
-
- // Prefetch the heap-allocated memory region to resolve potential TLB misses.
- // This is intended to overlap with execution of calculating the hash for a
- // key.
- void prefetch_heap_block() const {
- base_internal::PrefetchT2(ctrl_);
- }
-
- HashtablezInfoHandle& infoz() { return settings_.template get<1>(); }
-
- hasher& hash_ref() { return settings_.template get<2>(); }
- const hasher& hash_ref() const { return settings_.template get<2>(); }
- key_equal& eq_ref() { return settings_.template get<3>(); }
- const key_equal& eq_ref() const { return settings_.template get<3>(); }
- allocator_type& alloc_ref() { return settings_.template get<4>(); }
- const allocator_type& alloc_ref() const {
- return settings_.template get<4>();
- }
-
- // TODO(alkis): Investigate removing some of these fields:
- // - ctrl/slots can be derived from each other
- // - size can be moved into the slot array
-
- // The control bytes (and, also, a pointer to the base of the backing array).
- //
- // This contains `capacity_ + 1 + NumClonedBytes()` entries, even
- // when the table is empty (hence EmptyGroup).
- ctrl_t* ctrl_ = EmptyGroup();
- // The beginning of the slots, located at `SlotOffset()` bytes after
- // `ctrl_`. May be null for empty tables.
- slot_type* slots_ = nullptr;
-
- // The number of filled slots.
- size_t size_ = 0;
-
- // The total number of available slots.
- size_t capacity_ = 0;
- absl::container_internal::CompressedTuple<size_t /* growth_left */,
- HashtablezInfoHandle, hasher,
- key_equal, allocator_type>
- settings_{0u, HashtablezInfoHandle{}, hasher{}, key_equal{},
- allocator_type{}};
-};
-
-// Erases all elements that satisfy the predicate `pred` from the container `c`.
-template <typename P, typename H, typename E, typename A, typename Predicate>
-typename raw_hash_set<P, H, E, A>::size_type EraseIf(
- Predicate& pred, raw_hash_set<P, H, E, A>* c) {
- const auto initial_size = c->size();
- for (auto it = c->begin(), last = c->end(); it != last;) {
- if (pred(*it)) {
- c->erase(it++);
- } else {
- ++it;
- }
- }
- return initial_size - c->size();
-}
-
-namespace hashtable_debug_internal {
-template <typename Set>
-struct HashtableDebugAccess<Set, absl::void_t<typename Set::raw_hash_set>> {
- using Traits = typename Set::PolicyTraits;
- using Slot = typename Traits::slot_type;
-
- static size_t GetNumProbes(const Set& set,
- const typename Set::key_type& key) {
- size_t num_probes = 0;
- size_t hash = set.hash_ref()(key);
- auto seq = probe(set.ctrl_, hash, set.capacity_);
- while (true) {
- container_internal::Group g{set.ctrl_ + seq.offset()};
- for (uint32_t i : g.Match(container_internal::H2(hash))) {
- if (Traits::apply(
- typename Set::template EqualElement<typename Set::key_type>{
- key, set.eq_ref()},
- Traits::element(set.slots_ + seq.offset(i))))
- return num_probes;
- ++num_probes;
- }
- if (g.MaskEmpty()) return num_probes;
- seq.next();
- ++num_probes;
- }
- }
-
- static size_t AllocatedByteSize(const Set& c) {
- size_t capacity = c.capacity_;
- if (capacity == 0) return 0;
- size_t m = AllocSize(capacity, sizeof(Slot), alignof(Slot));
-
- size_t per_slot = Traits::space_used(static_cast<const Slot*>(nullptr));
- if (per_slot != ~size_t{}) {
- m += per_slot * c.size();
- } else {
- for (size_t i = 0; i != capacity; ++i) {
- if (container_internal::IsFull(c.ctrl_[i])) {
- m += Traits::space_used(c.slots_ + i);
- }
- }
- }
- return m;
- }
-
- static size_t LowerBoundAllocatedByteSize(size_t size) {
- size_t capacity = GrowthToLowerboundCapacity(size);
- if (capacity == 0) return 0;
- size_t m =
- AllocSize(NormalizeCapacity(capacity), sizeof(Slot), alignof(Slot));
- size_t per_slot = Traits::space_used(static_cast<const Slot*>(nullptr));
- if (per_slot != ~size_t{}) {
- m += per_slot * size;
- }
- return m;
- }
-};
-
-} // namespace hashtable_debug_internal
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#undef ABSL_INTERNAL_ASSERT_IS_FULL
-
-#endif // ABSL_CONTAINER_INTERNAL_RAW_HASH_SET_H_
diff --git a/third_party/abseil-cpp/absl/container/internal/raw_hash_set_allocator_test.cc b/third_party/abseil-cpp/absl/container/internal/raw_hash_set_allocator_test.cc
deleted file mode 100644
index e73f53f..0000000
--- a/third_party/abseil-cpp/absl/container/internal/raw_hash_set_allocator_test.cc
+++ /dev/null
@@ -1,505 +0,0 @@
-// Copyright 2018 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 <limits>
-#include <scoped_allocator>
-
-#include "gtest/gtest.h"
-#include "absl/container/internal/raw_hash_set.h"
-#include "absl/container/internal/tracked.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-namespace {
-
-enum AllocSpec {
- kPropagateOnCopy = 1,
- kPropagateOnMove = 2,
- kPropagateOnSwap = 4,
-};
-
-struct AllocState {
- size_t num_allocs = 0;
- std::set<void*> owned;
-};
-
-template <class T,
- int Spec = kPropagateOnCopy | kPropagateOnMove | kPropagateOnSwap>
-class CheckedAlloc {
- public:
- template <class, int>
- friend class CheckedAlloc;
-
- using value_type = T;
-
- CheckedAlloc() {}
- explicit CheckedAlloc(size_t id) : id_(id) {}
- CheckedAlloc(const CheckedAlloc&) = default;
- CheckedAlloc& operator=(const CheckedAlloc&) = default;
-
- template <class U>
- CheckedAlloc(const CheckedAlloc<U, Spec>& that)
- : id_(that.id_), state_(that.state_) {}
-
- template <class U>
- struct rebind {
- using other = CheckedAlloc<U, Spec>;
- };
-
- using propagate_on_container_copy_assignment =
- std::integral_constant<bool, (Spec & kPropagateOnCopy) != 0>;
-
- using propagate_on_container_move_assignment =
- std::integral_constant<bool, (Spec & kPropagateOnMove) != 0>;
-
- using propagate_on_container_swap =
- std::integral_constant<bool, (Spec & kPropagateOnSwap) != 0>;
-
- CheckedAlloc select_on_container_copy_construction() const {
- if (Spec & kPropagateOnCopy) return *this;
- return {};
- }
-
- T* allocate(size_t n) {
- T* ptr = std::allocator<T>().allocate(n);
- track_alloc(ptr);
- return ptr;
- }
- void deallocate(T* ptr, size_t n) {
- memset(ptr, 0, n * sizeof(T)); // The freed memory must be unpoisoned.
- track_dealloc(ptr);
- return std::allocator<T>().deallocate(ptr, n);
- }
-
- friend bool operator==(const CheckedAlloc& a, const CheckedAlloc& b) {
- return a.id_ == b.id_;
- }
- friend bool operator!=(const CheckedAlloc& a, const CheckedAlloc& b) {
- return !(a == b);
- }
-
- size_t num_allocs() const { return state_->num_allocs; }
-
- void swap(CheckedAlloc& that) {
- using std::swap;
- swap(id_, that.id_);
- swap(state_, that.state_);
- }
-
- friend void swap(CheckedAlloc& a, CheckedAlloc& b) { a.swap(b); }
-
- friend std::ostream& operator<<(std::ostream& o, const CheckedAlloc& a) {
- return o << "alloc(" << a.id_ << ")";
- }
-
- private:
- void track_alloc(void* ptr) {
- AllocState* state = state_.get();
- ++state->num_allocs;
- if (!state->owned.insert(ptr).second)
- ADD_FAILURE() << *this << " got previously allocated memory: " << ptr;
- }
- void track_dealloc(void* ptr) {
- if (state_->owned.erase(ptr) != 1)
- ADD_FAILURE() << *this
- << " deleting memory owned by another allocator: " << ptr;
- }
-
- size_t id_ = std::numeric_limits<size_t>::max();
-
- std::shared_ptr<AllocState> state_ = std::make_shared<AllocState>();
-};
-
-struct Identity {
- int32_t operator()(int32_t v) const { return v; }
-};
-
-struct Policy {
- using slot_type = Tracked<int32_t>;
- using init_type = Tracked<int32_t>;
- using key_type = int32_t;
-
- template <class allocator_type, class... Args>
- static void construct(allocator_type* alloc, slot_type* slot,
- Args&&... args) {
- std::allocator_traits<allocator_type>::construct(
- *alloc, slot, std::forward<Args>(args)...);
- }
-
- template <class allocator_type>
- static void destroy(allocator_type* alloc, slot_type* slot) {
- std::allocator_traits<allocator_type>::destroy(*alloc, slot);
- }
-
- template <class allocator_type>
- static void transfer(allocator_type* alloc, slot_type* new_slot,
- slot_type* old_slot) {
- construct(alloc, new_slot, std::move(*old_slot));
- destroy(alloc, old_slot);
- }
-
- template <class F>
- static auto apply(F&& f, int32_t v) -> decltype(std::forward<F>(f)(v, v)) {
- return std::forward<F>(f)(v, v);
- }
-
- template <class F>
- static auto apply(F&& f, const slot_type& v)
- -> decltype(std::forward<F>(f)(v.val(), v)) {
- return std::forward<F>(f)(v.val(), v);
- }
-
- template <class F>
- static auto apply(F&& f, slot_type&& v)
- -> decltype(std::forward<F>(f)(v.val(), std::move(v))) {
- return std::forward<F>(f)(v.val(), std::move(v));
- }
-
- static slot_type& element(slot_type* slot) { return *slot; }
-};
-
-template <int Spec>
-struct PropagateTest : public ::testing::Test {
- using Alloc = CheckedAlloc<Tracked<int32_t>, Spec>;
-
- using Table = raw_hash_set<Policy, Identity, std::equal_to<int32_t>, Alloc>;
-
- PropagateTest() {
- EXPECT_EQ(a1, t1.get_allocator());
- EXPECT_NE(a2, t1.get_allocator());
- }
-
- Alloc a1 = Alloc(1);
- Table t1 = Table(0, a1);
- Alloc a2 = Alloc(2);
-};
-
-using PropagateOnAll =
- PropagateTest<kPropagateOnCopy | kPropagateOnMove | kPropagateOnSwap>;
-using NoPropagateOnCopy = PropagateTest<kPropagateOnMove | kPropagateOnSwap>;
-using NoPropagateOnMove = PropagateTest<kPropagateOnCopy | kPropagateOnSwap>;
-
-TEST_F(PropagateOnAll, Empty) { EXPECT_EQ(0, a1.num_allocs()); }
-
-TEST_F(PropagateOnAll, InsertAllocates) {
- auto it = t1.insert(0).first;
- EXPECT_EQ(1, a1.num_allocs());
- EXPECT_EQ(0, it->num_moves());
- EXPECT_EQ(0, it->num_copies());
-}
-
-TEST_F(PropagateOnAll, InsertDecomposes) {
- auto it = t1.insert(0).first;
- EXPECT_EQ(1, a1.num_allocs());
- EXPECT_EQ(0, it->num_moves());
- EXPECT_EQ(0, it->num_copies());
-
- EXPECT_FALSE(t1.insert(0).second);
- EXPECT_EQ(1, a1.num_allocs());
- EXPECT_EQ(0, it->num_moves());
- EXPECT_EQ(0, it->num_copies());
-}
-
-TEST_F(PropagateOnAll, RehashMoves) {
- auto it = t1.insert(0).first;
- EXPECT_EQ(0, it->num_moves());
- t1.rehash(2 * t1.capacity());
- EXPECT_EQ(2, a1.num_allocs());
- it = t1.find(0);
- EXPECT_EQ(1, it->num_moves());
- EXPECT_EQ(0, it->num_copies());
-}
-
-TEST_F(PropagateOnAll, CopyConstructor) {
- auto it = t1.insert(0).first;
- Table u(t1);
- EXPECT_EQ(2, a1.num_allocs());
- EXPECT_EQ(0, it->num_moves());
- EXPECT_EQ(1, it->num_copies());
-}
-
-TEST_F(NoPropagateOnCopy, CopyConstructor) {
- auto it = t1.insert(0).first;
- Table u(t1);
- EXPECT_EQ(1, a1.num_allocs());
- EXPECT_EQ(1, u.get_allocator().num_allocs());
- EXPECT_EQ(0, it->num_moves());
- EXPECT_EQ(1, it->num_copies());
-}
-
-TEST_F(PropagateOnAll, CopyConstructorWithSameAlloc) {
- auto it = t1.insert(0).first;
- Table u(t1, a1);
- EXPECT_EQ(2, a1.num_allocs());
- EXPECT_EQ(0, it->num_moves());
- EXPECT_EQ(1, it->num_copies());
-}
-
-TEST_F(NoPropagateOnCopy, CopyConstructorWithSameAlloc) {
- auto it = t1.insert(0).first;
- Table u(t1, a1);
- EXPECT_EQ(2, a1.num_allocs());
- EXPECT_EQ(0, it->num_moves());
- EXPECT_EQ(1, it->num_copies());
-}
-
-TEST_F(PropagateOnAll, CopyConstructorWithDifferentAlloc) {
- auto it = t1.insert(0).first;
- Table u(t1, a2);
- EXPECT_EQ(a2, u.get_allocator());
- EXPECT_EQ(1, a1.num_allocs());
- EXPECT_EQ(1, a2.num_allocs());
- EXPECT_EQ(0, it->num_moves());
- EXPECT_EQ(1, it->num_copies());
-}
-
-TEST_F(NoPropagateOnCopy, CopyConstructorWithDifferentAlloc) {
- auto it = t1.insert(0).first;
- Table u(t1, a2);
- EXPECT_EQ(a2, u.get_allocator());
- EXPECT_EQ(1, a1.num_allocs());
- EXPECT_EQ(1, a2.num_allocs());
- EXPECT_EQ(0, it->num_moves());
- EXPECT_EQ(1, it->num_copies());
-}
-
-TEST_F(PropagateOnAll, MoveConstructor) {
- auto it = t1.insert(0).first;
- Table u(std::move(t1));
- EXPECT_EQ(1, a1.num_allocs());
- EXPECT_EQ(0, it->num_moves());
- EXPECT_EQ(0, it->num_copies());
-}
-
-TEST_F(NoPropagateOnMove, MoveConstructor) {
- auto it = t1.insert(0).first;
- Table u(std::move(t1));
- EXPECT_EQ(1, a1.num_allocs());
- EXPECT_EQ(0, it->num_moves());
- EXPECT_EQ(0, it->num_copies());
-}
-
-TEST_F(PropagateOnAll, MoveConstructorWithSameAlloc) {
- auto it = t1.insert(0).first;
- Table u(std::move(t1), a1);
- EXPECT_EQ(1, a1.num_allocs());
- EXPECT_EQ(0, it->num_moves());
- EXPECT_EQ(0, it->num_copies());
-}
-
-TEST_F(NoPropagateOnMove, MoveConstructorWithSameAlloc) {
- auto it = t1.insert(0).first;
- Table u(std::move(t1), a1);
- EXPECT_EQ(1, a1.num_allocs());
- EXPECT_EQ(0, it->num_moves());
- EXPECT_EQ(0, it->num_copies());
-}
-
-TEST_F(PropagateOnAll, MoveConstructorWithDifferentAlloc) {
- auto it = t1.insert(0).first;
- Table u(std::move(t1), a2);
- it = u.find(0);
- EXPECT_EQ(a2, u.get_allocator());
- EXPECT_EQ(1, a1.num_allocs());
- EXPECT_EQ(1, a2.num_allocs());
- EXPECT_EQ(1, it->num_moves());
- EXPECT_EQ(0, it->num_copies());
-}
-
-TEST_F(NoPropagateOnMove, MoveConstructorWithDifferentAlloc) {
- auto it = t1.insert(0).first;
- Table u(std::move(t1), a2);
- it = u.find(0);
- EXPECT_EQ(a2, u.get_allocator());
- EXPECT_EQ(1, a1.num_allocs());
- EXPECT_EQ(1, a2.num_allocs());
- EXPECT_EQ(1, it->num_moves());
- EXPECT_EQ(0, it->num_copies());
-}
-
-TEST_F(PropagateOnAll, CopyAssignmentWithSameAlloc) {
- auto it = t1.insert(0).first;
- Table u(0, a1);
- u = t1;
- EXPECT_EQ(2, a1.num_allocs());
- EXPECT_EQ(0, it->num_moves());
- EXPECT_EQ(1, it->num_copies());
-}
-
-TEST_F(NoPropagateOnCopy, CopyAssignmentWithSameAlloc) {
- auto it = t1.insert(0).first;
- Table u(0, a1);
- u = t1;
- EXPECT_EQ(2, a1.num_allocs());
- EXPECT_EQ(0, it->num_moves());
- EXPECT_EQ(1, it->num_copies());
-}
-
-TEST_F(PropagateOnAll, CopyAssignmentWithDifferentAlloc) {
- auto it = t1.insert(0).first;
- Table u(0, a2);
- u = t1;
- EXPECT_EQ(a1, u.get_allocator());
- EXPECT_EQ(2, a1.num_allocs());
- EXPECT_EQ(0, a2.num_allocs());
- EXPECT_EQ(0, it->num_moves());
- EXPECT_EQ(1, it->num_copies());
-}
-
-TEST_F(NoPropagateOnCopy, CopyAssignmentWithDifferentAlloc) {
- auto it = t1.insert(0).first;
- Table u(0, a2);
- u = t1;
- EXPECT_EQ(a2, u.get_allocator());
- EXPECT_EQ(1, a1.num_allocs());
- EXPECT_EQ(1, a2.num_allocs());
- EXPECT_EQ(0, it->num_moves());
- EXPECT_EQ(1, it->num_copies());
-}
-
-TEST_F(PropagateOnAll, MoveAssignmentWithSameAlloc) {
- auto it = t1.insert(0).first;
- Table u(0, a1);
- u = std::move(t1);
- EXPECT_EQ(a1, u.get_allocator());
- EXPECT_EQ(1, a1.num_allocs());
- EXPECT_EQ(0, it->num_moves());
- EXPECT_EQ(0, it->num_copies());
-}
-
-TEST_F(NoPropagateOnMove, MoveAssignmentWithSameAlloc) {
- auto it = t1.insert(0).first;
- Table u(0, a1);
- u = std::move(t1);
- EXPECT_EQ(a1, u.get_allocator());
- EXPECT_EQ(1, a1.num_allocs());
- EXPECT_EQ(0, it->num_moves());
- EXPECT_EQ(0, it->num_copies());
-}
-
-TEST_F(PropagateOnAll, MoveAssignmentWithDifferentAlloc) {
- auto it = t1.insert(0).first;
- Table u(0, a2);
- u = std::move(t1);
- EXPECT_EQ(a1, u.get_allocator());
- EXPECT_EQ(1, a1.num_allocs());
- EXPECT_EQ(0, a2.num_allocs());
- EXPECT_EQ(0, it->num_moves());
- EXPECT_EQ(0, it->num_copies());
-}
-
-TEST_F(NoPropagateOnMove, MoveAssignmentWithDifferentAlloc) {
- auto it = t1.insert(0).first;
- Table u(0, a2);
- u = std::move(t1);
- it = u.find(0);
- EXPECT_EQ(a2, u.get_allocator());
- EXPECT_EQ(1, a1.num_allocs());
- EXPECT_EQ(1, a2.num_allocs());
- EXPECT_EQ(1, it->num_moves());
- EXPECT_EQ(0, it->num_copies());
-}
-
-TEST_F(PropagateOnAll, Swap) {
- auto it = t1.insert(0).first;
- Table u(0, a2);
- u.swap(t1);
- EXPECT_EQ(a1, u.get_allocator());
- EXPECT_EQ(a2, t1.get_allocator());
- EXPECT_EQ(1, a1.num_allocs());
- EXPECT_EQ(0, a2.num_allocs());
- EXPECT_EQ(0, it->num_moves());
- EXPECT_EQ(0, it->num_copies());
-}
-
-// This allocator is similar to std::pmr::polymorphic_allocator.
-// Note the disabled assignment.
-template <class T>
-class PAlloc {
- template <class>
- friend class PAlloc;
-
- public:
- // types
- using value_type = T;
-
- // traits
- using propagate_on_container_swap = std::false_type;
-
- PAlloc() noexcept = default;
- explicit PAlloc(size_t id) noexcept : id_(id) {}
- PAlloc(const PAlloc&) noexcept = default;
- PAlloc& operator=(const PAlloc&) noexcept = delete;
-
- template <class U>
- PAlloc(const PAlloc<U>& that) noexcept : id_(that.id_) {} // NOLINT
-
- template <class U>
- struct rebind {
- using other = PAlloc<U>;
- };
-
- constexpr PAlloc select_on_container_copy_construction() const { return {}; }
-
- // public member functions
- T* allocate(size_t) { return new T; }
- void deallocate(T* p, size_t) { delete p; }
-
- friend bool operator==(const PAlloc& a, const PAlloc& b) {
- return a.id_ == b.id_;
- }
- friend bool operator!=(const PAlloc& a, const PAlloc& b) { return !(a == b); }
-
- private:
- size_t id_ = std::numeric_limits<size_t>::max();
-};
-
-// This doesn't compile with GCC 5.4 and 5.5 due to a bug in noexcept handing.
-#if !defined(__GNUC__) || __GNUC__ != 5 || (__GNUC_MINOR__ != 4 && \
- __GNUC_MINOR__ != 5)
-TEST(NoPropagateOn, Swap) {
- using PA = PAlloc<char>;
- using Table = raw_hash_set<Policy, Identity, std::equal_to<int32_t>, PA>;
-
- Table t1(PA{1}), t2(PA{2});
- swap(t1, t2);
- EXPECT_EQ(t1.get_allocator(), PA(1));
- EXPECT_EQ(t2.get_allocator(), PA(2));
-}
-#endif
-
-TEST(NoPropagateOn, CopyConstruct) {
- using PA = PAlloc<char>;
- using Table = raw_hash_set<Policy, Identity, std::equal_to<int32_t>, PA>;
-
- Table t1(PA{1}), t2(t1);
- EXPECT_EQ(t1.get_allocator(), PA(1));
- EXPECT_EQ(t2.get_allocator(), PA());
-}
-
-TEST(NoPropagateOn, Assignment) {
- using PA = PAlloc<char>;
- using Table = raw_hash_set<Policy, Identity, std::equal_to<int32_t>, PA>;
-
- Table t1(PA{1}), t2(PA{2});
- t1 = t2;
- EXPECT_EQ(t1.get_allocator(), PA(1));
- EXPECT_EQ(t2.get_allocator(), PA(2));
-}
-
-} // namespace
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/container/internal/raw_hash_set_benchmark.cc b/third_party/abseil-cpp/absl/container/internal/raw_hash_set_benchmark.cc
deleted file mode 100644
index e17ba9b..0000000
--- a/third_party/abseil-cpp/absl/container/internal/raw_hash_set_benchmark.cc
+++ /dev/null
@@ -1,518 +0,0 @@
-// Copyright 2018 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 <array>
-#include <cmath>
-#include <numeric>
-#include <random>
-#include <utility>
-#include <vector>
-
-#include "absl/base/internal/raw_logging.h"
-#include "absl/container/internal/hash_function_defaults.h"
-#include "absl/container/internal/raw_hash_set.h"
-#include "absl/strings/str_format.h"
-#include "benchmark/benchmark.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-
-struct RawHashSetTestOnlyAccess {
- template <typename C>
- static auto GetSlots(const C& c) -> decltype(c.slots_) {
- return c.slots_;
- }
-};
-
-namespace {
-
-struct IntPolicy {
- using slot_type = int64_t;
- using key_type = int64_t;
- using init_type = int64_t;
-
- static void construct(void*, int64_t* slot, int64_t v) { *slot = v; }
- static void destroy(void*, int64_t*) {}
- static void transfer(void*, int64_t* new_slot, int64_t* old_slot) {
- *new_slot = *old_slot;
- }
-
- static int64_t& element(slot_type* slot) { return *slot; }
-
- template <class F>
- static auto apply(F&& f, int64_t x) -> decltype(std::forward<F>(f)(x, x)) {
- return std::forward<F>(f)(x, x);
- }
-};
-
-class StringPolicy {
- template <class F, class K, class V,
- class = typename std::enable_if<
- std::is_convertible<const K&, absl::string_view>::value>::type>
- decltype(std::declval<F>()(
- std::declval<const absl::string_view&>(), std::piecewise_construct,
- std::declval<std::tuple<K>>(),
- std::declval<V>())) static apply_impl(F&& f,
- std::pair<std::tuple<K>, V> p) {
- const absl::string_view& key = std::get<0>(p.first);
- return std::forward<F>(f)(key, std::piecewise_construct, std::move(p.first),
- std::move(p.second));
- }
-
- public:
- struct slot_type {
- struct ctor {};
-
- template <class... Ts>
- slot_type(ctor, Ts&&... ts) : pair(std::forward<Ts>(ts)...) {}
-
- std::pair<std::string, std::string> pair;
- };
-
- using key_type = std::string;
- using init_type = std::pair<std::string, std::string>;
-
- template <class allocator_type, class... Args>
- static void construct(allocator_type* alloc, slot_type* slot, Args... args) {
- std::allocator_traits<allocator_type>::construct(
- *alloc, slot, typename slot_type::ctor(), std::forward<Args>(args)...);
- }
-
- template <class allocator_type>
- static void destroy(allocator_type* alloc, slot_type* slot) {
- std::allocator_traits<allocator_type>::destroy(*alloc, slot);
- }
-
- template <class allocator_type>
- static void transfer(allocator_type* alloc, slot_type* new_slot,
- slot_type* old_slot) {
- construct(alloc, new_slot, std::move(old_slot->pair));
- destroy(alloc, old_slot);
- }
-
- static std::pair<std::string, std::string>& element(slot_type* slot) {
- return slot->pair;
- }
-
- template <class F, class... Args>
- static auto apply(F&& f, Args&&... args)
- -> decltype(apply_impl(std::forward<F>(f),
- PairArgs(std::forward<Args>(args)...))) {
- return apply_impl(std::forward<F>(f),
- PairArgs(std::forward<Args>(args)...));
- }
-};
-
-struct StringHash : container_internal::hash_default_hash<absl::string_view> {
- using is_transparent = void;
-};
-struct StringEq : std::equal_to<absl::string_view> {
- using is_transparent = void;
-};
-
-struct StringTable
- : raw_hash_set<StringPolicy, StringHash, StringEq, std::allocator<int>> {
- using Base = typename StringTable::raw_hash_set;
- StringTable() {}
- using Base::Base;
-};
-
-struct IntTable
- : raw_hash_set<IntPolicy, container_internal::hash_default_hash<int64_t>,
- std::equal_to<int64_t>, std::allocator<int64_t>> {
- using Base = typename IntTable::raw_hash_set;
- IntTable() {}
- using Base::Base;
-};
-
-struct string_generator {
- template <class RNG>
- std::string operator()(RNG& rng) const {
- std::string res;
- res.resize(12);
- std::uniform_int_distribution<uint32_t> printable_ascii(0x20, 0x7E);
- std::generate(res.begin(), res.end(), [&] { return printable_ascii(rng); });
- return res;
- }
-
- size_t size;
-};
-
-// Model a cache in steady state.
-//
-// On a table of size N, keep deleting the LRU entry and add a random one.
-void BM_CacheInSteadyState(benchmark::State& state) {
- std::random_device rd;
- std::mt19937 rng(rd());
- string_generator gen{12};
- StringTable t;
- std::deque<std::string> keys;
- while (t.size() < state.range(0)) {
- auto x = t.emplace(gen(rng), gen(rng));
- if (x.second) keys.push_back(x.first->first);
- }
- ABSL_RAW_CHECK(state.range(0) >= 10, "");
- while (state.KeepRunning()) {
- // Some cache hits.
- std::deque<std::string>::const_iterator it;
- for (int i = 0; i != 90; ++i) {
- if (i % 10 == 0) it = keys.end();
- ::benchmark::DoNotOptimize(t.find(*--it));
- }
- // Some cache misses.
- for (int i = 0; i != 10; ++i) ::benchmark::DoNotOptimize(t.find(gen(rng)));
- ABSL_RAW_CHECK(t.erase(keys.front()), keys.front().c_str());
- keys.pop_front();
- while (true) {
- auto x = t.emplace(gen(rng), gen(rng));
- if (x.second) {
- keys.push_back(x.first->first);
- break;
- }
- }
- }
- state.SetItemsProcessed(state.iterations());
- state.SetLabel(absl::StrFormat("load_factor=%.2f", t.load_factor()));
-}
-
-template <typename Benchmark>
-void CacheInSteadyStateArgs(Benchmark* bm) {
- // The default.
- const float max_load_factor = 0.875;
- // When the cache is at the steady state, the probe sequence will equal
- // capacity if there is no reclamation of deleted slots. Pick a number large
- // enough to make the benchmark slow for that case.
- const size_t capacity = 1 << 10;
-
- // Check N data points to cover load factors in [0.4, 0.8).
- const size_t kNumPoints = 10;
- for (size_t i = 0; i != kNumPoints; ++i)
- bm->Arg(std::ceil(
- capacity * (max_load_factor + i * max_load_factor / kNumPoints) / 2));
-}
-BENCHMARK(BM_CacheInSteadyState)->Apply(CacheInSteadyStateArgs);
-
-void BM_EndComparison(benchmark::State& state) {
- StringTable t = {{"a", "a"}, {"b", "b"}};
- auto it = t.begin();
- for (auto i : state) {
- benchmark::DoNotOptimize(t);
- benchmark::DoNotOptimize(it);
- benchmark::DoNotOptimize(it != t.end());
- }
-}
-BENCHMARK(BM_EndComparison);
-
-void BM_Iteration(benchmark::State& state) {
- std::random_device rd;
- std::mt19937 rng(rd());
- string_generator gen{12};
- StringTable t;
-
- size_t capacity = state.range(0);
- size_t size = state.range(1);
- t.reserve(capacity);
-
- while (t.size() < size) {
- t.emplace(gen(rng), gen(rng));
- }
-
- for (auto i : state) {
- benchmark::DoNotOptimize(t);
- for (auto it = t.begin(); it != t.end(); ++it) {
- benchmark::DoNotOptimize(*it);
- }
- }
-}
-
-BENCHMARK(BM_Iteration)
- ->ArgPair(1, 1)
- ->ArgPair(2, 2)
- ->ArgPair(4, 4)
- ->ArgPair(7, 7)
- ->ArgPair(10, 10)
- ->ArgPair(15, 15)
- ->ArgPair(16, 16)
- ->ArgPair(54, 54)
- ->ArgPair(100, 100)
- ->ArgPair(400, 400)
- // empty
- ->ArgPair(0, 0)
- ->ArgPair(10, 0)
- ->ArgPair(100, 0)
- ->ArgPair(1000, 0)
- ->ArgPair(10000, 0)
- // sparse
- ->ArgPair(100, 1)
- ->ArgPair(1000, 10);
-
-void BM_CopyCtorSparseInt(benchmark::State& state) {
- std::random_device rd;
- std::mt19937 rng(rd());
- IntTable t;
- std::uniform_int_distribution<uint64_t> dist(0, ~uint64_t{});
-
- size_t size = state.range(0);
- t.reserve(size * 10);
- while (t.size() < size) {
- t.emplace(dist(rng));
- }
-
- for (auto i : state) {
- IntTable t2 = t;
- benchmark::DoNotOptimize(t2);
- }
-}
-BENCHMARK(BM_CopyCtorSparseInt)->Range(128, 4096);
-
-void BM_CopyCtorInt(benchmark::State& state) {
- std::random_device rd;
- std::mt19937 rng(rd());
- IntTable t;
- std::uniform_int_distribution<uint64_t> dist(0, ~uint64_t{});
-
- size_t size = state.range(0);
- while (t.size() < size) {
- t.emplace(dist(rng));
- }
-
- for (auto i : state) {
- IntTable t2 = t;
- benchmark::DoNotOptimize(t2);
- }
-}
-BENCHMARK(BM_CopyCtorInt)->Range(128, 4096);
-
-void BM_CopyCtorString(benchmark::State& state) {
- std::random_device rd;
- std::mt19937 rng(rd());
- StringTable t;
- std::uniform_int_distribution<uint64_t> dist(0, ~uint64_t{});
-
- size_t size = state.range(0);
- while (t.size() < size) {
- t.emplace(std::to_string(dist(rng)), std::to_string(dist(rng)));
- }
-
- for (auto i : state) {
- StringTable t2 = t;
- benchmark::DoNotOptimize(t2);
- }
-}
-BENCHMARK(BM_CopyCtorString)->Range(128, 4096);
-
-void BM_CopyAssign(benchmark::State& state) {
- std::random_device rd;
- std::mt19937 rng(rd());
- IntTable t;
- std::uniform_int_distribution<uint64_t> dist(0, ~uint64_t{});
- while (t.size() < state.range(0)) {
- t.emplace(dist(rng));
- }
-
- IntTable t2;
- for (auto _ : state) {
- t2 = t;
- benchmark::DoNotOptimize(t2);
- }
-}
-BENCHMARK(BM_CopyAssign)->Range(128, 4096);
-
-void BM_RangeCtor(benchmark::State& state) {
- std::random_device rd;
- std::mt19937 rng(rd());
- std::uniform_int_distribution<uint64_t> dist(0, ~uint64_t{});
- std::vector<int> values;
- const size_t desired_size = state.range(0);
- while (values.size() < desired_size) {
- values.emplace_back(dist(rng));
- }
-
- for (auto unused : state) {
- IntTable t{values.begin(), values.end()};
- benchmark::DoNotOptimize(t);
- }
-}
-BENCHMARK(BM_RangeCtor)->Range(128, 65536);
-
-void BM_NoOpReserveIntTable(benchmark::State& state) {
- IntTable t;
- t.reserve(100000);
- for (auto _ : state) {
- benchmark::DoNotOptimize(t);
- t.reserve(100000);
- }
-}
-BENCHMARK(BM_NoOpReserveIntTable);
-
-void BM_NoOpReserveStringTable(benchmark::State& state) {
- StringTable t;
- t.reserve(100000);
- for (auto _ : state) {
- benchmark::DoNotOptimize(t);
- t.reserve(100000);
- }
-}
-BENCHMARK(BM_NoOpReserveStringTable);
-
-void BM_ReserveIntTable(benchmark::State& state) {
- int reserve_size = state.range(0);
- for (auto _ : state) {
- state.PauseTiming();
- IntTable t;
- state.ResumeTiming();
- benchmark::DoNotOptimize(t);
- t.reserve(reserve_size);
- }
-}
-BENCHMARK(BM_ReserveIntTable)->Range(128, 4096);
-
-void BM_ReserveStringTable(benchmark::State& state) {
- int reserve_size = state.range(0);
- for (auto _ : state) {
- state.PauseTiming();
- StringTable t;
- state.ResumeTiming();
- benchmark::DoNotOptimize(t);
- t.reserve(reserve_size);
- }
-}
-BENCHMARK(BM_ReserveStringTable)->Range(128, 4096);
-
-// Like std::iota, except that ctrl_t doesn't support operator++.
-template <typename CtrlIter>
-void Iota(CtrlIter begin, CtrlIter end, int value) {
- for (; begin != end; ++begin, ++value) {
- *begin = static_cast<ctrl_t>(value);
- }
-}
-
-void BM_Group_Match(benchmark::State& state) {
- std::array<ctrl_t, Group::kWidth> group;
- Iota(group.begin(), group.end(), -4);
- Group g{group.data()};
- h2_t h = 1;
- for (auto _ : state) {
- ::benchmark::DoNotOptimize(h);
- ::benchmark::DoNotOptimize(g);
- ::benchmark::DoNotOptimize(g.Match(h));
- }
-}
-BENCHMARK(BM_Group_Match);
-
-void BM_Group_MaskEmpty(benchmark::State& state) {
- std::array<ctrl_t, Group::kWidth> group;
- Iota(group.begin(), group.end(), -4);
- Group g{group.data()};
- for (auto _ : state) {
- ::benchmark::DoNotOptimize(g);
- ::benchmark::DoNotOptimize(g.MaskEmpty());
- }
-}
-BENCHMARK(BM_Group_MaskEmpty);
-
-void BM_Group_MaskEmptyOrDeleted(benchmark::State& state) {
- std::array<ctrl_t, Group::kWidth> group;
- Iota(group.begin(), group.end(), -4);
- Group g{group.data()};
- for (auto _ : state) {
- ::benchmark::DoNotOptimize(g);
- ::benchmark::DoNotOptimize(g.MaskEmptyOrDeleted());
- }
-}
-BENCHMARK(BM_Group_MaskEmptyOrDeleted);
-
-void BM_Group_CountLeadingEmptyOrDeleted(benchmark::State& state) {
- std::array<ctrl_t, Group::kWidth> group;
- Iota(group.begin(), group.end(), -2);
- Group g{group.data()};
- for (auto _ : state) {
- ::benchmark::DoNotOptimize(g);
- ::benchmark::DoNotOptimize(g.CountLeadingEmptyOrDeleted());
- }
-}
-BENCHMARK(BM_Group_CountLeadingEmptyOrDeleted);
-
-void BM_Group_MatchFirstEmptyOrDeleted(benchmark::State& state) {
- std::array<ctrl_t, Group::kWidth> group;
- Iota(group.begin(), group.end(), -2);
- Group g{group.data()};
- for (auto _ : state) {
- ::benchmark::DoNotOptimize(g);
- ::benchmark::DoNotOptimize(g.MaskEmptyOrDeleted().LowestBitSet());
- }
-}
-BENCHMARK(BM_Group_MatchFirstEmptyOrDeleted);
-
-void BM_DropDeletes(benchmark::State& state) {
- constexpr size_t capacity = (1 << 20) - 1;
- std::vector<ctrl_t> ctrl(capacity + 1 + Group::kWidth);
- ctrl[capacity] = ctrl_t::kSentinel;
- std::vector<ctrl_t> pattern = {ctrl_t::kEmpty, static_cast<ctrl_t>(2),
- ctrl_t::kDeleted, static_cast<ctrl_t>(2),
- ctrl_t::kEmpty, static_cast<ctrl_t>(1),
- ctrl_t::kDeleted};
- for (size_t i = 0; i != capacity; ++i) {
- ctrl[i] = pattern[i % pattern.size()];
- }
- while (state.KeepRunning()) {
- state.PauseTiming();
- std::vector<ctrl_t> ctrl_copy = ctrl;
- state.ResumeTiming();
- ConvertDeletedToEmptyAndFullToDeleted(ctrl_copy.data(), capacity);
- ::benchmark::DoNotOptimize(ctrl_copy[capacity]);
- }
-}
-BENCHMARK(BM_DropDeletes);
-
-} // namespace
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-// These methods are here to make it easy to examine the assembly for targeted
-// parts of the API.
-auto CodegenAbslRawHashSetInt64Find(absl::container_internal::IntTable* table,
- int64_t key) -> decltype(table->find(key)) {
- return table->find(key);
-}
-
-bool CodegenAbslRawHashSetInt64FindNeEnd(
- absl::container_internal::IntTable* table, int64_t key) {
- return table->find(key) != table->end();
-}
-
-auto CodegenAbslRawHashSetInt64Insert(absl::container_internal::IntTable* table,
- int64_t key)
- -> decltype(table->insert(key)) {
- return table->insert(key);
-}
-
-bool CodegenAbslRawHashSetInt64Contains(
- absl::container_internal::IntTable* table, int64_t key) {
- return table->contains(key);
-}
-
-void CodegenAbslRawHashSetInt64Iterate(
- absl::container_internal::IntTable* table) {
- for (auto x : *table) benchmark::DoNotOptimize(x);
-}
-
-int odr =
- (::benchmark::DoNotOptimize(std::make_tuple(
- &CodegenAbslRawHashSetInt64Find, &CodegenAbslRawHashSetInt64FindNeEnd,
- &CodegenAbslRawHashSetInt64Insert, &CodegenAbslRawHashSetInt64Contains,
- &CodegenAbslRawHashSetInt64Iterate)),
- 1);
diff --git a/third_party/abseil-cpp/absl/container/internal/raw_hash_set_probe_benchmark.cc b/third_party/abseil-cpp/absl/container/internal/raw_hash_set_probe_benchmark.cc
deleted file mode 100644
index 7169a2e..0000000
--- a/third_party/abseil-cpp/absl/container/internal/raw_hash_set_probe_benchmark.cc
+++ /dev/null
@@ -1,590 +0,0 @@
-// Copyright 2018 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.
-//
-// Generates probe length statistics for many combinations of key types and key
-// distributions, all using the default hash function for swisstable.
-
-#include <memory>
-#include <regex> // NOLINT
-#include <vector>
-
-#include "absl/container/flat_hash_map.h"
-#include "absl/container/internal/hash_function_defaults.h"
-#include "absl/container/internal/hashtable_debug.h"
-#include "absl/container/internal/raw_hash_set.h"
-#include "absl/random/distributions.h"
-#include "absl/random/random.h"
-#include "absl/strings/str_cat.h"
-#include "absl/strings/str_format.h"
-#include "absl/strings/string_view.h"
-#include "absl/strings/strip.h"
-
-namespace {
-
-enum class OutputStyle { kRegular, kBenchmark };
-
-// The --benchmark command line flag.
-// This is populated from main().
-// When run in "benchmark" mode, we have different output. This allows
-// A/B comparisons with tools like `benchy`.
-absl::string_view benchmarks;
-
-OutputStyle output() {
- return !benchmarks.empty() ? OutputStyle::kBenchmark : OutputStyle::kRegular;
-}
-
-template <class T>
-struct Policy {
- using slot_type = T;
- using key_type = T;
- using init_type = T;
-
- template <class allocator_type, class Arg>
- static void construct(allocator_type* alloc, slot_type* slot,
- const Arg& arg) {
- std::allocator_traits<allocator_type>::construct(*alloc, slot, arg);
- }
-
- template <class allocator_type>
- static void destroy(allocator_type* alloc, slot_type* slot) {
- std::allocator_traits<allocator_type>::destroy(*alloc, slot);
- }
-
- static slot_type& element(slot_type* slot) { return *slot; }
-
- template <class F, class... Args>
- static auto apply(F&& f, const slot_type& arg)
- -> decltype(std::forward<F>(f)(arg, arg)) {
- return std::forward<F>(f)(arg, arg);
- }
-};
-
-absl::BitGen& GlobalBitGen() {
- static auto* value = new absl::BitGen;
- return *value;
-}
-
-// Keeps a pool of allocations and randomly gives one out.
-// This introduces more randomization to the addresses given to swisstable and
-// should help smooth out this factor from probe length calculation.
-template <class T>
-class RandomizedAllocator {
- public:
- using value_type = T;
-
- RandomizedAllocator() = default;
- template <typename U>
- RandomizedAllocator(RandomizedAllocator<U>) {} // NOLINT
-
- static T* allocate(size_t n) {
- auto& pointers = GetPointers(n);
- // Fill the pool
- while (pointers.size() < kRandomPool) {
- pointers.push_back(std::allocator<T>{}.allocate(n));
- }
-
- // Choose a random one.
- size_t i = absl::Uniform<size_t>(GlobalBitGen(), 0, pointers.size());
- T* result = pointers[i];
- pointers[i] = pointers.back();
- pointers.pop_back();
- return result;
- }
-
- static void deallocate(T* p, size_t n) {
- // Just put it back on the pool. No need to release the memory.
- GetPointers(n).push_back(p);
- }
-
- private:
- // We keep at least kRandomPool allocations for each size.
- static constexpr size_t kRandomPool = 20;
-
- static std::vector<T*>& GetPointers(size_t n) {
- static auto* m = new absl::flat_hash_map<size_t, std::vector<T*>>();
- return (*m)[n];
- }
-};
-
-template <class T>
-struct DefaultHash {
- using type = absl::container_internal::hash_default_hash<T>;
-};
-
-template <class T>
-using DefaultHashT = typename DefaultHash<T>::type;
-
-template <class T>
-struct Table : absl::container_internal::raw_hash_set<
- Policy<T>, DefaultHashT<T>,
- absl::container_internal::hash_default_eq<T>,
- RandomizedAllocator<T>> {};
-
-struct LoadSizes {
- size_t min_load;
- size_t max_load;
-};
-
-LoadSizes GetMinMaxLoadSizes() {
- static const auto sizes = [] {
- Table<int> t;
-
- // First, fill enough to have a good distribution.
- constexpr size_t kMinSize = 10000;
- while (t.size() < kMinSize) t.insert(t.size());
-
- const auto reach_min_load_factor = [&] {
- const double lf = t.load_factor();
- while (lf <= t.load_factor()) t.insert(t.size());
- };
-
- // Then, insert until we reach min load factor.
- reach_min_load_factor();
- const size_t min_load_size = t.size();
-
- // Keep going until we hit min load factor again, then go back one.
- t.insert(t.size());
- reach_min_load_factor();
-
- return LoadSizes{min_load_size, t.size() - 1};
- }();
- return sizes;
-}
-
-struct Ratios {
- double min_load;
- double avg_load;
- double max_load;
-};
-
-// See absl/container/internal/hashtable_debug.h for details on
-// probe length calculation.
-template <class ElemFn>
-Ratios CollectMeanProbeLengths() {
- const auto min_max_sizes = GetMinMaxLoadSizes();
-
- ElemFn elem;
- using Key = decltype(elem());
- Table<Key> t;
-
- Ratios result;
- while (t.size() < min_max_sizes.min_load) t.insert(elem());
- result.min_load =
- absl::container_internal::GetHashtableDebugProbeSummary(t).mean;
-
- while (t.size() < (min_max_sizes.min_load + min_max_sizes.max_load) / 2)
- t.insert(elem());
- result.avg_load =
- absl::container_internal::GetHashtableDebugProbeSummary(t).mean;
-
- while (t.size() < min_max_sizes.max_load) t.insert(elem());
- result.max_load =
- absl::container_internal::GetHashtableDebugProbeSummary(t).mean;
-
- return result;
-}
-
-template <int Align>
-uintptr_t PointerForAlignment() {
- alignas(Align) static constexpr uintptr_t kInitPointer = 0;
- return reinterpret_cast<uintptr_t>(&kInitPointer);
-}
-
-// This incomplete type is used for testing hash of pointers of different
-// alignments.
-// NOTE: We are generating invalid pointer values on the fly with
-// reinterpret_cast. There are not "safely derived" pointers so using them is
-// technically UB. It is unlikely to be a problem, though.
-template <int Align>
-struct Ptr;
-
-template <int Align>
-Ptr<Align>* MakePtr(uintptr_t v) {
- if (sizeof(v) == 8) {
- constexpr int kCopyBits = 16;
- // Ensure high bits are all the same.
- v = static_cast<uintptr_t>(static_cast<intptr_t>(v << kCopyBits) >>
- kCopyBits);
- }
- return reinterpret_cast<Ptr<Align>*>(v);
-}
-
-struct IntIdentity {
- uint64_t i;
- friend bool operator==(IntIdentity a, IntIdentity b) { return a.i == b.i; }
- IntIdentity operator++(int) { return IntIdentity{i++}; }
-};
-
-template <int Align>
-struct PtrIdentity {
- explicit PtrIdentity(uintptr_t val = PointerForAlignment<Align>()) : i(val) {}
- uintptr_t i;
- friend bool operator==(PtrIdentity a, PtrIdentity b) { return a.i == b.i; }
- PtrIdentity operator++(int) {
- PtrIdentity p(i);
- i += Align;
- return p;
- }
-};
-
-constexpr char kStringFormat[] = "/path/to/file/name-%07d-of-9999999.txt";
-
-template <bool small>
-struct String {
- std::string value;
- static std::string Make(uint32_t v) {
- return {small ? absl::StrCat(v) : absl::StrFormat(kStringFormat, v)};
- }
-};
-
-template <>
-struct DefaultHash<IntIdentity> {
- struct type {
- size_t operator()(IntIdentity t) const { return t.i; }
- };
-};
-
-template <int Align>
-struct DefaultHash<PtrIdentity<Align>> {
- struct type {
- size_t operator()(PtrIdentity<Align> t) const { return t.i; }
- };
-};
-
-template <class T>
-struct Sequential {
- T operator()() const { return current++; }
- mutable T current{};
-};
-
-template <int Align>
-struct Sequential<Ptr<Align>*> {
- Ptr<Align>* operator()() const {
- auto* result = MakePtr<Align>(current);
- current += Align;
- return result;
- }
- mutable uintptr_t current = PointerForAlignment<Align>();
-};
-
-
-template <bool small>
-struct Sequential<String<small>> {
- std::string operator()() const { return String<small>::Make(current++); }
- mutable uint32_t current = 0;
-};
-
-template <class T, class U>
-struct Sequential<std::pair<T, U>> {
- mutable Sequential<T> tseq;
- mutable Sequential<U> useq;
-
- using RealT = decltype(tseq());
- using RealU = decltype(useq());
-
- mutable std::vector<RealT> ts;
- mutable std::vector<RealU> us;
- mutable size_t ti = 0, ui = 0;
-
- std::pair<RealT, RealU> operator()() const {
- std::pair<RealT, RealU> value{get_t(), get_u()};
- if (ti == 0) {
- ti = ui + 1;
- ui = 0;
- } else {
- --ti;
- ++ui;
- }
- return value;
- }
-
- RealT get_t() const {
- while (ti >= ts.size()) ts.push_back(tseq());
- return ts[ti];
- }
-
- RealU get_u() const {
- while (ui >= us.size()) us.push_back(useq());
- return us[ui];
- }
-};
-
-template <class T, int percent_skip>
-struct AlmostSequential {
- mutable Sequential<T> current;
-
- auto operator()() const -> decltype(current()) {
- while (absl::Uniform(GlobalBitGen(), 0.0, 1.0) <= percent_skip / 100.)
- current();
- return current();
- }
-};
-
-struct Uniform {
- template <typename T>
- T operator()(T) const {
- return absl::Uniform<T>(absl::IntervalClosed, GlobalBitGen(), T{0}, ~T{0});
- }
-};
-
-struct Gaussian {
- template <typename T>
- T operator()(T) const {
- double d;
- do {
- d = absl::Gaussian<double>(GlobalBitGen(), 1e6, 1e4);
- } while (d <= 0 || d > std::numeric_limits<T>::max() / 2);
- return static_cast<T>(d);
- }
-};
-
-struct Zipf {
- template <typename T>
- T operator()(T) const {
- return absl::Zipf<T>(GlobalBitGen(), std::numeric_limits<T>::max(), 1.6);
- }
-};
-
-template <class T, class Dist>
-struct Random {
- T operator()() const { return Dist{}(T{}); }
-};
-
-template <class Dist, int Align>
-struct Random<Ptr<Align>*, Dist> {
- Ptr<Align>* operator()() const {
- return MakePtr<Align>(Random<uintptr_t, Dist>{}() * Align);
- }
-};
-
-template <class Dist>
-struct Random<IntIdentity, Dist> {
- IntIdentity operator()() const {
- return IntIdentity{Random<uint64_t, Dist>{}()};
- }
-};
-
-template <class Dist, int Align>
-struct Random<PtrIdentity<Align>, Dist> {
- PtrIdentity<Align> operator()() const {
- return PtrIdentity<Align>{Random<uintptr_t, Dist>{}() * Align};
- }
-};
-
-template <class Dist, bool small>
-struct Random<String<small>, Dist> {
- std::string operator()() const {
- return String<small>::Make(Random<uint32_t, Dist>{}());
- }
-};
-
-template <class T, class U, class Dist>
-struct Random<std::pair<T, U>, Dist> {
- auto operator()() const
- -> decltype(std::make_pair(Random<T, Dist>{}(), Random<U, Dist>{}())) {
- return std::make_pair(Random<T, Dist>{}(), Random<U, Dist>{}());
- }
-};
-
-template <typename>
-std::string Name();
-
-std::string Name(uint32_t*) { return "u32"; }
-std::string Name(uint64_t*) { return "u64"; }
-std::string Name(IntIdentity*) { return "IntIdentity"; }
-
-template <int Align>
-std::string Name(Ptr<Align>**) {
- return absl::StrCat("Ptr", Align);
-}
-
-template <int Align>
-std::string Name(PtrIdentity<Align>*) {
- return absl::StrCat("PtrIdentity", Align);
-}
-
-template <bool small>
-std::string Name(String<small>*) {
- return small ? "StrS" : "StrL";
-}
-
-template <class T, class U>
-std::string Name(std::pair<T, U>*) {
- if (output() == OutputStyle::kBenchmark)
- return absl::StrCat("P_", Name<T>(), "_", Name<U>());
- return absl::StrCat("P<", Name<T>(), ",", Name<U>(), ">");
-}
-
-template <class T>
-std::string Name(Sequential<T>*) {
- return "Sequential";
-}
-
-template <class T, int P>
-std::string Name(AlmostSequential<T, P>*) {
- return absl::StrCat("AlmostSeq_", P);
-}
-
-template <class T>
-std::string Name(Random<T, Uniform>*) {
- return "UnifRand";
-}
-
-template <class T>
-std::string Name(Random<T, Gaussian>*) {
- return "GausRand";
-}
-
-template <class T>
-std::string Name(Random<T, Zipf>*) {
- return "ZipfRand";
-}
-
-template <typename T>
-std::string Name() {
- return Name(static_cast<T*>(nullptr));
-}
-
-constexpr int kNameWidth = 15;
-constexpr int kDistWidth = 16;
-
-bool CanRunBenchmark(absl::string_view name) {
- static std::regex* const filter = []() -> std::regex* {
- return benchmarks.empty() || benchmarks == "all"
- ? nullptr
- : new std::regex(std::string(benchmarks));
- }();
- return filter == nullptr || std::regex_search(std::string(name), *filter);
-}
-
-struct Result {
- std::string name;
- std::string dist_name;
- Ratios ratios;
-};
-
-template <typename T, typename Dist>
-void RunForTypeAndDistribution(std::vector<Result>& results) {
- std::string name = absl::StrCat(Name<T>(), "/", Name<Dist>());
- // We have to check against all three names (min/avg/max) before we run it.
- // If any of them is enabled, we run it.
- if (!CanRunBenchmark(absl::StrCat(name, "/min")) &&
- !CanRunBenchmark(absl::StrCat(name, "/avg")) &&
- !CanRunBenchmark(absl::StrCat(name, "/max"))) {
- return;
- }
- results.push_back({Name<T>(), Name<Dist>(), CollectMeanProbeLengths<Dist>()});
-}
-
-template <class T>
-void RunForType(std::vector<Result>& results) {
- RunForTypeAndDistribution<T, Sequential<T>>(results);
- RunForTypeAndDistribution<T, AlmostSequential<T, 20>>(results);
- RunForTypeAndDistribution<T, AlmostSequential<T, 50>>(results);
- RunForTypeAndDistribution<T, Random<T, Uniform>>(results);
-#ifdef NDEBUG
- // Disable these in non-opt mode because they take too long.
- RunForTypeAndDistribution<T, Random<T, Gaussian>>(results);
- RunForTypeAndDistribution<T, Random<T, Zipf>>(results);
-#endif // NDEBUG
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- // Parse the benchmark flags. Ignore all of them except the regex pattern.
- for (int i = 1; i < argc; ++i) {
- absl::string_view arg = argv[i];
- const auto next = [&] { return argv[std::min(i + 1, argc - 1)]; };
-
- if (absl::ConsumePrefix(&arg, "--benchmark_filter")) {
- if (arg == "") {
- // --benchmark_filter X
- benchmarks = next();
- } else if (absl::ConsumePrefix(&arg, "=")) {
- // --benchmark_filter=X
- benchmarks = arg;
- }
- }
-
- // Any --benchmark flag turns on the mode.
- if (absl::ConsumePrefix(&arg, "--benchmark")) {
- if (benchmarks.empty()) benchmarks="all";
- }
- }
-
- std::vector<Result> results;
- RunForType<uint64_t>(results);
- RunForType<IntIdentity>(results);
- RunForType<Ptr<8>*>(results);
- RunForType<Ptr<16>*>(results);
- RunForType<Ptr<32>*>(results);
- RunForType<Ptr<64>*>(results);
- RunForType<PtrIdentity<8>>(results);
- RunForType<PtrIdentity<16>>(results);
- RunForType<PtrIdentity<32>>(results);
- RunForType<PtrIdentity<64>>(results);
- RunForType<std::pair<uint32_t, uint32_t>>(results);
- RunForType<String<true>>(results);
- RunForType<String<false>>(results);
- RunForType<std::pair<uint64_t, String<true>>>(results);
- RunForType<std::pair<String<true>, uint64_t>>(results);
- RunForType<std::pair<uint64_t, String<false>>>(results);
- RunForType<std::pair<String<false>, uint64_t>>(results);
-
- switch (output()) {
- case OutputStyle::kRegular:
- absl::PrintF("%-*s%-*s Min Avg Max\n%s\n", kNameWidth,
- "Type", kDistWidth, "Distribution",
- std::string(kNameWidth + kDistWidth + 10 * 3, '-'));
- for (const auto& result : results) {
- absl::PrintF("%-*s%-*s %8.4f %8.4f %8.4f\n", kNameWidth, result.name,
- kDistWidth, result.dist_name, result.ratios.min_load,
- result.ratios.avg_load, result.ratios.max_load);
- }
- break;
- case OutputStyle::kBenchmark: {
- absl::PrintF("{\n");
- absl::PrintF(" \"benchmarks\": [\n");
- absl::string_view comma;
- for (const auto& result : results) {
- auto print = [&](absl::string_view stat, double Ratios::*val) {
- std::string name =
- absl::StrCat(result.name, "/", result.dist_name, "/", stat);
- // Check the regex again. We might had have enabled only one of the
- // stats for the benchmark.
- if (!CanRunBenchmark(name)) return;
- absl::PrintF(" %s{\n", comma);
- absl::PrintF(" \"cpu_time\": %f,\n", 1e9 * result.ratios.*val);
- absl::PrintF(" \"real_time\": %f,\n", 1e9 * result.ratios.*val);
- absl::PrintF(" \"iterations\": 1,\n");
- absl::PrintF(" \"name\": \"%s\",\n", name);
- absl::PrintF(" \"time_unit\": \"ns\"\n");
- absl::PrintF(" }\n");
- comma = ",";
- };
- print("min", &Ratios::min_load);
- print("avg", &Ratios::avg_load);
- print("max", &Ratios::max_load);
- }
- absl::PrintF(" ],\n");
- absl::PrintF(" \"context\": {\n");
- absl::PrintF(" }\n");
- absl::PrintF("}\n");
- break;
- }
- }
-
- return 0;
-}
diff --git a/third_party/abseil-cpp/absl/container/internal/raw_hash_set_test.cc b/third_party/abseil-cpp/absl/container/internal/raw_hash_set_test.cc
deleted file mode 100644
index 6478d3f..0000000
--- a/third_party/abseil-cpp/absl/container/internal/raw_hash_set_test.cc
+++ /dev/null
@@ -1,2239 +0,0 @@
-// Copyright 2018 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/container/internal/raw_hash_set.h"
-
-#include <algorithm>
-#include <atomic>
-#include <cmath>
-#include <cstdint>
-#include <deque>
-#include <functional>
-#include <iterator>
-#include <list>
-#include <map>
-#include <memory>
-#include <numeric>
-#include <ostream>
-#include <random>
-#include <string>
-#include <type_traits>
-#include <unordered_map>
-#include <unordered_set>
-#include <utility>
-#include <vector>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/base/attributes.h"
-#include "absl/base/config.h"
-#include "absl/base/internal/cycleclock.h"
-#include "absl/base/internal/prefetch.h"
-#include "absl/base/internal/raw_logging.h"
-#include "absl/container/flat_hash_map.h"
-#include "absl/container/flat_hash_set.h"
-#include "absl/container/internal/container_memory.h"
-#include "absl/container/internal/hash_function_defaults.h"
-#include "absl/container/internal/hash_policy_testing.h"
-#include "absl/container/internal/hashtable_debug.h"
-#include "absl/log/log.h"
-#include "absl/strings/string_view.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-
-struct RawHashSetTestOnlyAccess {
- template <typename C>
- static auto GetSlots(const C& c) -> decltype(c.slots_) {
- return c.slots_;
- }
-};
-
-namespace {
-
-using ::testing::ElementsAre;
-using ::testing::Eq;
-using ::testing::Ge;
-using ::testing::Lt;
-using ::testing::Pair;
-using ::testing::UnorderedElementsAre;
-
-// Convenience function to static cast to ctrl_t.
-ctrl_t CtrlT(int i) { return static_cast<ctrl_t>(i); }
-
-TEST(Util, NormalizeCapacity) {
- EXPECT_EQ(1, NormalizeCapacity(0));
- EXPECT_EQ(1, NormalizeCapacity(1));
- EXPECT_EQ(3, NormalizeCapacity(2));
- EXPECT_EQ(3, NormalizeCapacity(3));
- EXPECT_EQ(7, NormalizeCapacity(4));
- EXPECT_EQ(7, NormalizeCapacity(7));
- EXPECT_EQ(15, NormalizeCapacity(8));
- EXPECT_EQ(15, NormalizeCapacity(15));
- EXPECT_EQ(15 * 2 + 1, NormalizeCapacity(15 + 1));
- EXPECT_EQ(15 * 2 + 1, NormalizeCapacity(15 + 2));
-}
-
-TEST(Util, GrowthAndCapacity) {
- // Verify that GrowthToCapacity gives the minimum capacity that has enough
- // growth.
- for (size_t growth = 0; growth < 10000; ++growth) {
- SCOPED_TRACE(growth);
- size_t capacity = NormalizeCapacity(GrowthToLowerboundCapacity(growth));
- // The capacity is large enough for `growth`.
- EXPECT_THAT(CapacityToGrowth(capacity), Ge(growth));
- // For (capacity+1) < kWidth, growth should equal capacity.
- if (capacity + 1 < Group::kWidth) {
- EXPECT_THAT(CapacityToGrowth(capacity), Eq(capacity));
- } else {
- EXPECT_THAT(CapacityToGrowth(capacity), Lt(capacity));
- }
- if (growth != 0 && capacity > 1) {
- // There is no smaller capacity that works.
- EXPECT_THAT(CapacityToGrowth(capacity / 2), Lt(growth));
- }
- }
-
- for (size_t capacity = Group::kWidth - 1; capacity < 10000;
- capacity = 2 * capacity + 1) {
- SCOPED_TRACE(capacity);
- size_t growth = CapacityToGrowth(capacity);
- EXPECT_THAT(growth, Lt(capacity));
- EXPECT_LE(GrowthToLowerboundCapacity(growth), capacity);
- EXPECT_EQ(NormalizeCapacity(GrowthToLowerboundCapacity(growth)), capacity);
- }
-}
-
-TEST(Util, probe_seq) {
- probe_seq<16> seq(0, 127);
- auto gen = [&]() {
- size_t res = seq.offset();
- seq.next();
- return res;
- };
- std::vector<size_t> offsets(8);
- std::generate_n(offsets.begin(), 8, gen);
- EXPECT_THAT(offsets, ElementsAre(0, 16, 48, 96, 32, 112, 80, 64));
- seq = probe_seq<16>(128, 127);
- std::generate_n(offsets.begin(), 8, gen);
- EXPECT_THAT(offsets, ElementsAre(0, 16, 48, 96, 32, 112, 80, 64));
-}
-
-TEST(BitMask, Smoke) {
- EXPECT_FALSE((BitMask<uint8_t, 8>(0)));
- EXPECT_TRUE((BitMask<uint8_t, 8>(5)));
-
- EXPECT_THAT((BitMask<uint8_t, 8>(0)), ElementsAre());
- EXPECT_THAT((BitMask<uint8_t, 8>(0x1)), ElementsAre(0));
- EXPECT_THAT((BitMask<uint8_t, 8>(0x2)), ElementsAre(1));
- EXPECT_THAT((BitMask<uint8_t, 8>(0x3)), ElementsAre(0, 1));
- EXPECT_THAT((BitMask<uint8_t, 8>(0x4)), ElementsAre(2));
- EXPECT_THAT((BitMask<uint8_t, 8>(0x5)), ElementsAre(0, 2));
- EXPECT_THAT((BitMask<uint8_t, 8>(0x55)), ElementsAre(0, 2, 4, 6));
- EXPECT_THAT((BitMask<uint8_t, 8>(0xAA)), ElementsAre(1, 3, 5, 7));
-}
-
-TEST(BitMask, WithShift) {
- // See the non-SSE version of Group for details on what this math is for.
- uint64_t ctrl = 0x1716151413121110;
- uint64_t hash = 0x12;
- constexpr uint64_t msbs = 0x8080808080808080ULL;
- constexpr uint64_t lsbs = 0x0101010101010101ULL;
- auto x = ctrl ^ (lsbs * hash);
- uint64_t mask = (x - lsbs) & ~x & msbs;
- EXPECT_EQ(0x0000000080800000, mask);
-
- BitMask<uint64_t, 8, 3> b(mask);
- EXPECT_EQ(*b, 2);
-}
-
-TEST(BitMask, LeadingTrailing) {
- EXPECT_EQ((BitMask<uint32_t, 16>(0x00001a40).LeadingZeros()), 3);
- EXPECT_EQ((BitMask<uint32_t, 16>(0x00001a40).TrailingZeros()), 6);
-
- EXPECT_EQ((BitMask<uint32_t, 16>(0x00000001).LeadingZeros()), 15);
- EXPECT_EQ((BitMask<uint32_t, 16>(0x00000001).TrailingZeros()), 0);
-
- EXPECT_EQ((BitMask<uint32_t, 16>(0x00008000).LeadingZeros()), 0);
- EXPECT_EQ((BitMask<uint32_t, 16>(0x00008000).TrailingZeros()), 15);
-
- EXPECT_EQ((BitMask<uint64_t, 8, 3>(0x0000008080808000).LeadingZeros()), 3);
- EXPECT_EQ((BitMask<uint64_t, 8, 3>(0x0000008080808000).TrailingZeros()), 1);
-
- EXPECT_EQ((BitMask<uint64_t, 8, 3>(0x0000000000000080).LeadingZeros()), 7);
- EXPECT_EQ((BitMask<uint64_t, 8, 3>(0x0000000000000080).TrailingZeros()), 0);
-
- EXPECT_EQ((BitMask<uint64_t, 8, 3>(0x8000000000000000).LeadingZeros()), 0);
- EXPECT_EQ((BitMask<uint64_t, 8, 3>(0x8000000000000000).TrailingZeros()), 7);
-}
-
-TEST(Group, EmptyGroup) {
- for (h2_t h = 0; h != 128; ++h) EXPECT_FALSE(Group{EmptyGroup()}.Match(h));
-}
-
-TEST(Group, Match) {
- if (Group::kWidth == 16) {
- ctrl_t group[] = {ctrl_t::kEmpty, CtrlT(1), ctrl_t::kDeleted, CtrlT(3),
- ctrl_t::kEmpty, CtrlT(5), ctrl_t::kSentinel, CtrlT(7),
- CtrlT(7), CtrlT(5), CtrlT(3), CtrlT(1),
- CtrlT(1), CtrlT(1), CtrlT(1), CtrlT(1)};
- EXPECT_THAT(Group{group}.Match(0), ElementsAre());
- EXPECT_THAT(Group{group}.Match(1), ElementsAre(1, 11, 12, 13, 14, 15));
- EXPECT_THAT(Group{group}.Match(3), ElementsAre(3, 10));
- EXPECT_THAT(Group{group}.Match(5), ElementsAre(5, 9));
- EXPECT_THAT(Group{group}.Match(7), ElementsAre(7, 8));
- } else if (Group::kWidth == 8) {
- ctrl_t group[] = {ctrl_t::kEmpty, CtrlT(1), CtrlT(2),
- ctrl_t::kDeleted, CtrlT(2), CtrlT(1),
- ctrl_t::kSentinel, CtrlT(1)};
- EXPECT_THAT(Group{group}.Match(0), ElementsAre());
- EXPECT_THAT(Group{group}.Match(1), ElementsAre(1, 5, 7));
- EXPECT_THAT(Group{group}.Match(2), ElementsAre(2, 4));
- } else {
- FAIL() << "No test coverage for Group::kWidth==" << Group::kWidth;
- }
-}
-
-TEST(Group, MaskEmpty) {
- if (Group::kWidth == 16) {
- ctrl_t group[] = {ctrl_t::kEmpty, CtrlT(1), ctrl_t::kDeleted, CtrlT(3),
- ctrl_t::kEmpty, CtrlT(5), ctrl_t::kSentinel, CtrlT(7),
- CtrlT(7), CtrlT(5), CtrlT(3), CtrlT(1),
- CtrlT(1), CtrlT(1), CtrlT(1), CtrlT(1)};
- EXPECT_THAT(Group{group}.MaskEmpty().LowestBitSet(), 0);
- EXPECT_THAT(Group{group}.MaskEmpty().HighestBitSet(), 4);
- } else if (Group::kWidth == 8) {
- ctrl_t group[] = {ctrl_t::kEmpty, CtrlT(1), CtrlT(2),
- ctrl_t::kDeleted, CtrlT(2), CtrlT(1),
- ctrl_t::kSentinel, CtrlT(1)};
- EXPECT_THAT(Group{group}.MaskEmpty().LowestBitSet(), 0);
- EXPECT_THAT(Group{group}.MaskEmpty().HighestBitSet(), 0);
- } else {
- FAIL() << "No test coverage for Group::kWidth==" << Group::kWidth;
- }
-}
-
-TEST(Group, MaskEmptyOrDeleted) {
- if (Group::kWidth == 16) {
- ctrl_t group[] = {ctrl_t::kEmpty, CtrlT(1), ctrl_t::kEmpty, CtrlT(3),
- ctrl_t::kDeleted, CtrlT(5), ctrl_t::kSentinel, CtrlT(7),
- CtrlT(7), CtrlT(5), CtrlT(3), CtrlT(1),
- CtrlT(1), CtrlT(1), CtrlT(1), CtrlT(1)};
- EXPECT_THAT(Group{group}.MaskEmptyOrDeleted().LowestBitSet(), 0);
- EXPECT_THAT(Group{group}.MaskEmptyOrDeleted().HighestBitSet(), 4);
- } else if (Group::kWidth == 8) {
- ctrl_t group[] = {ctrl_t::kEmpty, CtrlT(1), CtrlT(2),
- ctrl_t::kDeleted, CtrlT(2), CtrlT(1),
- ctrl_t::kSentinel, CtrlT(1)};
- EXPECT_THAT(Group{group}.MaskEmptyOrDeleted().LowestBitSet(), 0);
- EXPECT_THAT(Group{group}.MaskEmptyOrDeleted().HighestBitSet(), 3);
- } else {
- FAIL() << "No test coverage for Group::kWidth==" << Group::kWidth;
- }
-}
-
-TEST(Batch, DropDeletes) {
- constexpr size_t kCapacity = 63;
- constexpr size_t kGroupWidth = container_internal::Group::kWidth;
- std::vector<ctrl_t> ctrl(kCapacity + 1 + kGroupWidth);
- ctrl[kCapacity] = ctrl_t::kSentinel;
- std::vector<ctrl_t> pattern = {
- ctrl_t::kEmpty, CtrlT(2), ctrl_t::kDeleted, CtrlT(2),
- ctrl_t::kEmpty, CtrlT(1), ctrl_t::kDeleted};
- for (size_t i = 0; i != kCapacity; ++i) {
- ctrl[i] = pattern[i % pattern.size()];
- if (i < kGroupWidth - 1)
- ctrl[i + kCapacity + 1] = pattern[i % pattern.size()];
- }
- ConvertDeletedToEmptyAndFullToDeleted(ctrl.data(), kCapacity);
- ASSERT_EQ(ctrl[kCapacity], ctrl_t::kSentinel);
- for (size_t i = 0; i < kCapacity + kGroupWidth; ++i) {
- ctrl_t expected = pattern[i % (kCapacity + 1) % pattern.size()];
- if (i == kCapacity) expected = ctrl_t::kSentinel;
- if (expected == ctrl_t::kDeleted) expected = ctrl_t::kEmpty;
- if (IsFull(expected)) expected = ctrl_t::kDeleted;
- EXPECT_EQ(ctrl[i], expected)
- << i << " " << static_cast<int>(pattern[i % pattern.size()]);
- }
-}
-
-TEST(Group, CountLeadingEmptyOrDeleted) {
- const std::vector<ctrl_t> empty_examples = {ctrl_t::kEmpty, ctrl_t::kDeleted};
- const std::vector<ctrl_t> full_examples = {
- CtrlT(0), CtrlT(1), CtrlT(2), CtrlT(3),
- CtrlT(5), CtrlT(9), CtrlT(127), ctrl_t::kSentinel};
-
- for (ctrl_t empty : empty_examples) {
- std::vector<ctrl_t> e(Group::kWidth, empty);
- EXPECT_EQ(Group::kWidth, Group{e.data()}.CountLeadingEmptyOrDeleted());
- for (ctrl_t full : full_examples) {
- for (size_t i = 0; i != Group::kWidth; ++i) {
- std::vector<ctrl_t> f(Group::kWidth, empty);
- f[i] = full;
- EXPECT_EQ(i, Group{f.data()}.CountLeadingEmptyOrDeleted());
- }
- std::vector<ctrl_t> f(Group::kWidth, empty);
- f[Group::kWidth * 2 / 3] = full;
- f[Group::kWidth / 2] = full;
- EXPECT_EQ(
- Group::kWidth / 2, Group{f.data()}.CountLeadingEmptyOrDeleted());
- }
- }
-}
-
-template <class T>
-struct ValuePolicy {
- using slot_type = T;
- using key_type = T;
- using init_type = T;
-
- template <class Allocator, class... Args>
- static void construct(Allocator* alloc, slot_type* slot, Args&&... args) {
- absl::allocator_traits<Allocator>::construct(*alloc, slot,
- std::forward<Args>(args)...);
- }
-
- template <class Allocator>
- static void destroy(Allocator* alloc, slot_type* slot) {
- absl::allocator_traits<Allocator>::destroy(*alloc, slot);
- }
-
- template <class Allocator>
- static void transfer(Allocator* alloc, slot_type* new_slot,
- slot_type* old_slot) {
- construct(alloc, new_slot, std::move(*old_slot));
- destroy(alloc, old_slot);
- }
-
- static T& element(slot_type* slot) { return *slot; }
-
- template <class F, class... Args>
- static decltype(absl::container_internal::DecomposeValue(
- std::declval<F>(), std::declval<Args>()...))
- apply(F&& f, Args&&... args) {
- return absl::container_internal::DecomposeValue(
- std::forward<F>(f), std::forward<Args>(args)...);
- }
-};
-
-using IntPolicy = ValuePolicy<int64_t>;
-using Uint8Policy = ValuePolicy<uint8_t>;
-
-class StringPolicy {
- template <class F, class K, class V,
- class = typename std::enable_if<
- std::is_convertible<const K&, absl::string_view>::value>::type>
- decltype(std::declval<F>()(
- std::declval<const absl::string_view&>(), std::piecewise_construct,
- std::declval<std::tuple<K>>(),
- std::declval<V>())) static apply_impl(F&& f,
- std::pair<std::tuple<K>, V> p) {
- const absl::string_view& key = std::get<0>(p.first);
- return std::forward<F>(f)(key, std::piecewise_construct, std::move(p.first),
- std::move(p.second));
- }
-
- public:
- struct slot_type {
- struct ctor {};
-
- template <class... Ts>
- explicit slot_type(ctor, Ts&&... ts) : pair(std::forward<Ts>(ts)...) {}
-
- std::pair<std::string, std::string> pair;
- };
-
- using key_type = std::string;
- using init_type = std::pair<std::string, std::string>;
-
- template <class allocator_type, class... Args>
- static void construct(allocator_type* alloc, slot_type* slot, Args... args) {
- std::allocator_traits<allocator_type>::construct(
- *alloc, slot, typename slot_type::ctor(), std::forward<Args>(args)...);
- }
-
- template <class allocator_type>
- static void destroy(allocator_type* alloc, slot_type* slot) {
- std::allocator_traits<allocator_type>::destroy(*alloc, slot);
- }
-
- template <class allocator_type>
- static void transfer(allocator_type* alloc, slot_type* new_slot,
- slot_type* old_slot) {
- construct(alloc, new_slot, std::move(old_slot->pair));
- destroy(alloc, old_slot);
- }
-
- static std::pair<std::string, std::string>& element(slot_type* slot) {
- return slot->pair;
- }
-
- template <class F, class... Args>
- static auto apply(F&& f, Args&&... args)
- -> decltype(apply_impl(std::forward<F>(f),
- PairArgs(std::forward<Args>(args)...))) {
- return apply_impl(std::forward<F>(f),
- PairArgs(std::forward<Args>(args)...));
- }
-};
-
-struct StringHash : absl::Hash<absl::string_view> {
- using is_transparent = void;
-};
-struct StringEq : std::equal_to<absl::string_view> {
- using is_transparent = void;
-};
-
-struct StringTable
- : raw_hash_set<StringPolicy, StringHash, StringEq, std::allocator<int>> {
- using Base = typename StringTable::raw_hash_set;
- StringTable() {}
- using Base::Base;
-};
-
-struct IntTable
- : raw_hash_set<IntPolicy, container_internal::hash_default_hash<int64_t>,
- std::equal_to<int64_t>, std::allocator<int64_t>> {
- using Base = typename IntTable::raw_hash_set;
- using Base::Base;
-};
-
-struct Uint8Table
- : raw_hash_set<Uint8Policy, container_internal::hash_default_hash<uint8_t>,
- std::equal_to<uint8_t>, std::allocator<uint8_t>> {
- using Base = typename Uint8Table::raw_hash_set;
- using Base::Base;
-};
-
-template <typename T>
-struct CustomAlloc : std::allocator<T> {
- CustomAlloc() {}
-
- template <typename U>
- explicit CustomAlloc(const CustomAlloc<U>& /*other*/) {}
-
- template<class U> struct rebind {
- using other = CustomAlloc<U>;
- };
-};
-
-struct CustomAllocIntTable
- : raw_hash_set<IntPolicy, container_internal::hash_default_hash<int64_t>,
- std::equal_to<int64_t>, CustomAlloc<int64_t>> {
- using Base = typename CustomAllocIntTable::raw_hash_set;
- using Base::Base;
-};
-
-struct BadFastHash {
- template <class T>
- size_t operator()(const T&) const {
- return 0;
- }
-};
-
-struct BadTable : raw_hash_set<IntPolicy, BadFastHash, std::equal_to<int>,
- std::allocator<int>> {
- using Base = typename BadTable::raw_hash_set;
- BadTable() {}
- using Base::Base;
-};
-
-TEST(Table, EmptyFunctorOptimization) {
- static_assert(std::is_empty<std::equal_to<absl::string_view>>::value, "");
- static_assert(std::is_empty<std::allocator<int>>::value, "");
-
- struct MockTable {
- void* ctrl;
- void* slots;
- size_t size;
- size_t capacity;
- size_t growth_left;
- void* infoz;
- };
- struct MockTableInfozDisabled {
- void* ctrl;
- void* slots;
- size_t size;
- size_t capacity;
- size_t growth_left;
- };
- struct StatelessHash {
- size_t operator()(absl::string_view) const { return 0; }
- };
- struct StatefulHash : StatelessHash {
- size_t dummy;
- };
-
- if (std::is_empty<HashtablezInfoHandle>::value) {
- EXPECT_EQ(sizeof(MockTableInfozDisabled),
- sizeof(raw_hash_set<StringPolicy, StatelessHash,
- std::equal_to<absl::string_view>,
- std::allocator<int>>));
-
- EXPECT_EQ(sizeof(MockTableInfozDisabled) + sizeof(StatefulHash),
- sizeof(raw_hash_set<StringPolicy, StatefulHash,
- std::equal_to<absl::string_view>,
- std::allocator<int>>));
- } else {
- EXPECT_EQ(sizeof(MockTable),
- sizeof(raw_hash_set<StringPolicy, StatelessHash,
- std::equal_to<absl::string_view>,
- std::allocator<int>>));
-
- EXPECT_EQ(sizeof(MockTable) + sizeof(StatefulHash),
- sizeof(raw_hash_set<StringPolicy, StatefulHash,
- std::equal_to<absl::string_view>,
- std::allocator<int>>));
- }
-}
-
-TEST(Table, Empty) {
- IntTable t;
- EXPECT_EQ(0, t.size());
- EXPECT_TRUE(t.empty());
-}
-
-TEST(Table, LookupEmpty) {
- IntTable t;
- auto it = t.find(0);
- EXPECT_TRUE(it == t.end());
-}
-
-TEST(Table, Insert1) {
- IntTable t;
- EXPECT_TRUE(t.find(0) == t.end());
- auto res = t.emplace(0);
- EXPECT_TRUE(res.second);
- EXPECT_THAT(*res.first, 0);
- EXPECT_EQ(1, t.size());
- EXPECT_THAT(*t.find(0), 0);
-}
-
-TEST(Table, Insert2) {
- IntTable t;
- EXPECT_TRUE(t.find(0) == t.end());
- auto res = t.emplace(0);
- EXPECT_TRUE(res.second);
- EXPECT_THAT(*res.first, 0);
- EXPECT_EQ(1, t.size());
- EXPECT_TRUE(t.find(1) == t.end());
- res = t.emplace(1);
- EXPECT_TRUE(res.second);
- EXPECT_THAT(*res.first, 1);
- EXPECT_EQ(2, t.size());
- EXPECT_THAT(*t.find(0), 0);
- EXPECT_THAT(*t.find(1), 1);
-}
-
-TEST(Table, InsertCollision) {
- BadTable t;
- EXPECT_TRUE(t.find(1) == t.end());
- auto res = t.emplace(1);
- EXPECT_TRUE(res.second);
- EXPECT_THAT(*res.first, 1);
- EXPECT_EQ(1, t.size());
-
- EXPECT_TRUE(t.find(2) == t.end());
- res = t.emplace(2);
- EXPECT_THAT(*res.first, 2);
- EXPECT_TRUE(res.second);
- EXPECT_EQ(2, t.size());
-
- EXPECT_THAT(*t.find(1), 1);
- EXPECT_THAT(*t.find(2), 2);
-}
-
-// Test that we do not add existent element in case we need to search through
-// many groups with deleted elements
-TEST(Table, InsertCollisionAndFindAfterDelete) {
- BadTable t; // all elements go to the same group.
- // Have at least 2 groups with Group::kWidth collisions
- // plus some extra collisions in the last group.
- constexpr size_t kNumInserts = Group::kWidth * 2 + 5;
- for (size_t i = 0; i < kNumInserts; ++i) {
- auto res = t.emplace(i);
- EXPECT_TRUE(res.second);
- EXPECT_THAT(*res.first, i);
- EXPECT_EQ(i + 1, t.size());
- }
-
- // Remove elements one by one and check
- // that we still can find all other elements.
- for (size_t i = 0; i < kNumInserts; ++i) {
- EXPECT_EQ(1, t.erase(i)) << i;
- for (size_t j = i + 1; j < kNumInserts; ++j) {
- EXPECT_THAT(*t.find(j), j);
- auto res = t.emplace(j);
- EXPECT_FALSE(res.second) << i << " " << j;
- EXPECT_THAT(*res.first, j);
- EXPECT_EQ(kNumInserts - i - 1, t.size());
- }
- }
- EXPECT_TRUE(t.empty());
-}
-
-TEST(Table, InsertWithinCapacity) {
- IntTable t;
- t.reserve(10);
- const size_t original_capacity = t.capacity();
- const auto addr = [&](int i) {
- return reinterpret_cast<uintptr_t>(&*t.find(i));
- };
- // Inserting an element does not change capacity.
- t.insert(0);
- EXPECT_THAT(t.capacity(), original_capacity);
- const uintptr_t original_addr_0 = addr(0);
- // Inserting another element does not rehash.
- t.insert(1);
- EXPECT_THAT(t.capacity(), original_capacity);
- EXPECT_THAT(addr(0), original_addr_0);
- // Inserting lots of duplicate elements does not rehash.
- for (int i = 0; i < 100; ++i) {
- t.insert(i % 10);
- }
- EXPECT_THAT(t.capacity(), original_capacity);
- EXPECT_THAT(addr(0), original_addr_0);
- // Inserting a range of duplicate elements does not rehash.
- std::vector<int> dup_range;
- for (int i = 0; i < 100; ++i) {
- dup_range.push_back(i % 10);
- }
- t.insert(dup_range.begin(), dup_range.end());
- EXPECT_THAT(t.capacity(), original_capacity);
- EXPECT_THAT(addr(0), original_addr_0);
-}
-
-TEST(Table, LazyEmplace) {
- StringTable t;
- bool called = false;
- auto it = t.lazy_emplace("abc", [&](const StringTable::constructor& f) {
- called = true;
- f("abc", "ABC");
- });
- EXPECT_TRUE(called);
- EXPECT_THAT(*it, Pair("abc", "ABC"));
- called = false;
- it = t.lazy_emplace("abc", [&](const StringTable::constructor& f) {
- called = true;
- f("abc", "DEF");
- });
- EXPECT_FALSE(called);
- EXPECT_THAT(*it, Pair("abc", "ABC"));
-}
-
-TEST(Table, ContainsEmpty) {
- IntTable t;
-
- EXPECT_FALSE(t.contains(0));
-}
-
-TEST(Table, Contains1) {
- IntTable t;
-
- EXPECT_TRUE(t.insert(0).second);
- EXPECT_TRUE(t.contains(0));
- EXPECT_FALSE(t.contains(1));
-
- EXPECT_EQ(1, t.erase(0));
- EXPECT_FALSE(t.contains(0));
-}
-
-TEST(Table, Contains2) {
- IntTable t;
-
- EXPECT_TRUE(t.insert(0).second);
- EXPECT_TRUE(t.contains(0));
- EXPECT_FALSE(t.contains(1));
-
- t.clear();
- EXPECT_FALSE(t.contains(0));
-}
-
-int decompose_constructed;
-int decompose_copy_constructed;
-int decompose_copy_assigned;
-int decompose_move_constructed;
-int decompose_move_assigned;
-struct DecomposeType {
- DecomposeType(int i = 0) : i(i) { // NOLINT
- ++decompose_constructed;
- }
-
- explicit DecomposeType(const char* d) : DecomposeType(*d) {}
-
- DecomposeType(const DecomposeType& other) : i(other.i) {
- ++decompose_copy_constructed;
- }
- DecomposeType& operator=(const DecomposeType& other) {
- ++decompose_copy_assigned;
- i = other.i;
- return *this;
- }
- DecomposeType(DecomposeType&& other) : i(other.i) {
- ++decompose_move_constructed;
- }
- DecomposeType& operator=(DecomposeType&& other) {
- ++decompose_move_assigned;
- i = other.i;
- return *this;
- }
-
- int i;
-};
-
-struct DecomposeHash {
- using is_transparent = void;
- size_t operator()(const DecomposeType& a) const { return a.i; }
- size_t operator()(int a) const { return a; }
- size_t operator()(const char* a) const { return *a; }
-};
-
-struct DecomposeEq {
- using is_transparent = void;
- bool operator()(const DecomposeType& a, const DecomposeType& b) const {
- return a.i == b.i;
- }
- bool operator()(const DecomposeType& a, int b) const { return a.i == b; }
- bool operator()(const DecomposeType& a, const char* b) const {
- return a.i == *b;
- }
-};
-
-struct DecomposePolicy {
- using slot_type = DecomposeType;
- using key_type = DecomposeType;
- using init_type = DecomposeType;
-
- template <typename T>
- static void construct(void*, DecomposeType* slot, T&& v) {
- ::new (slot) DecomposeType(std::forward<T>(v));
- }
- static void destroy(void*, DecomposeType* slot) { slot->~DecomposeType(); }
- static DecomposeType& element(slot_type* slot) { return *slot; }
-
- template <class F, class T>
- static auto apply(F&& f, const T& x) -> decltype(std::forward<F>(f)(x, x)) {
- return std::forward<F>(f)(x, x);
- }
-};
-
-template <typename Hash, typename Eq>
-void TestDecompose(bool construct_three) {
- DecomposeType elem{0};
- const int one = 1;
- const char* three_p = "3";
- const auto& three = three_p;
- const int elem_vector_count = 256;
- std::vector<DecomposeType> elem_vector(elem_vector_count, DecomposeType{0});
- std::iota(elem_vector.begin(), elem_vector.end(), 0);
-
- using DecomposeSet =
- raw_hash_set<DecomposePolicy, Hash, Eq, std::allocator<int>>;
- DecomposeSet set1;
-
- decompose_constructed = 0;
- int expected_constructed = 0;
- EXPECT_EQ(expected_constructed, decompose_constructed);
- set1.insert(elem);
- EXPECT_EQ(expected_constructed, decompose_constructed);
- set1.insert(1);
- EXPECT_EQ(++expected_constructed, decompose_constructed);
- set1.emplace("3");
- EXPECT_EQ(++expected_constructed, decompose_constructed);
- EXPECT_EQ(expected_constructed, decompose_constructed);
-
- { // insert(T&&)
- set1.insert(1);
- EXPECT_EQ(expected_constructed, decompose_constructed);
- }
-
- { // insert(const T&)
- set1.insert(one);
- EXPECT_EQ(expected_constructed, decompose_constructed);
- }
-
- { // insert(hint, T&&)
- set1.insert(set1.begin(), 1);
- EXPECT_EQ(expected_constructed, decompose_constructed);
- }
-
- { // insert(hint, const T&)
- set1.insert(set1.begin(), one);
- EXPECT_EQ(expected_constructed, decompose_constructed);
- }
-
- { // emplace(...)
- set1.emplace(1);
- EXPECT_EQ(expected_constructed, decompose_constructed);
- set1.emplace("3");
- expected_constructed += construct_three;
- EXPECT_EQ(expected_constructed, decompose_constructed);
- set1.emplace(one);
- EXPECT_EQ(expected_constructed, decompose_constructed);
- set1.emplace(three);
- expected_constructed += construct_three;
- EXPECT_EQ(expected_constructed, decompose_constructed);
- }
-
- { // emplace_hint(...)
- set1.emplace_hint(set1.begin(), 1);
- EXPECT_EQ(expected_constructed, decompose_constructed);
- set1.emplace_hint(set1.begin(), "3");
- expected_constructed += construct_three;
- EXPECT_EQ(expected_constructed, decompose_constructed);
- set1.emplace_hint(set1.begin(), one);
- EXPECT_EQ(expected_constructed, decompose_constructed);
- set1.emplace_hint(set1.begin(), three);
- expected_constructed += construct_three;
- EXPECT_EQ(expected_constructed, decompose_constructed);
- }
-
- decompose_copy_constructed = 0;
- decompose_copy_assigned = 0;
- decompose_move_constructed = 0;
- decompose_move_assigned = 0;
- int expected_copy_constructed = 0;
- int expected_move_constructed = 0;
- { // raw_hash_set(first, last) with random-access iterators
- DecomposeSet set2(elem_vector.begin(), elem_vector.end());
- // Expect exactly one copy-constructor call for each element if no
- // rehashing is done.
- expected_copy_constructed += elem_vector_count;
- EXPECT_EQ(expected_copy_constructed, decompose_copy_constructed);
- EXPECT_EQ(expected_move_constructed, decompose_move_constructed);
- EXPECT_EQ(0, decompose_move_assigned);
- EXPECT_EQ(0, decompose_copy_assigned);
- }
-
- { // raw_hash_set(first, last) with forward iterators
- std::list<DecomposeType> elem_list(elem_vector.begin(), elem_vector.end());
- expected_copy_constructed = decompose_copy_constructed;
- DecomposeSet set2(elem_list.begin(), elem_list.end());
- // Expect exactly N elements copied into set, expect at most 2*N elements
- // moving internally for all resizing needed (for a growth factor of 2).
- expected_copy_constructed += elem_vector_count;
- EXPECT_EQ(expected_copy_constructed, decompose_copy_constructed);
- expected_move_constructed += elem_vector_count;
- EXPECT_LT(expected_move_constructed, decompose_move_constructed);
- expected_move_constructed += elem_vector_count;
- EXPECT_GE(expected_move_constructed, decompose_move_constructed);
- EXPECT_EQ(0, decompose_move_assigned);
- EXPECT_EQ(0, decompose_copy_assigned);
- expected_copy_constructed = decompose_copy_constructed;
- expected_move_constructed = decompose_move_constructed;
- }
-
- { // insert(first, last)
- DecomposeSet set2;
- set2.insert(elem_vector.begin(), elem_vector.end());
- // Expect exactly N elements copied into set, expect at most 2*N elements
- // moving internally for all resizing needed (for a growth factor of 2).
- const int expected_new_elements = elem_vector_count;
- const int expected_max_element_moves = 2 * elem_vector_count;
- expected_copy_constructed += expected_new_elements;
- EXPECT_EQ(expected_copy_constructed, decompose_copy_constructed);
- expected_move_constructed += expected_max_element_moves;
- EXPECT_GE(expected_move_constructed, decompose_move_constructed);
- EXPECT_EQ(0, decompose_move_assigned);
- EXPECT_EQ(0, decompose_copy_assigned);
- expected_copy_constructed = decompose_copy_constructed;
- expected_move_constructed = decompose_move_constructed;
- }
-}
-
-TEST(Table, Decompose) {
- TestDecompose<DecomposeHash, DecomposeEq>(false);
-
- struct TransparentHashIntOverload {
- size_t operator()(const DecomposeType& a) const { return a.i; }
- size_t operator()(int a) const { return a; }
- };
- struct TransparentEqIntOverload {
- bool operator()(const DecomposeType& a, const DecomposeType& b) const {
- return a.i == b.i;
- }
- bool operator()(const DecomposeType& a, int b) const { return a.i == b; }
- };
- TestDecompose<TransparentHashIntOverload, DecomposeEq>(true);
- TestDecompose<TransparentHashIntOverload, TransparentEqIntOverload>(true);
- TestDecompose<DecomposeHash, TransparentEqIntOverload>(true);
-}
-
-// Returns the largest m such that a table with m elements has the same number
-// of buckets as a table with n elements.
-size_t MaxDensitySize(size_t n) {
- IntTable t;
- t.reserve(n);
- for (size_t i = 0; i != n; ++i) t.emplace(i);
- const size_t c = t.bucket_count();
- while (c == t.bucket_count()) t.emplace(n++);
- return t.size() - 1;
-}
-
-struct Modulo1000Hash {
- size_t operator()(int x) const { return x % 1000; }
-};
-
-struct Modulo1000HashTable
- : public raw_hash_set<IntPolicy, Modulo1000Hash, std::equal_to<int>,
- std::allocator<int>> {};
-
-// Test that rehash with no resize happen in case of many deleted slots.
-TEST(Table, RehashWithNoResize) {
- Modulo1000HashTable t;
- // Adding the same length (and the same hash) strings
- // to have at least kMinFullGroups groups
- // with Group::kWidth collisions. Then fill up to MaxDensitySize;
- const size_t kMinFullGroups = 7;
- std::vector<int> keys;
- for (size_t i = 0; i < MaxDensitySize(Group::kWidth * kMinFullGroups); ++i) {
- int k = i * 1000;
- t.emplace(k);
- keys.push_back(k);
- }
- const size_t capacity = t.capacity();
-
- // Remove elements from all groups except the first and the last one.
- // All elements removed from full groups will be marked as ctrl_t::kDeleted.
- const size_t erase_begin = Group::kWidth / 2;
- const size_t erase_end = (t.size() / Group::kWidth - 1) * Group::kWidth;
- for (size_t i = erase_begin; i < erase_end; ++i) {
- EXPECT_EQ(1, t.erase(keys[i])) << i;
- }
- keys.erase(keys.begin() + erase_begin, keys.begin() + erase_end);
-
- auto last_key = keys.back();
- size_t last_key_num_probes = GetHashtableDebugNumProbes(t, last_key);
-
- // Make sure that we have to make a lot of probes for last key.
- ASSERT_GT(last_key_num_probes, kMinFullGroups);
-
- int x = 1;
- // Insert and erase one element, before inplace rehash happen.
- while (last_key_num_probes == GetHashtableDebugNumProbes(t, last_key)) {
- t.emplace(x);
- ASSERT_EQ(capacity, t.capacity());
- // All elements should be there.
- ASSERT_TRUE(t.find(x) != t.end()) << x;
- for (const auto& k : keys) {
- ASSERT_TRUE(t.find(k) != t.end()) << k;
- }
- t.erase(x);
- ++x;
- }
-}
-
-TEST(Table, InsertEraseStressTest) {
- IntTable t;
- const size_t kMinElementCount = 250;
- std::deque<int> keys;
- size_t i = 0;
- for (; i < MaxDensitySize(kMinElementCount); ++i) {
- t.emplace(i);
- keys.push_back(i);
- }
- const size_t kNumIterations = 1000000;
- for (; i < kNumIterations; ++i) {
- ASSERT_EQ(1, t.erase(keys.front()));
- keys.pop_front();
- t.emplace(i);
- keys.push_back(i);
- }
-}
-
-TEST(Table, InsertOverloads) {
- StringTable t;
- // These should all trigger the insert(init_type) overload.
- t.insert({{}, {}});
- t.insert({"ABC", {}});
- t.insert({"DEF", "!!!"});
-
- EXPECT_THAT(t, UnorderedElementsAre(Pair("", ""), Pair("ABC", ""),
- Pair("DEF", "!!!")));
-}
-
-TEST(Table, LargeTable) {
- IntTable t;
- for (int64_t i = 0; i != 100000; ++i) t.emplace(i << 40);
- for (int64_t i = 0; i != 100000; ++i) ASSERT_EQ(i << 40, *t.find(i << 40));
-}
-
-// Timeout if copy is quadratic as it was in Rust.
-TEST(Table, EnsureNonQuadraticAsInRust) {
- static const size_t kLargeSize = 1 << 15;
-
- IntTable t;
- for (size_t i = 0; i != kLargeSize; ++i) {
- t.insert(i);
- }
-
- // If this is quadratic, the test will timeout.
- IntTable t2;
- for (const auto& entry : t) t2.insert(entry);
-}
-
-TEST(Table, ClearBug) {
- IntTable t;
- constexpr size_t capacity = container_internal::Group::kWidth - 1;
- constexpr size_t max_size = capacity / 2 + 1;
- for (size_t i = 0; i < max_size; ++i) {
- t.insert(i);
- }
- ASSERT_EQ(capacity, t.capacity());
- intptr_t original = reinterpret_cast<intptr_t>(&*t.find(2));
- t.clear();
- ASSERT_EQ(capacity, t.capacity());
- for (size_t i = 0; i < max_size; ++i) {
- t.insert(i);
- }
- ASSERT_EQ(capacity, t.capacity());
- intptr_t second = reinterpret_cast<intptr_t>(&*t.find(2));
- // We are checking that original and second are close enough to each other
- // that they are probably still in the same group. This is not strictly
- // guaranteed.
- EXPECT_LT(std::abs(original - second),
- capacity * sizeof(IntTable::value_type));
-}
-
-TEST(Table, Erase) {
- IntTable t;
- EXPECT_TRUE(t.find(0) == t.end());
- auto res = t.emplace(0);
- EXPECT_TRUE(res.second);
- EXPECT_EQ(1, t.size());
- t.erase(res.first);
- EXPECT_EQ(0, t.size());
- EXPECT_TRUE(t.find(0) == t.end());
-}
-
-TEST(Table, EraseMaintainsValidIterator) {
- IntTable t;
- const int kNumElements = 100;
- for (int i = 0; i < kNumElements; i ++) {
- EXPECT_TRUE(t.emplace(i).second);
- }
- EXPECT_EQ(t.size(), kNumElements);
-
- int num_erase_calls = 0;
- auto it = t.begin();
- while (it != t.end()) {
- t.erase(it++);
- num_erase_calls++;
- }
-
- EXPECT_TRUE(t.empty());
- EXPECT_EQ(num_erase_calls, kNumElements);
-}
-
-// Collect N bad keys by following algorithm:
-// 1. Create an empty table and reserve it to 2 * N.
-// 2. Insert N random elements.
-// 3. Take first Group::kWidth - 1 to bad_keys array.
-// 4. Clear the table without resize.
-// 5. Go to point 2 while N keys not collected
-std::vector<int64_t> CollectBadMergeKeys(size_t N) {
- static constexpr int kGroupSize = Group::kWidth - 1;
-
- auto topk_range = [](size_t b, size_t e,
- IntTable* t) -> std::vector<int64_t> {
- for (size_t i = b; i != e; ++i) {
- t->emplace(i);
- }
- std::vector<int64_t> res;
- res.reserve(kGroupSize);
- auto it = t->begin();
- for (size_t i = b; i != e && i != b + kGroupSize; ++i, ++it) {
- res.push_back(*it);
- }
- return res;
- };
-
- std::vector<int64_t> bad_keys;
- bad_keys.reserve(N);
- IntTable t;
- t.reserve(N * 2);
-
- for (size_t b = 0; bad_keys.size() < N; b += N) {
- auto keys = topk_range(b, b + N, &t);
- bad_keys.insert(bad_keys.end(), keys.begin(), keys.end());
- t.erase(t.begin(), t.end());
- EXPECT_TRUE(t.empty());
- }
- return bad_keys;
-}
-
-struct ProbeStats {
- // Number of elements with specific probe length over all tested tables.
- std::vector<size_t> all_probes_histogram;
- // Ratios total_probe_length/size for every tested table.
- std::vector<double> single_table_ratios;
-
- friend ProbeStats operator+(const ProbeStats& a, const ProbeStats& b) {
- ProbeStats res = a;
- res.all_probes_histogram.resize(std::max(res.all_probes_histogram.size(),
- b.all_probes_histogram.size()));
- std::transform(b.all_probes_histogram.begin(), b.all_probes_histogram.end(),
- res.all_probes_histogram.begin(),
- res.all_probes_histogram.begin(), std::plus<size_t>());
- res.single_table_ratios.insert(res.single_table_ratios.end(),
- b.single_table_ratios.begin(),
- b.single_table_ratios.end());
- return res;
- }
-
- // Average ratio total_probe_length/size over tables.
- double AvgRatio() const {
- return std::accumulate(single_table_ratios.begin(),
- single_table_ratios.end(), 0.0) /
- single_table_ratios.size();
- }
-
- // Maximum ratio total_probe_length/size over tables.
- double MaxRatio() const {
- return *std::max_element(single_table_ratios.begin(),
- single_table_ratios.end());
- }
-
- // Percentile ratio total_probe_length/size over tables.
- double PercentileRatio(double Percentile = 0.95) const {
- auto r = single_table_ratios;
- auto mid = r.begin() + static_cast<size_t>(r.size() * Percentile);
- if (mid != r.end()) {
- std::nth_element(r.begin(), mid, r.end());
- return *mid;
- } else {
- return MaxRatio();
- }
- }
-
- // Maximum probe length over all elements and all tables.
- size_t MaxProbe() const { return all_probes_histogram.size(); }
-
- // Fraction of elements with specified probe length.
- std::vector<double> ProbeNormalizedHistogram() const {
- double total_elements = std::accumulate(all_probes_histogram.begin(),
- all_probes_histogram.end(), 0ull);
- std::vector<double> res;
- for (size_t p : all_probes_histogram) {
- res.push_back(p / total_elements);
- }
- return res;
- }
-
- size_t PercentileProbe(double Percentile = 0.99) const {
- size_t idx = 0;
- for (double p : ProbeNormalizedHistogram()) {
- if (Percentile > p) {
- Percentile -= p;
- ++idx;
- } else {
- return idx;
- }
- }
- return idx;
- }
-
- friend std::ostream& operator<<(std::ostream& out, const ProbeStats& s) {
- out << "{AvgRatio:" << s.AvgRatio() << ", MaxRatio:" << s.MaxRatio()
- << ", PercentileRatio:" << s.PercentileRatio()
- << ", MaxProbe:" << s.MaxProbe() << ", Probes=[";
- for (double p : s.ProbeNormalizedHistogram()) {
- out << p << ",";
- }
- out << "]}";
-
- return out;
- }
-};
-
-struct ExpectedStats {
- double avg_ratio;
- double max_ratio;
- std::vector<std::pair<double, double>> pecentile_ratios;
- std::vector<std::pair<double, double>> pecentile_probes;
-
- friend std::ostream& operator<<(std::ostream& out, const ExpectedStats& s) {
- out << "{AvgRatio:" << s.avg_ratio << ", MaxRatio:" << s.max_ratio
- << ", PercentileRatios: [";
- for (auto el : s.pecentile_ratios) {
- out << el.first << ":" << el.second << ", ";
- }
- out << "], PercentileProbes: [";
- for (auto el : s.pecentile_probes) {
- out << el.first << ":" << el.second << ", ";
- }
- out << "]}";
-
- return out;
- }
-};
-
-void VerifyStats(size_t size, const ExpectedStats& exp,
- const ProbeStats& stats) {
- EXPECT_LT(stats.AvgRatio(), exp.avg_ratio) << size << " " << stats;
- EXPECT_LT(stats.MaxRatio(), exp.max_ratio) << size << " " << stats;
- for (auto pr : exp.pecentile_ratios) {
- EXPECT_LE(stats.PercentileRatio(pr.first), pr.second)
- << size << " " << pr.first << " " << stats;
- }
-
- for (auto pr : exp.pecentile_probes) {
- EXPECT_LE(stats.PercentileProbe(pr.first), pr.second)
- << size << " " << pr.first << " " << stats;
- }
-}
-
-using ProbeStatsPerSize = std::map<size_t, ProbeStats>;
-
-// Collect total ProbeStats on num_iters iterations of the following algorithm:
-// 1. Create new table and reserve it to keys.size() * 2
-// 2. Insert all keys xored with seed
-// 3. Collect ProbeStats from final table.
-ProbeStats CollectProbeStatsOnKeysXoredWithSeed(
- const std::vector<int64_t>& keys, size_t num_iters) {
- const size_t reserve_size = keys.size() * 2;
-
- ProbeStats stats;
-
- int64_t seed = 0x71b1a19b907d6e33;
- while (num_iters--) {
- seed = static_cast<int64_t>(static_cast<uint64_t>(seed) * 17 + 13);
- IntTable t1;
- t1.reserve(reserve_size);
- for (const auto& key : keys) {
- t1.emplace(key ^ seed);
- }
-
- auto probe_histogram = GetHashtableDebugNumProbesHistogram(t1);
- stats.all_probes_histogram.resize(
- std::max(stats.all_probes_histogram.size(), probe_histogram.size()));
- std::transform(probe_histogram.begin(), probe_histogram.end(),
- stats.all_probes_histogram.begin(),
- stats.all_probes_histogram.begin(), std::plus<size_t>());
-
- size_t total_probe_seq_length = 0;
- for (size_t i = 0; i < probe_histogram.size(); ++i) {
- total_probe_seq_length += i * probe_histogram[i];
- }
- stats.single_table_ratios.push_back(total_probe_seq_length * 1.0 /
- keys.size());
- t1.erase(t1.begin(), t1.end());
- }
- return stats;
-}
-
-ExpectedStats XorSeedExpectedStats() {
- constexpr bool kRandomizesInserts =
-#ifdef NDEBUG
- false;
-#else // NDEBUG
- true;
-#endif // NDEBUG
-
- // The effective load factor is larger in non-opt mode because we insert
- // elements out of order.
- switch (container_internal::Group::kWidth) {
- case 8:
- if (kRandomizesInserts) {
- return {0.05,
- 1.0,
- {{0.95, 0.5}},
- {{0.95, 0}, {0.99, 2}, {0.999, 4}, {0.9999, 10}}};
- } else {
- return {0.05,
- 2.0,
- {{0.95, 0.1}},
- {{0.95, 0}, {0.99, 2}, {0.999, 4}, {0.9999, 10}}};
- }
- case 16:
- if (kRandomizesInserts) {
- return {0.1,
- 2.0,
- {{0.95, 0.1}},
- {{0.95, 0}, {0.99, 1}, {0.999, 8}, {0.9999, 15}}};
- } else {
- return {0.05,
- 1.0,
- {{0.95, 0.05}},
- {{0.95, 0}, {0.99, 1}, {0.999, 4}, {0.9999, 10}}};
- }
- }
- ABSL_RAW_LOG(FATAL, "%s", "Unknown Group width");
- return {};
-}
-
-// TODO(b/80415403): Figure out why this test is so flaky, esp. on MSVC
-TEST(Table, DISABLED_EnsureNonQuadraticTopNXorSeedByProbeSeqLength) {
- ProbeStatsPerSize stats;
- std::vector<size_t> sizes = {Group::kWidth << 5, Group::kWidth << 10};
- for (size_t size : sizes) {
- stats[size] =
- CollectProbeStatsOnKeysXoredWithSeed(CollectBadMergeKeys(size), 200);
- }
- auto expected = XorSeedExpectedStats();
- for (size_t size : sizes) {
- auto& stat = stats[size];
- VerifyStats(size, expected, stat);
- LOG(INFO) << size << " " << stat;
- }
-}
-
-// Collect total ProbeStats on num_iters iterations of the following algorithm:
-// 1. Create new table
-// 2. Select 10% of keys and insert 10 elements key * 17 + j * 13
-// 3. Collect ProbeStats from final table
-ProbeStats CollectProbeStatsOnLinearlyTransformedKeys(
- const std::vector<int64_t>& keys, size_t num_iters) {
- ProbeStats stats;
-
- std::random_device rd;
- std::mt19937 rng(rd());
- auto linear_transform = [](size_t x, size_t y) { return x * 17 + y * 13; };
- std::uniform_int_distribution<size_t> dist(0, keys.size()-1);
- while (num_iters--) {
- IntTable t1;
- size_t num_keys = keys.size() / 10;
- size_t start = dist(rng);
- for (size_t i = 0; i != num_keys; ++i) {
- for (size_t j = 0; j != 10; ++j) {
- t1.emplace(linear_transform(keys[(i + start) % keys.size()], j));
- }
- }
-
- auto probe_histogram = GetHashtableDebugNumProbesHistogram(t1);
- stats.all_probes_histogram.resize(
- std::max(stats.all_probes_histogram.size(), probe_histogram.size()));
- std::transform(probe_histogram.begin(), probe_histogram.end(),
- stats.all_probes_histogram.begin(),
- stats.all_probes_histogram.begin(), std::plus<size_t>());
-
- size_t total_probe_seq_length = 0;
- for (size_t i = 0; i < probe_histogram.size(); ++i) {
- total_probe_seq_length += i * probe_histogram[i];
- }
- stats.single_table_ratios.push_back(total_probe_seq_length * 1.0 /
- t1.size());
- t1.erase(t1.begin(), t1.end());
- }
- return stats;
-}
-
-ExpectedStats LinearTransformExpectedStats() {
- constexpr bool kRandomizesInserts =
-#ifdef NDEBUG
- false;
-#else // NDEBUG
- true;
-#endif // NDEBUG
-
- // The effective load factor is larger in non-opt mode because we insert
- // elements out of order.
- switch (container_internal::Group::kWidth) {
- case 8:
- if (kRandomizesInserts) {
- return {0.1,
- 0.5,
- {{0.95, 0.3}},
- {{0.95, 0}, {0.99, 1}, {0.999, 8}, {0.9999, 15}}};
- } else {
- return {0.4,
- 0.6,
- {{0.95, 0.5}},
- {{0.95, 1}, {0.99, 14}, {0.999, 23}, {0.9999, 26}}};
- }
- case 16:
- if (kRandomizesInserts) {
- return {0.1,
- 0.4,
- {{0.95, 0.3}},
- {{0.95, 1}, {0.99, 2}, {0.999, 9}, {0.9999, 15}}};
- } else {
- return {0.05,
- 0.2,
- {{0.95, 0.1}},
- {{0.95, 0}, {0.99, 1}, {0.999, 6}, {0.9999, 10}}};
- }
- }
- ABSL_RAW_LOG(FATAL, "%s", "Unknown Group width");
- return {};
-}
-
-// TODO(b/80415403): Figure out why this test is so flaky.
-TEST(Table, DISABLED_EnsureNonQuadraticTopNLinearTransformByProbeSeqLength) {
- ProbeStatsPerSize stats;
- std::vector<size_t> sizes = {Group::kWidth << 5, Group::kWidth << 10};
- for (size_t size : sizes) {
- stats[size] = CollectProbeStatsOnLinearlyTransformedKeys(
- CollectBadMergeKeys(size), 300);
- }
- auto expected = LinearTransformExpectedStats();
- for (size_t size : sizes) {
- auto& stat = stats[size];
- VerifyStats(size, expected, stat);
- LOG(INFO) << size << " " << stat;
- }
-}
-
-TEST(Table, EraseCollision) {
- BadTable t;
-
- // 1 2 3
- t.emplace(1);
- t.emplace(2);
- t.emplace(3);
- EXPECT_THAT(*t.find(1), 1);
- EXPECT_THAT(*t.find(2), 2);
- EXPECT_THAT(*t.find(3), 3);
- EXPECT_EQ(3, t.size());
-
- // 1 DELETED 3
- t.erase(t.find(2));
- EXPECT_THAT(*t.find(1), 1);
- EXPECT_TRUE(t.find(2) == t.end());
- EXPECT_THAT(*t.find(3), 3);
- EXPECT_EQ(2, t.size());
-
- // DELETED DELETED 3
- t.erase(t.find(1));
- EXPECT_TRUE(t.find(1) == t.end());
- EXPECT_TRUE(t.find(2) == t.end());
- EXPECT_THAT(*t.find(3), 3);
- EXPECT_EQ(1, t.size());
-
- // DELETED DELETED DELETED
- t.erase(t.find(3));
- EXPECT_TRUE(t.find(1) == t.end());
- EXPECT_TRUE(t.find(2) == t.end());
- EXPECT_TRUE(t.find(3) == t.end());
- EXPECT_EQ(0, t.size());
-}
-
-TEST(Table, EraseInsertProbing) {
- BadTable t(100);
-
- // 1 2 3 4
- t.emplace(1);
- t.emplace(2);
- t.emplace(3);
- t.emplace(4);
-
- // 1 DELETED 3 DELETED
- t.erase(t.find(2));
- t.erase(t.find(4));
-
- // 1 10 3 11 12
- t.emplace(10);
- t.emplace(11);
- t.emplace(12);
-
- EXPECT_EQ(5, t.size());
- EXPECT_THAT(t, UnorderedElementsAre(1, 10, 3, 11, 12));
-}
-
-TEST(Table, Clear) {
- IntTable t;
- EXPECT_TRUE(t.find(0) == t.end());
- t.clear();
- EXPECT_TRUE(t.find(0) == t.end());
- auto res = t.emplace(0);
- EXPECT_TRUE(res.second);
- EXPECT_EQ(1, t.size());
- t.clear();
- EXPECT_EQ(0, t.size());
- EXPECT_TRUE(t.find(0) == t.end());
-}
-
-TEST(Table, Swap) {
- IntTable t;
- EXPECT_TRUE(t.find(0) == t.end());
- auto res = t.emplace(0);
- EXPECT_TRUE(res.second);
- EXPECT_EQ(1, t.size());
- IntTable u;
- t.swap(u);
- EXPECT_EQ(0, t.size());
- EXPECT_EQ(1, u.size());
- EXPECT_TRUE(t.find(0) == t.end());
- EXPECT_THAT(*u.find(0), 0);
-}
-
-TEST(Table, Rehash) {
- IntTable t;
- EXPECT_TRUE(t.find(0) == t.end());
- t.emplace(0);
- t.emplace(1);
- EXPECT_EQ(2, t.size());
- t.rehash(128);
- EXPECT_EQ(2, t.size());
- EXPECT_THAT(*t.find(0), 0);
- EXPECT_THAT(*t.find(1), 1);
-}
-
-TEST(Table, RehashDoesNotRehashWhenNotNecessary) {
- IntTable t;
- t.emplace(0);
- t.emplace(1);
- auto* p = &*t.find(0);
- t.rehash(1);
- EXPECT_EQ(p, &*t.find(0));
-}
-
-TEST(Table, RehashZeroDoesNotAllocateOnEmptyTable) {
- IntTable t;
- t.rehash(0);
- EXPECT_EQ(0, t.bucket_count());
-}
-
-TEST(Table, RehashZeroDeallocatesEmptyTable) {
- IntTable t;
- t.emplace(0);
- t.clear();
- EXPECT_NE(0, t.bucket_count());
- t.rehash(0);
- EXPECT_EQ(0, t.bucket_count());
-}
-
-TEST(Table, RehashZeroForcesRehash) {
- IntTable t;
- t.emplace(0);
- t.emplace(1);
- auto* p = &*t.find(0);
- t.rehash(0);
- EXPECT_NE(p, &*t.find(0));
-}
-
-TEST(Table, ConstructFromInitList) {
- using P = std::pair<std::string, std::string>;
- struct Q {
- operator P() const { return {}; } // NOLINT
- };
- StringTable t = {P(), Q(), {}, {{}, {}}};
-}
-
-TEST(Table, CopyConstruct) {
- IntTable t;
- t.emplace(0);
- EXPECT_EQ(1, t.size());
- {
- IntTable u(t);
- EXPECT_EQ(1, u.size());
- EXPECT_THAT(*u.find(0), 0);
- }
- {
- IntTable u{t};
- EXPECT_EQ(1, u.size());
- EXPECT_THAT(*u.find(0), 0);
- }
- {
- IntTable u = t;
- EXPECT_EQ(1, u.size());
- EXPECT_THAT(*u.find(0), 0);
- }
-}
-
-TEST(Table, CopyConstructWithAlloc) {
- StringTable t;
- t.emplace("a", "b");
- EXPECT_EQ(1, t.size());
- StringTable u(t, Alloc<std::pair<std::string, std::string>>());
- EXPECT_EQ(1, u.size());
- EXPECT_THAT(*u.find("a"), Pair("a", "b"));
-}
-
-struct ExplicitAllocIntTable
- : raw_hash_set<IntPolicy, container_internal::hash_default_hash<int64_t>,
- std::equal_to<int64_t>, Alloc<int64_t>> {
- ExplicitAllocIntTable() {}
-};
-
-TEST(Table, AllocWithExplicitCtor) {
- ExplicitAllocIntTable t;
- EXPECT_EQ(0, t.size());
-}
-
-TEST(Table, MoveConstruct) {
- {
- StringTable t;
- t.emplace("a", "b");
- EXPECT_EQ(1, t.size());
-
- StringTable u(std::move(t));
- EXPECT_EQ(1, u.size());
- EXPECT_THAT(*u.find("a"), Pair("a", "b"));
- }
- {
- StringTable t;
- t.emplace("a", "b");
- EXPECT_EQ(1, t.size());
-
- StringTable u{std::move(t)};
- EXPECT_EQ(1, u.size());
- EXPECT_THAT(*u.find("a"), Pair("a", "b"));
- }
- {
- StringTable t;
- t.emplace("a", "b");
- EXPECT_EQ(1, t.size());
-
- StringTable u = std::move(t);
- EXPECT_EQ(1, u.size());
- EXPECT_THAT(*u.find("a"), Pair("a", "b"));
- }
-}
-
-TEST(Table, MoveConstructWithAlloc) {
- StringTable t;
- t.emplace("a", "b");
- EXPECT_EQ(1, t.size());
- StringTable u(std::move(t), Alloc<std::pair<std::string, std::string>>());
- EXPECT_EQ(1, u.size());
- EXPECT_THAT(*u.find("a"), Pair("a", "b"));
-}
-
-TEST(Table, CopyAssign) {
- StringTable t;
- t.emplace("a", "b");
- EXPECT_EQ(1, t.size());
- StringTable u;
- u = t;
- EXPECT_EQ(1, u.size());
- EXPECT_THAT(*u.find("a"), Pair("a", "b"));
-}
-
-TEST(Table, CopySelfAssign) {
- StringTable t;
- t.emplace("a", "b");
- EXPECT_EQ(1, t.size());
- t = *&t;
- EXPECT_EQ(1, t.size());
- EXPECT_THAT(*t.find("a"), Pair("a", "b"));
-}
-
-TEST(Table, MoveAssign) {
- StringTable t;
- t.emplace("a", "b");
- EXPECT_EQ(1, t.size());
- StringTable u;
- u = std::move(t);
- EXPECT_EQ(1, u.size());
- EXPECT_THAT(*u.find("a"), Pair("a", "b"));
-}
-
-TEST(Table, Equality) {
- StringTable t;
- std::vector<std::pair<std::string, std::string>> v = {{"a", "b"},
- {"aa", "bb"}};
- t.insert(std::begin(v), std::end(v));
- StringTable u = t;
- EXPECT_EQ(u, t);
-}
-
-TEST(Table, Equality2) {
- StringTable t;
- std::vector<std::pair<std::string, std::string>> v1 = {{"a", "b"},
- {"aa", "bb"}};
- t.insert(std::begin(v1), std::end(v1));
- StringTable u;
- std::vector<std::pair<std::string, std::string>> v2 = {{"a", "a"},
- {"aa", "aa"}};
- u.insert(std::begin(v2), std::end(v2));
- EXPECT_NE(u, t);
-}
-
-TEST(Table, Equality3) {
- StringTable t;
- std::vector<std::pair<std::string, std::string>> v1 = {{"b", "b"},
- {"bb", "bb"}};
- t.insert(std::begin(v1), std::end(v1));
- StringTable u;
- std::vector<std::pair<std::string, std::string>> v2 = {{"a", "a"},
- {"aa", "aa"}};
- u.insert(std::begin(v2), std::end(v2));
- EXPECT_NE(u, t);
-}
-
-TEST(Table, NumDeletedRegression) {
- IntTable t;
- t.emplace(0);
- t.erase(t.find(0));
- // construct over a deleted slot.
- t.emplace(0);
- t.clear();
-}
-
-TEST(Table, FindFullDeletedRegression) {
- IntTable t;
- for (int i = 0; i < 1000; ++i) {
- t.emplace(i);
- t.erase(t.find(i));
- }
- EXPECT_EQ(0, t.size());
-}
-
-TEST(Table, ReplacingDeletedSlotDoesNotRehash) {
- size_t n;
- {
- // Compute n such that n is the maximum number of elements before rehash.
- IntTable t;
- t.emplace(0);
- size_t c = t.bucket_count();
- for (n = 1; c == t.bucket_count(); ++n) t.emplace(n);
- --n;
- }
- IntTable t;
- t.rehash(n);
- const size_t c = t.bucket_count();
- for (size_t i = 0; i != n; ++i) t.emplace(i);
- EXPECT_EQ(c, t.bucket_count()) << "rehashing threshold = " << n;
- t.erase(0);
- t.emplace(0);
- EXPECT_EQ(c, t.bucket_count()) << "rehashing threshold = " << n;
-}
-
-TEST(Table, NoThrowMoveConstruct) {
- ASSERT_TRUE(
- std::is_nothrow_copy_constructible<absl::Hash<absl::string_view>>::value);
- ASSERT_TRUE(std::is_nothrow_copy_constructible<
- std::equal_to<absl::string_view>>::value);
- ASSERT_TRUE(std::is_nothrow_copy_constructible<std::allocator<int>>::value);
- EXPECT_TRUE(std::is_nothrow_move_constructible<StringTable>::value);
-}
-
-TEST(Table, NoThrowMoveAssign) {
- ASSERT_TRUE(
- std::is_nothrow_move_assignable<absl::Hash<absl::string_view>>::value);
- ASSERT_TRUE(
- std::is_nothrow_move_assignable<std::equal_to<absl::string_view>>::value);
- ASSERT_TRUE(std::is_nothrow_move_assignable<std::allocator<int>>::value);
- ASSERT_TRUE(
- absl::allocator_traits<std::allocator<int>>::is_always_equal::value);
- EXPECT_TRUE(std::is_nothrow_move_assignable<StringTable>::value);
-}
-
-TEST(Table, NoThrowSwappable) {
- ASSERT_TRUE(
- container_internal::IsNoThrowSwappable<absl::Hash<absl::string_view>>());
- ASSERT_TRUE(container_internal::IsNoThrowSwappable<
- std::equal_to<absl::string_view>>());
- ASSERT_TRUE(container_internal::IsNoThrowSwappable<std::allocator<int>>());
- EXPECT_TRUE(container_internal::IsNoThrowSwappable<StringTable>());
-}
-
-TEST(Table, HeterogeneousLookup) {
- struct Hash {
- size_t operator()(int64_t i) const { return i; }
- size_t operator()(double i) const {
- ADD_FAILURE();
- return i;
- }
- };
- struct Eq {
- bool operator()(int64_t a, int64_t b) const { return a == b; }
- bool operator()(double a, int64_t b) const {
- ADD_FAILURE();
- return a == b;
- }
- bool operator()(int64_t a, double b) const {
- ADD_FAILURE();
- return a == b;
- }
- bool operator()(double a, double b) const {
- ADD_FAILURE();
- return a == b;
- }
- };
-
- struct THash {
- using is_transparent = void;
- size_t operator()(int64_t i) const { return i; }
- size_t operator()(double i) const { return i; }
- };
- struct TEq {
- using is_transparent = void;
- bool operator()(int64_t a, int64_t b) const { return a == b; }
- bool operator()(double a, int64_t b) const { return a == b; }
- bool operator()(int64_t a, double b) const { return a == b; }
- bool operator()(double a, double b) const { return a == b; }
- };
-
- raw_hash_set<IntPolicy, Hash, Eq, Alloc<int64_t>> s{0, 1, 2};
- // It will convert to int64_t before the query.
- EXPECT_EQ(1, *s.find(double{1.1}));
-
- raw_hash_set<IntPolicy, THash, TEq, Alloc<int64_t>> ts{0, 1, 2};
- // It will try to use the double, and fail to find the object.
- EXPECT_TRUE(ts.find(1.1) == ts.end());
-}
-
-template <class Table>
-using CallFind = decltype(std::declval<Table&>().find(17));
-
-template <class Table>
-using CallErase = decltype(std::declval<Table&>().erase(17));
-
-template <class Table>
-using CallExtract = decltype(std::declval<Table&>().extract(17));
-
-template <class Table>
-using CallPrefetch = decltype(std::declval<Table&>().prefetch(17));
-
-template <class Table>
-using CallCount = decltype(std::declval<Table&>().count(17));
-
-template <template <typename> class C, class Table, class = void>
-struct VerifyResultOf : std::false_type {};
-
-template <template <typename> class C, class Table>
-struct VerifyResultOf<C, Table, absl::void_t<C<Table>>> : std::true_type {};
-
-TEST(Table, HeterogeneousLookupOverloads) {
- using NonTransparentTable =
- raw_hash_set<StringPolicy, absl::Hash<absl::string_view>,
- std::equal_to<absl::string_view>, std::allocator<int>>;
-
- EXPECT_FALSE((VerifyResultOf<CallFind, NonTransparentTable>()));
- EXPECT_FALSE((VerifyResultOf<CallErase, NonTransparentTable>()));
- EXPECT_FALSE((VerifyResultOf<CallExtract, NonTransparentTable>()));
- EXPECT_FALSE((VerifyResultOf<CallPrefetch, NonTransparentTable>()));
- EXPECT_FALSE((VerifyResultOf<CallCount, NonTransparentTable>()));
-
- using TransparentTable = raw_hash_set<
- StringPolicy,
- absl::container_internal::hash_default_hash<absl::string_view>,
- absl::container_internal::hash_default_eq<absl::string_view>,
- std::allocator<int>>;
-
- EXPECT_TRUE((VerifyResultOf<CallFind, TransparentTable>()));
- EXPECT_TRUE((VerifyResultOf<CallErase, TransparentTable>()));
- EXPECT_TRUE((VerifyResultOf<CallExtract, TransparentTable>()));
- EXPECT_TRUE((VerifyResultOf<CallPrefetch, TransparentTable>()));
- EXPECT_TRUE((VerifyResultOf<CallCount, TransparentTable>()));
-}
-
-// TODO(alkis): Expand iterator tests.
-TEST(Iterator, IsDefaultConstructible) {
- StringTable::iterator i;
- EXPECT_TRUE(i == StringTable::iterator());
-}
-
-TEST(ConstIterator, IsDefaultConstructible) {
- StringTable::const_iterator i;
- EXPECT_TRUE(i == StringTable::const_iterator());
-}
-
-TEST(Iterator, ConvertsToConstIterator) {
- StringTable::iterator i;
- EXPECT_TRUE(i == StringTable::const_iterator());
-}
-
-TEST(Iterator, Iterates) {
- IntTable t;
- for (size_t i = 3; i != 6; ++i) EXPECT_TRUE(t.emplace(i).second);
- EXPECT_THAT(t, UnorderedElementsAre(3, 4, 5));
-}
-
-TEST(Table, Merge) {
- StringTable t1, t2;
- t1.emplace("0", "-0");
- t1.emplace("1", "-1");
- t2.emplace("0", "~0");
- t2.emplace("2", "~2");
-
- EXPECT_THAT(t1, UnorderedElementsAre(Pair("0", "-0"), Pair("1", "-1")));
- EXPECT_THAT(t2, UnorderedElementsAre(Pair("0", "~0"), Pair("2", "~2")));
-
- t1.merge(t2);
- EXPECT_THAT(t1, UnorderedElementsAre(Pair("0", "-0"), Pair("1", "-1"),
- Pair("2", "~2")));
- EXPECT_THAT(t2, UnorderedElementsAre(Pair("0", "~0")));
-}
-
-TEST(Table, IteratorEmplaceConstructibleRequirement) {
- struct Value {
- explicit Value(absl::string_view view) : value(view) {}
- std::string value;
-
- bool operator==(const Value& other) const { return value == other.value; }
- };
- struct H {
- size_t operator()(const Value& v) const {
- return absl::Hash<std::string>{}(v.value);
- }
- };
-
- struct Table : raw_hash_set<ValuePolicy<Value>, H, std::equal_to<Value>,
- std::allocator<Value>> {
- using Base = typename Table::raw_hash_set;
- using Base::Base;
- };
-
- std::string input[3]{"A", "B", "C"};
-
- Table t(std::begin(input), std::end(input));
- EXPECT_THAT(t, UnorderedElementsAre(Value{"A"}, Value{"B"}, Value{"C"}));
-
- input[0] = "D";
- input[1] = "E";
- input[2] = "F";
- t.insert(std::begin(input), std::end(input));
- EXPECT_THAT(t, UnorderedElementsAre(Value{"A"}, Value{"B"}, Value{"C"},
- Value{"D"}, Value{"E"}, Value{"F"}));
-}
-
-TEST(Nodes, EmptyNodeType) {
- using node_type = StringTable::node_type;
- node_type n;
- EXPECT_FALSE(n);
- EXPECT_TRUE(n.empty());
-
- EXPECT_TRUE((std::is_same<node_type::allocator_type,
- StringTable::allocator_type>::value));
-}
-
-TEST(Nodes, ExtractInsert) {
- constexpr char k0[] = "Very long string zero.";
- constexpr char k1[] = "Very long string one.";
- constexpr char k2[] = "Very long string two.";
- StringTable t = {{k0, ""}, {k1, ""}, {k2, ""}};
- EXPECT_THAT(t,
- UnorderedElementsAre(Pair(k0, ""), Pair(k1, ""), Pair(k2, "")));
-
- auto node = t.extract(k0);
- EXPECT_THAT(t, UnorderedElementsAre(Pair(k1, ""), Pair(k2, "")));
- EXPECT_TRUE(node);
- EXPECT_FALSE(node.empty());
-
- StringTable t2;
- StringTable::insert_return_type res = t2.insert(std::move(node));
- EXPECT_TRUE(res.inserted);
- EXPECT_THAT(*res.position, Pair(k0, ""));
- EXPECT_FALSE(res.node);
- EXPECT_THAT(t2, UnorderedElementsAre(Pair(k0, "")));
-
- // Not there.
- EXPECT_THAT(t, UnorderedElementsAre(Pair(k1, ""), Pair(k2, "")));
- node = t.extract("Not there!");
- EXPECT_THAT(t, UnorderedElementsAre(Pair(k1, ""), Pair(k2, "")));
- EXPECT_FALSE(node);
-
- // Inserting nothing.
- res = t2.insert(std::move(node));
- EXPECT_FALSE(res.inserted);
- EXPECT_EQ(res.position, t2.end());
- EXPECT_FALSE(res.node);
- EXPECT_THAT(t2, UnorderedElementsAre(Pair(k0, "")));
-
- t.emplace(k0, "1");
- node = t.extract(k0);
-
- // Insert duplicate.
- res = t2.insert(std::move(node));
- EXPECT_FALSE(res.inserted);
- EXPECT_THAT(*res.position, Pair(k0, ""));
- EXPECT_TRUE(res.node);
- EXPECT_FALSE(node);
-}
-
-TEST(Nodes, HintInsert) {
- IntTable t = {1, 2, 3};
- auto node = t.extract(1);
- EXPECT_THAT(t, UnorderedElementsAre(2, 3));
- auto it = t.insert(t.begin(), std::move(node));
- EXPECT_THAT(t, UnorderedElementsAre(1, 2, 3));
- EXPECT_EQ(*it, 1);
- EXPECT_FALSE(node);
-
- node = t.extract(2);
- EXPECT_THAT(t, UnorderedElementsAre(1, 3));
- // reinsert 2 to make the next insert fail.
- t.insert(2);
- EXPECT_THAT(t, UnorderedElementsAre(1, 2, 3));
- it = t.insert(t.begin(), std::move(node));
- EXPECT_EQ(*it, 2);
- // The node was not emptied by the insert call.
- EXPECT_TRUE(node);
-}
-
-IntTable MakeSimpleTable(size_t size) {
- IntTable t;
- while (t.size() < size) t.insert(t.size());
- return t;
-}
-
-std::vector<int> OrderOfIteration(const IntTable& t) {
- return {t.begin(), t.end()};
-}
-
-// These IterationOrderChanges tests depend on non-deterministic behavior.
-// We are injecting non-determinism from the pointer of the table, but do so in
-// a way that only the page matters. We have to retry enough times to make sure
-// we are touching different memory pages to cause the ordering to change.
-// We also need to keep the old tables around to avoid getting the same memory
-// blocks over and over.
-TEST(Table, IterationOrderChangesByInstance) {
- for (size_t size : {2, 6, 12, 20}) {
- const auto reference_table = MakeSimpleTable(size);
- const auto reference = OrderOfIteration(reference_table);
-
- std::vector<IntTable> tables;
- bool found_difference = false;
- for (int i = 0; !found_difference && i < 5000; ++i) {
- tables.push_back(MakeSimpleTable(size));
- found_difference = OrderOfIteration(tables.back()) != reference;
- }
- if (!found_difference) {
- FAIL()
- << "Iteration order remained the same across many attempts with size "
- << size;
- }
- }
-}
-
-TEST(Table, IterationOrderChangesOnRehash) {
- std::vector<IntTable> garbage;
- for (int i = 0; i < 5000; ++i) {
- auto t = MakeSimpleTable(20);
- const auto reference = OrderOfIteration(t);
- // Force rehash to the same size.
- t.rehash(0);
- auto trial = OrderOfIteration(t);
- if (trial != reference) {
- // We are done.
- return;
- }
- garbage.push_back(std::move(t));
- }
- FAIL() << "Iteration order remained the same across many attempts.";
-}
-
-// Verify that pointers are invalidated as soon as a second element is inserted.
-// This prevents dependency on pointer stability on small tables.
-TEST(Table, UnstablePointers) {
- IntTable table;
-
- const auto addr = [&](int i) {
- return reinterpret_cast<uintptr_t>(&*table.find(i));
- };
-
- table.insert(0);
- const uintptr_t old_ptr = addr(0);
-
- // This causes a rehash.
- table.insert(1);
-
- EXPECT_NE(old_ptr, addr(0));
-}
-
-bool IsAssertEnabled() {
- // Use an assert with side-effects to figure out if they are actually enabled.
- bool assert_enabled = false;
- assert([&]() { // NOLINT
- assert_enabled = true;
- return true;
- }());
- return assert_enabled;
-}
-
-TEST(TableDeathTest, InvalidIteratorAsserts) {
- if (!IsAssertEnabled()) GTEST_SKIP() << "Assertions not enabled.";
-
- IntTable t;
- // Extra simple "regexp" as regexp support is highly varied across platforms.
- EXPECT_DEATH_IF_SUPPORTED(
- t.erase(t.end()),
- "erase.* called on invalid iterator. The iterator might be an "
- "end.*iterator or may have been default constructed.");
- typename IntTable::iterator iter;
- EXPECT_DEATH_IF_SUPPORTED(
- ++iter,
- "operator.* called on invalid iterator. The iterator might be an "
- "end.*iterator or may have been default constructed.");
- t.insert(0);
- iter = t.begin();
- t.erase(iter);
- EXPECT_DEATH_IF_SUPPORTED(
- ++iter,
- "operator.* called on invalid iterator. The element might have been "
- "erased or .*the table might have rehashed.");
-}
-
-TEST(TableDeathTest, IteratorInvalidAssertsEqualityOperator) {
- if (!IsAssertEnabled()) GTEST_SKIP() << "Assertions not enabled.";
-
- IntTable t;
- t.insert(1);
- t.insert(2);
- t.insert(3);
- auto iter1 = t.begin();
- auto iter2 = std::next(iter1);
- ASSERT_NE(iter1, t.end());
- ASSERT_NE(iter2, t.end());
- t.erase(iter1);
- // Extra simple "regexp" as regexp support is highly varied across platforms.
- const char* const kDeathMessage =
- "Invalid operation on iterator. The element might have .*been erased or "
- "the table might have rehashed.";
- EXPECT_DEATH_IF_SUPPORTED(void(iter1 == iter2), kDeathMessage);
- EXPECT_DEATH_IF_SUPPORTED(void(iter2 != iter1), kDeathMessage);
- t.erase(iter2);
- EXPECT_DEATH_IF_SUPPORTED(void(iter1 == iter2), kDeathMessage);
-}
-
-#if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
-TEST(RawHashSamplerTest, Sample) {
- // Enable the feature even if the prod default is off.
- SetHashtablezEnabled(true);
- SetHashtablezSampleParameter(100);
-
- auto& sampler = GlobalHashtablezSampler();
- size_t start_size = 0;
- absl::flat_hash_set<const HashtablezInfo*> preexisting_info;
- start_size += sampler.Iterate([&](const HashtablezInfo& info) {
- preexisting_info.insert(&info);
- ++start_size;
- });
-
- std::vector<IntTable> tables;
- for (int i = 0; i < 1000000; ++i) {
- tables.emplace_back();
-
- const bool do_reserve = (i % 10 > 5);
- const bool do_rehash = !do_reserve && (i % 10 > 0);
-
- if (do_reserve) {
- // Don't reserve on all tables.
- tables.back().reserve(10 * (i % 10));
- }
-
- tables.back().insert(1);
- tables.back().insert(i % 5);
-
- if (do_rehash) {
- // Rehash some other tables.
- tables.back().rehash(10 * (i % 10));
- }
- }
- size_t end_size = 0;
- absl::flat_hash_map<size_t, int> observed_checksums;
- absl::flat_hash_map<ssize_t, int> reservations;
- end_size += sampler.Iterate([&](const HashtablezInfo& info) {
- if (preexisting_info.count(&info) == 0) {
- observed_checksums[info.hashes_bitwise_xor.load(
- std::memory_order_relaxed)]++;
- reservations[info.max_reserve.load(std::memory_order_relaxed)]++;
- }
- EXPECT_EQ(info.inline_element_size, sizeof(int64_t));
- ++end_size;
- });
-
- EXPECT_NEAR((end_size - start_size) / static_cast<double>(tables.size()),
- 0.01, 0.005);
- EXPECT_EQ(observed_checksums.size(), 5);
- for (const auto& [_, count] : observed_checksums) {
- EXPECT_NEAR((100 * count) / static_cast<double>(tables.size()), 0.2, 0.05);
- }
-
- EXPECT_EQ(reservations.size(), 10);
- for (const auto& [reservation, count] : reservations) {
- EXPECT_GE(reservation, 0);
- EXPECT_LT(reservation, 100);
-
- EXPECT_NEAR((100 * count) / static_cast<double>(tables.size()), 0.1, 0.05)
- << reservation;
- }
-}
-#endif // ABSL_INTERNAL_HASHTABLEZ_SAMPLE
-
-TEST(RawHashSamplerTest, DoNotSampleCustomAllocators) {
- // Enable the feature even if the prod default is off.
- SetHashtablezEnabled(true);
- SetHashtablezSampleParameter(100);
-
- auto& sampler = GlobalHashtablezSampler();
- size_t start_size = 0;
- start_size += sampler.Iterate([&](const HashtablezInfo&) { ++start_size; });
-
- std::vector<CustomAllocIntTable> tables;
- for (int i = 0; i < 1000000; ++i) {
- tables.emplace_back();
- tables.back().insert(1);
- }
- size_t end_size = 0;
- end_size += sampler.Iterate([&](const HashtablezInfo&) { ++end_size; });
-
- EXPECT_NEAR((end_size - start_size) / static_cast<double>(tables.size()),
- 0.00, 0.001);
-}
-
-#ifdef ABSL_HAVE_ADDRESS_SANITIZER
-TEST(Sanitizer, PoisoningUnused) {
- IntTable t;
- t.reserve(5);
- // Insert something to force an allocation.
- int64_t& v1 = *t.insert(0).first;
-
- // Make sure there is something to test.
- ASSERT_GT(t.capacity(), 1);
-
- int64_t* slots = RawHashSetTestOnlyAccess::GetSlots(t);
- for (size_t i = 0; i < t.capacity(); ++i) {
- EXPECT_EQ(slots + i != &v1, __asan_address_is_poisoned(slots + i));
- }
-}
-
-TEST(Sanitizer, PoisoningOnErase) {
- IntTable t;
- int64_t& v = *t.insert(0).first;
-
- EXPECT_FALSE(__asan_address_is_poisoned(&v));
- t.erase(0);
- EXPECT_TRUE(__asan_address_is_poisoned(&v));
-}
-#endif // ABSL_HAVE_ADDRESS_SANITIZER
-
-TEST(Table, AlignOne) {
- // We previously had a bug in which we were copying a control byte over the
- // first slot when alignof(value_type) is 1. We test repeated
- // insertions/erases and verify that the behavior is correct.
- Uint8Table t;
- std::unordered_set<uint8_t> verifier; // NOLINT
-
- // Do repeated insertions/erases from the table.
- for (int64_t i = 0; i < 100000; ++i) {
- SCOPED_TRACE(i);
- const uint8_t u = (i * -i) & 0xFF;
- auto it = t.find(u);
- auto verifier_it = verifier.find(u);
- if (it == t.end()) {
- ASSERT_EQ(verifier_it, verifier.end());
- t.insert(u);
- verifier.insert(u);
- } else {
- ASSERT_NE(verifier_it, verifier.end());
- t.erase(it);
- verifier.erase(verifier_it);
- }
- }
-
- EXPECT_EQ(t.size(), verifier.size());
- for (uint8_t u : t) {
- EXPECT_EQ(verifier.count(u), 1);
- }
-}
-
-} // namespace
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/container/internal/test_instance_tracker.cc b/third_party/abseil-cpp/absl/container/internal/test_instance_tracker.cc
deleted file mode 100644
index f9947f0..0000000
--- a/third_party/abseil-cpp/absl/container/internal/test_instance_tracker.cc
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2017 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/container/internal/test_instance_tracker.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace test_internal {
-int BaseCountedInstance::num_instances_ = 0;
-int BaseCountedInstance::num_live_instances_ = 0;
-int BaseCountedInstance::num_moves_ = 0;
-int BaseCountedInstance::num_copies_ = 0;
-int BaseCountedInstance::num_swaps_ = 0;
-int BaseCountedInstance::num_comparisons_ = 0;
-
-} // namespace test_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/container/internal/test_instance_tracker.h b/third_party/abseil-cpp/absl/container/internal/test_instance_tracker.h
deleted file mode 100644
index 5ff6fd7..0000000
--- a/third_party/abseil-cpp/absl/container/internal/test_instance_tracker.h
+++ /dev/null
@@ -1,274 +0,0 @@
-// Copyright 2017 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_CONTAINER_INTERNAL_TEST_INSTANCE_TRACKER_H_
-#define ABSL_CONTAINER_INTERNAL_TEST_INSTANCE_TRACKER_H_
-
-#include <cstdlib>
-#include <ostream>
-
-#include "absl/types/compare.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace test_internal {
-
-// A type that counts number of occurrences of the type, the live occurrences of
-// the type, as well as the number of copies, moves, swaps, and comparisons that
-// have occurred on the type. This is used as a base class for the copyable,
-// copyable+movable, and movable types below that are used in actual tests. Use
-// InstanceTracker in tests to track the number of instances.
-class BaseCountedInstance {
- public:
- explicit BaseCountedInstance(int x) : value_(x) {
- ++num_instances_;
- ++num_live_instances_;
- }
- BaseCountedInstance(const BaseCountedInstance& x)
- : value_(x.value_), is_live_(x.is_live_) {
- ++num_instances_;
- if (is_live_) ++num_live_instances_;
- ++num_copies_;
- }
- BaseCountedInstance(BaseCountedInstance&& x)
- : value_(x.value_), is_live_(x.is_live_) {
- x.is_live_ = false;
- ++num_instances_;
- ++num_moves_;
- }
- ~BaseCountedInstance() {
- --num_instances_;
- if (is_live_) --num_live_instances_;
- }
-
- BaseCountedInstance& operator=(const BaseCountedInstance& x) {
- value_ = x.value_;
- if (is_live_) --num_live_instances_;
- is_live_ = x.is_live_;
- if (is_live_) ++num_live_instances_;
- ++num_copies_;
- return *this;
- }
- BaseCountedInstance& operator=(BaseCountedInstance&& x) {
- value_ = x.value_;
- if (is_live_) --num_live_instances_;
- is_live_ = x.is_live_;
- x.is_live_ = false;
- ++num_moves_;
- return *this;
- }
-
- bool operator==(const BaseCountedInstance& x) const {
- ++num_comparisons_;
- return value_ == x.value_;
- }
-
- bool operator!=(const BaseCountedInstance& x) const {
- ++num_comparisons_;
- return value_ != x.value_;
- }
-
- bool operator<(const BaseCountedInstance& x) const {
- ++num_comparisons_;
- return value_ < x.value_;
- }
-
- bool operator>(const BaseCountedInstance& x) const {
- ++num_comparisons_;
- return value_ > x.value_;
- }
-
- bool operator<=(const BaseCountedInstance& x) const {
- ++num_comparisons_;
- return value_ <= x.value_;
- }
-
- bool operator>=(const BaseCountedInstance& x) const {
- ++num_comparisons_;
- return value_ >= x.value_;
- }
-
- absl::weak_ordering compare(const BaseCountedInstance& x) const {
- ++num_comparisons_;
- return value_ < x.value_
- ? absl::weak_ordering::less
- : value_ == x.value_ ? absl::weak_ordering::equivalent
- : absl::weak_ordering::greater;
- }
-
- int value() const {
- if (!is_live_) std::abort();
- return value_;
- }
-
- friend std::ostream& operator<<(std::ostream& o,
- const BaseCountedInstance& v) {
- return o << "[value:" << v.value() << "]";
- }
-
- // Implementation of efficient swap() that counts swaps.
- static void SwapImpl(
- BaseCountedInstance& lhs, // NOLINT(runtime/references)
- BaseCountedInstance& rhs) { // NOLINT(runtime/references)
- using std::swap;
- swap(lhs.value_, rhs.value_);
- swap(lhs.is_live_, rhs.is_live_);
- ++BaseCountedInstance::num_swaps_;
- }
-
- private:
- friend class InstanceTracker;
-
- int value_;
-
- // Indicates if the value is live, ie it hasn't been moved away from.
- bool is_live_ = true;
-
- // Number of instances.
- static int num_instances_;
-
- // Number of live instances (those that have not been moved away from.)
- static int num_live_instances_;
-
- // Number of times that BaseCountedInstance objects were moved.
- static int num_moves_;
-
- // Number of times that BaseCountedInstance objects were copied.
- static int num_copies_;
-
- // Number of times that BaseCountedInstance objects were swapped.
- static int num_swaps_;
-
- // Number of times that BaseCountedInstance objects were compared.
- static int num_comparisons_;
-};
-
-// Helper to track the BaseCountedInstance instance counters. Expects that the
-// number of instances and live_instances are the same when it is constructed
-// and when it is destructed.
-class InstanceTracker {
- public:
- InstanceTracker()
- : start_instances_(BaseCountedInstance::num_instances_),
- start_live_instances_(BaseCountedInstance::num_live_instances_) {
- ResetCopiesMovesSwaps();
- }
- ~InstanceTracker() {
- if (instances() != 0) std::abort();
- if (live_instances() != 0) std::abort();
- }
-
- // Returns the number of BaseCountedInstance instances both containing valid
- // values and those moved away from compared to when the InstanceTracker was
- // constructed
- int instances() const {
- return BaseCountedInstance::num_instances_ - start_instances_;
- }
-
- // Returns the number of live BaseCountedInstance instances compared to when
- // the InstanceTracker was constructed
- int live_instances() const {
- return BaseCountedInstance::num_live_instances_ - start_live_instances_;
- }
-
- // Returns the number of moves on BaseCountedInstance objects since
- // construction or since the last call to ResetCopiesMovesSwaps().
- int moves() const { return BaseCountedInstance::num_moves_ - start_moves_; }
-
- // Returns the number of copies on BaseCountedInstance objects since
- // construction or the last call to ResetCopiesMovesSwaps().
- int copies() const {
- return BaseCountedInstance::num_copies_ - start_copies_;
- }
-
- // Returns the number of swaps on BaseCountedInstance objects since
- // construction or the last call to ResetCopiesMovesSwaps().
- int swaps() const { return BaseCountedInstance::num_swaps_ - start_swaps_; }
-
- // Returns the number of comparisons on BaseCountedInstance objects since
- // construction or the last call to ResetCopiesMovesSwaps().
- int comparisons() const {
- return BaseCountedInstance::num_comparisons_ - start_comparisons_;
- }
-
- // Resets the base values for moves, copies, comparisons, and swaps to the
- // current values, so that subsequent Get*() calls for moves, copies,
- // comparisons, and swaps will compare to the situation at the point of this
- // call.
- void ResetCopiesMovesSwaps() {
- start_moves_ = BaseCountedInstance::num_moves_;
- start_copies_ = BaseCountedInstance::num_copies_;
- start_swaps_ = BaseCountedInstance::num_swaps_;
- start_comparisons_ = BaseCountedInstance::num_comparisons_;
- }
-
- private:
- int start_instances_;
- int start_live_instances_;
- int start_moves_;
- int start_copies_;
- int start_swaps_;
- int start_comparisons_;
-};
-
-// Copyable, not movable.
-class CopyableOnlyInstance : public BaseCountedInstance {
- public:
- explicit CopyableOnlyInstance(int x) : BaseCountedInstance(x) {}
- CopyableOnlyInstance(const CopyableOnlyInstance& rhs) = default;
- CopyableOnlyInstance& operator=(const CopyableOnlyInstance& rhs) = default;
-
- friend void swap(CopyableOnlyInstance& lhs, CopyableOnlyInstance& rhs) {
- BaseCountedInstance::SwapImpl(lhs, rhs);
- }
-
- static bool supports_move() { return false; }
-};
-
-// Copyable and movable.
-class CopyableMovableInstance : public BaseCountedInstance {
- public:
- explicit CopyableMovableInstance(int x) : BaseCountedInstance(x) {}
- CopyableMovableInstance(const CopyableMovableInstance& rhs) = default;
- CopyableMovableInstance(CopyableMovableInstance&& rhs) = default;
- CopyableMovableInstance& operator=(const CopyableMovableInstance& rhs) =
- default;
- CopyableMovableInstance& operator=(CopyableMovableInstance&& rhs) = default;
-
- friend void swap(CopyableMovableInstance& lhs, CopyableMovableInstance& rhs) {
- BaseCountedInstance::SwapImpl(lhs, rhs);
- }
-
- static bool supports_move() { return true; }
-};
-
-// Only movable, not default-constructible.
-class MovableOnlyInstance : public BaseCountedInstance {
- public:
- explicit MovableOnlyInstance(int x) : BaseCountedInstance(x) {}
- MovableOnlyInstance(MovableOnlyInstance&& other) = default;
- MovableOnlyInstance& operator=(MovableOnlyInstance&& other) = default;
-
- friend void swap(MovableOnlyInstance& lhs, MovableOnlyInstance& rhs) {
- BaseCountedInstance::SwapImpl(lhs, rhs);
- }
-
- static bool supports_move() { return true; }
-};
-
-} // namespace test_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_INTERNAL_TEST_INSTANCE_TRACKER_H_
diff --git a/third_party/abseil-cpp/absl/container/internal/test_instance_tracker_test.cc b/third_party/abseil-cpp/absl/container/internal/test_instance_tracker_test.cc
deleted file mode 100644
index 1c6a4fa..0000000
--- a/third_party/abseil-cpp/absl/container/internal/test_instance_tracker_test.cc
+++ /dev/null
@@ -1,184 +0,0 @@
-// Copyright 2017 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/container/internal/test_instance_tracker.h"
-
-#include "gtest/gtest.h"
-
-namespace {
-
-using absl::test_internal::CopyableMovableInstance;
-using absl::test_internal::CopyableOnlyInstance;
-using absl::test_internal::InstanceTracker;
-using absl::test_internal::MovableOnlyInstance;
-
-TEST(TestInstanceTracker, CopyableMovable) {
- InstanceTracker tracker;
- CopyableMovableInstance src(1);
- EXPECT_EQ(1, src.value()) << src;
- CopyableMovableInstance copy(src);
- CopyableMovableInstance move(std::move(src));
- EXPECT_EQ(1, tracker.copies());
- EXPECT_EQ(1, tracker.moves());
- EXPECT_EQ(0, tracker.swaps());
- EXPECT_EQ(3, tracker.instances());
- EXPECT_EQ(2, tracker.live_instances());
- tracker.ResetCopiesMovesSwaps();
-
- CopyableMovableInstance copy_assign(1);
- copy_assign = copy;
- CopyableMovableInstance move_assign(1);
- move_assign = std::move(move);
- EXPECT_EQ(1, tracker.copies());
- EXPECT_EQ(1, tracker.moves());
- EXPECT_EQ(0, tracker.swaps());
- EXPECT_EQ(5, tracker.instances());
- EXPECT_EQ(3, tracker.live_instances());
- tracker.ResetCopiesMovesSwaps();
-
- {
- using std::swap;
- swap(move_assign, copy);
- swap(copy, move_assign);
- EXPECT_EQ(2, tracker.swaps());
- EXPECT_EQ(0, tracker.copies());
- EXPECT_EQ(0, tracker.moves());
- EXPECT_EQ(5, tracker.instances());
- EXPECT_EQ(3, tracker.live_instances());
- }
-}
-
-TEST(TestInstanceTracker, CopyableOnly) {
- InstanceTracker tracker;
- CopyableOnlyInstance src(1);
- EXPECT_EQ(1, src.value()) << src;
- CopyableOnlyInstance copy(src);
- CopyableOnlyInstance copy2(std::move(src)); // NOLINT
- EXPECT_EQ(2, tracker.copies());
- EXPECT_EQ(0, tracker.moves());
- EXPECT_EQ(3, tracker.instances());
- EXPECT_EQ(3, tracker.live_instances());
- tracker.ResetCopiesMovesSwaps();
-
- CopyableOnlyInstance copy_assign(1);
- copy_assign = copy;
- CopyableOnlyInstance copy_assign2(1);
- copy_assign2 = std::move(copy2); // NOLINT
- EXPECT_EQ(2, tracker.copies());
- EXPECT_EQ(0, tracker.moves());
- EXPECT_EQ(5, tracker.instances());
- EXPECT_EQ(5, tracker.live_instances());
- tracker.ResetCopiesMovesSwaps();
-
- {
- using std::swap;
- swap(src, copy);
- swap(copy, src);
- EXPECT_EQ(2, tracker.swaps());
- EXPECT_EQ(0, tracker.copies());
- EXPECT_EQ(0, tracker.moves());
- EXPECT_EQ(5, tracker.instances());
- EXPECT_EQ(5, tracker.live_instances());
- }
-}
-
-TEST(TestInstanceTracker, MovableOnly) {
- InstanceTracker tracker;
- MovableOnlyInstance src(1);
- EXPECT_EQ(1, src.value()) << src;
- MovableOnlyInstance move(std::move(src));
- MovableOnlyInstance move_assign(2);
- move_assign = std::move(move);
- EXPECT_EQ(3, tracker.instances());
- EXPECT_EQ(1, tracker.live_instances());
- EXPECT_EQ(2, tracker.moves());
- EXPECT_EQ(0, tracker.copies());
- tracker.ResetCopiesMovesSwaps();
-
- {
- using std::swap;
- MovableOnlyInstance other(2);
- swap(move_assign, other);
- swap(other, move_assign);
- EXPECT_EQ(2, tracker.swaps());
- EXPECT_EQ(0, tracker.copies());
- EXPECT_EQ(0, tracker.moves());
- EXPECT_EQ(4, tracker.instances());
- EXPECT_EQ(2, tracker.live_instances());
- }
-}
-
-TEST(TestInstanceTracker, ExistingInstances) {
- CopyableMovableInstance uncounted_instance(1);
- CopyableMovableInstance uncounted_live_instance(
- std::move(uncounted_instance));
- InstanceTracker tracker;
- EXPECT_EQ(0, tracker.instances());
- EXPECT_EQ(0, tracker.live_instances());
- EXPECT_EQ(0, tracker.copies());
- {
- CopyableMovableInstance instance1(1);
- EXPECT_EQ(1, tracker.instances());
- EXPECT_EQ(1, tracker.live_instances());
- EXPECT_EQ(0, tracker.copies());
- EXPECT_EQ(0, tracker.moves());
- {
- InstanceTracker tracker2;
- CopyableMovableInstance instance2(instance1);
- CopyableMovableInstance instance3(std::move(instance2));
- EXPECT_EQ(3, tracker.instances());
- EXPECT_EQ(2, tracker.live_instances());
- EXPECT_EQ(1, tracker.copies());
- EXPECT_EQ(1, tracker.moves());
- EXPECT_EQ(2, tracker2.instances());
- EXPECT_EQ(1, tracker2.live_instances());
- EXPECT_EQ(1, tracker2.copies());
- EXPECT_EQ(1, tracker2.moves());
- }
- EXPECT_EQ(1, tracker.instances());
- EXPECT_EQ(1, tracker.live_instances());
- EXPECT_EQ(1, tracker.copies());
- EXPECT_EQ(1, tracker.moves());
- }
- EXPECT_EQ(0, tracker.instances());
- EXPECT_EQ(0, tracker.live_instances());
- EXPECT_EQ(1, tracker.copies());
- EXPECT_EQ(1, tracker.moves());
-}
-
-TEST(TestInstanceTracker, Comparisons) {
- InstanceTracker tracker;
- MovableOnlyInstance one(1), two(2);
-
- EXPECT_EQ(0, tracker.comparisons());
- EXPECT_FALSE(one == two);
- EXPECT_EQ(1, tracker.comparisons());
- EXPECT_TRUE(one != two);
- EXPECT_EQ(2, tracker.comparisons());
- EXPECT_TRUE(one < two);
- EXPECT_EQ(3, tracker.comparisons());
- EXPECT_FALSE(one > two);
- EXPECT_EQ(4, tracker.comparisons());
- EXPECT_TRUE(one <= two);
- EXPECT_EQ(5, tracker.comparisons());
- EXPECT_FALSE(one >= two);
- EXPECT_EQ(6, tracker.comparisons());
- EXPECT_TRUE(one.compare(two) < 0); // NOLINT
- EXPECT_EQ(7, tracker.comparisons());
-
- tracker.ResetCopiesMovesSwaps();
- EXPECT_EQ(0, tracker.comparisons());
-}
-
-} // namespace
diff --git a/third_party/abseil-cpp/absl/container/internal/tracked.h b/third_party/abseil-cpp/absl/container/internal/tracked.h
deleted file mode 100644
index 29f5829..0000000
--- a/third_party/abseil-cpp/absl/container/internal/tracked.h
+++ /dev/null
@@ -1,83 +0,0 @@
-// Copyright 2018 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_CONTAINER_INTERNAL_TRACKED_H_
-#define ABSL_CONTAINER_INTERNAL_TRACKED_H_
-
-#include <stddef.h>
-
-#include <memory>
-#include <utility>
-
-#include "absl/base/config.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-
-// A class that tracks its copies and moves so that it can be queried in tests.
-template <class T>
-class Tracked {
- public:
- Tracked() {}
- // NOLINTNEXTLINE(runtime/explicit)
- Tracked(const T& val) : val_(val) {}
- Tracked(const Tracked& that)
- : val_(that.val_),
- num_moves_(that.num_moves_),
- num_copies_(that.num_copies_) {
- ++(*num_copies_);
- }
- Tracked(Tracked&& that)
- : val_(std::move(that.val_)),
- num_moves_(std::move(that.num_moves_)),
- num_copies_(std::move(that.num_copies_)) {
- ++(*num_moves_);
- }
- Tracked& operator=(const Tracked& that) {
- val_ = that.val_;
- num_moves_ = that.num_moves_;
- num_copies_ = that.num_copies_;
- ++(*num_copies_);
- }
- Tracked& operator=(Tracked&& that) {
- val_ = std::move(that.val_);
- num_moves_ = std::move(that.num_moves_);
- num_copies_ = std::move(that.num_copies_);
- ++(*num_moves_);
- }
-
- const T& val() const { return val_; }
-
- friend bool operator==(const Tracked& a, const Tracked& b) {
- return a.val_ == b.val_;
- }
- friend bool operator!=(const Tracked& a, const Tracked& b) {
- return !(a == b);
- }
-
- size_t num_copies() { return *num_copies_; }
- size_t num_moves() { return *num_moves_; }
-
- private:
- T val_;
- std::shared_ptr<size_t> num_moves_ = std::make_shared<size_t>(0);
- std::shared_ptr<size_t> num_copies_ = std::make_shared<size_t>(0);
-};
-
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_INTERNAL_TRACKED_H_
diff --git a/third_party/abseil-cpp/absl/container/internal/unordered_map_constructor_test.h b/third_party/abseil-cpp/absl/container/internal/unordered_map_constructor_test.h
deleted file mode 100644
index 7e84dc2..0000000
--- a/third_party/abseil-cpp/absl/container/internal/unordered_map_constructor_test.h
+++ /dev/null
@@ -1,494 +0,0 @@
-// Copyright 2018 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_CONTAINER_INTERNAL_UNORDERED_MAP_CONSTRUCTOR_TEST_H_
-#define ABSL_CONTAINER_INTERNAL_UNORDERED_MAP_CONSTRUCTOR_TEST_H_
-
-#include <algorithm>
-#include <unordered_map>
-#include <vector>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/container/internal/hash_generator_testing.h"
-#include "absl/container/internal/hash_policy_testing.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-
-template <class UnordMap>
-class ConstructorTest : public ::testing::Test {};
-
-TYPED_TEST_SUITE_P(ConstructorTest);
-
-TYPED_TEST_P(ConstructorTest, NoArgs) {
- TypeParam m;
- EXPECT_TRUE(m.empty());
- EXPECT_THAT(m, ::testing::UnorderedElementsAre());
-}
-
-TYPED_TEST_P(ConstructorTest, BucketCount) {
- TypeParam m(123);
- EXPECT_TRUE(m.empty());
- EXPECT_THAT(m, ::testing::UnorderedElementsAre());
- EXPECT_GE(m.bucket_count(), 123);
-}
-
-TYPED_TEST_P(ConstructorTest, BucketCountHash) {
- using H = typename TypeParam::hasher;
- H hasher;
- TypeParam m(123, hasher);
- EXPECT_EQ(m.hash_function(), hasher);
- EXPECT_TRUE(m.empty());
- EXPECT_THAT(m, ::testing::UnorderedElementsAre());
- EXPECT_GE(m.bucket_count(), 123);
-}
-
-TYPED_TEST_P(ConstructorTest, BucketCountHashEqual) {
- using H = typename TypeParam::hasher;
- using E = typename TypeParam::key_equal;
- H hasher;
- E equal;
- TypeParam m(123, hasher, equal);
- EXPECT_EQ(m.hash_function(), hasher);
- EXPECT_EQ(m.key_eq(), equal);
- EXPECT_TRUE(m.empty());
- EXPECT_THAT(m, ::testing::UnorderedElementsAre());
- EXPECT_GE(m.bucket_count(), 123);
-}
-
-TYPED_TEST_P(ConstructorTest, BucketCountHashEqualAlloc) {
- using H = typename TypeParam::hasher;
- using E = typename TypeParam::key_equal;
- using A = typename TypeParam::allocator_type;
- H hasher;
- E equal;
- A alloc(0);
- TypeParam m(123, hasher, equal, alloc);
- EXPECT_EQ(m.hash_function(), hasher);
- EXPECT_EQ(m.key_eq(), equal);
- EXPECT_EQ(m.get_allocator(), alloc);
- EXPECT_TRUE(m.empty());
- EXPECT_THAT(m, ::testing::UnorderedElementsAre());
- EXPECT_GE(m.bucket_count(), 123);
-}
-
-template <typename T>
-struct is_std_unordered_map : std::false_type {};
-
-template <typename... T>
-struct is_std_unordered_map<std::unordered_map<T...>> : std::true_type {};
-
-#if defined(UNORDERED_MAP_CXX14) || defined(UNORDERED_MAP_CXX17)
-using has_cxx14_std_apis = std::true_type;
-#else
-using has_cxx14_std_apis = std::false_type;
-#endif
-
-template <typename T>
-using expect_cxx14_apis =
- absl::disjunction<absl::negation<is_std_unordered_map<T>>,
- has_cxx14_std_apis>;
-
-template <typename TypeParam>
-void BucketCountAllocTest(std::false_type) {}
-
-template <typename TypeParam>
-void BucketCountAllocTest(std::true_type) {
- using A = typename TypeParam::allocator_type;
- A alloc(0);
- TypeParam m(123, alloc);
- EXPECT_EQ(m.get_allocator(), alloc);
- EXPECT_TRUE(m.empty());
- EXPECT_THAT(m, ::testing::UnorderedElementsAre());
- EXPECT_GE(m.bucket_count(), 123);
-}
-
-TYPED_TEST_P(ConstructorTest, BucketCountAlloc) {
- BucketCountAllocTest<TypeParam>(expect_cxx14_apis<TypeParam>());
-}
-
-template <typename TypeParam>
-void BucketCountHashAllocTest(std::false_type) {}
-
-template <typename TypeParam>
-void BucketCountHashAllocTest(std::true_type) {
- using H = typename TypeParam::hasher;
- using A = typename TypeParam::allocator_type;
- H hasher;
- A alloc(0);
- TypeParam m(123, hasher, alloc);
- EXPECT_EQ(m.hash_function(), hasher);
- EXPECT_EQ(m.get_allocator(), alloc);
- EXPECT_TRUE(m.empty());
- EXPECT_THAT(m, ::testing::UnorderedElementsAre());
- EXPECT_GE(m.bucket_count(), 123);
-}
-
-TYPED_TEST_P(ConstructorTest, BucketCountHashAlloc) {
- BucketCountHashAllocTest<TypeParam>(expect_cxx14_apis<TypeParam>());
-}
-
-#if ABSL_UNORDERED_SUPPORTS_ALLOC_CTORS
-using has_alloc_std_constructors = std::true_type;
-#else
-using has_alloc_std_constructors = std::false_type;
-#endif
-
-template <typename T>
-using expect_alloc_constructors =
- absl::disjunction<absl::negation<is_std_unordered_map<T>>,
- has_alloc_std_constructors>;
-
-template <typename TypeParam>
-void AllocTest(std::false_type) {}
-
-template <typename TypeParam>
-void AllocTest(std::true_type) {
- using A = typename TypeParam::allocator_type;
- A alloc(0);
- TypeParam m(alloc);
- EXPECT_EQ(m.get_allocator(), alloc);
- EXPECT_TRUE(m.empty());
- EXPECT_THAT(m, ::testing::UnorderedElementsAre());
-}
-
-TYPED_TEST_P(ConstructorTest, Alloc) {
- AllocTest<TypeParam>(expect_alloc_constructors<TypeParam>());
-}
-
-TYPED_TEST_P(ConstructorTest, InputIteratorBucketHashEqualAlloc) {
- using T = hash_internal::GeneratedType<TypeParam>;
- using H = typename TypeParam::hasher;
- using E = typename TypeParam::key_equal;
- using A = typename TypeParam::allocator_type;
- H hasher;
- E equal;
- A alloc(0);
- std::vector<T> values;
- std::generate_n(std::back_inserter(values), 10,
- hash_internal::UniqueGenerator<T>());
- TypeParam m(values.begin(), values.end(), 123, hasher, equal, alloc);
- EXPECT_EQ(m.hash_function(), hasher);
- EXPECT_EQ(m.key_eq(), equal);
- EXPECT_EQ(m.get_allocator(), alloc);
- EXPECT_THAT(items(m), ::testing::UnorderedElementsAreArray(values));
- EXPECT_GE(m.bucket_count(), 123);
-}
-
-template <typename TypeParam>
-void InputIteratorBucketAllocTest(std::false_type) {}
-
-template <typename TypeParam>
-void InputIteratorBucketAllocTest(std::true_type) {
- using T = hash_internal::GeneratedType<TypeParam>;
- using A = typename TypeParam::allocator_type;
- A alloc(0);
- std::vector<T> values;
- std::generate_n(std::back_inserter(values), 10,
- hash_internal::UniqueGenerator<T>());
- TypeParam m(values.begin(), values.end(), 123, alloc);
- EXPECT_EQ(m.get_allocator(), alloc);
- EXPECT_THAT(items(m), ::testing::UnorderedElementsAreArray(values));
- EXPECT_GE(m.bucket_count(), 123);
-}
-
-TYPED_TEST_P(ConstructorTest, InputIteratorBucketAlloc) {
- InputIteratorBucketAllocTest<TypeParam>(expect_cxx14_apis<TypeParam>());
-}
-
-template <typename TypeParam>
-void InputIteratorBucketHashAllocTest(std::false_type) {}
-
-template <typename TypeParam>
-void InputIteratorBucketHashAllocTest(std::true_type) {
- using T = hash_internal::GeneratedType<TypeParam>;
- using H = typename TypeParam::hasher;
- using A = typename TypeParam::allocator_type;
- H hasher;
- A alloc(0);
- std::vector<T> values;
- std::generate_n(std::back_inserter(values), 10,
- hash_internal::UniqueGenerator<T>());
- TypeParam m(values.begin(), values.end(), 123, hasher, alloc);
- EXPECT_EQ(m.hash_function(), hasher);
- EXPECT_EQ(m.get_allocator(), alloc);
- EXPECT_THAT(items(m), ::testing::UnorderedElementsAreArray(values));
- EXPECT_GE(m.bucket_count(), 123);
-}
-
-TYPED_TEST_P(ConstructorTest, InputIteratorBucketHashAlloc) {
- InputIteratorBucketHashAllocTest<TypeParam>(expect_cxx14_apis<TypeParam>());
-}
-
-TYPED_TEST_P(ConstructorTest, CopyConstructor) {
- using T = hash_internal::GeneratedType<TypeParam>;
- using H = typename TypeParam::hasher;
- using E = typename TypeParam::key_equal;
- using A = typename TypeParam::allocator_type;
- H hasher;
- E equal;
- A alloc(0);
- hash_internal::UniqueGenerator<T> gen;
- TypeParam m(123, hasher, equal, alloc);
- for (size_t i = 0; i != 10; ++i) m.insert(gen());
- TypeParam n(m);
- EXPECT_EQ(m.hash_function(), n.hash_function());
- EXPECT_EQ(m.key_eq(), n.key_eq());
- EXPECT_EQ(m.get_allocator(), n.get_allocator());
- EXPECT_EQ(m, n);
-}
-
-template <typename TypeParam>
-void CopyConstructorAllocTest(std::false_type) {}
-
-template <typename TypeParam>
-void CopyConstructorAllocTest(std::true_type) {
- using T = hash_internal::GeneratedType<TypeParam>;
- using H = typename TypeParam::hasher;
- using E = typename TypeParam::key_equal;
- using A = typename TypeParam::allocator_type;
- H hasher;
- E equal;
- A alloc(0);
- hash_internal::UniqueGenerator<T> gen;
- TypeParam m(123, hasher, equal, alloc);
- for (size_t i = 0; i != 10; ++i) m.insert(gen());
- TypeParam n(m, A(11));
- EXPECT_EQ(m.hash_function(), n.hash_function());
- EXPECT_EQ(m.key_eq(), n.key_eq());
- EXPECT_NE(m.get_allocator(), n.get_allocator());
- EXPECT_EQ(m, n);
-}
-
-TYPED_TEST_P(ConstructorTest, CopyConstructorAlloc) {
- CopyConstructorAllocTest<TypeParam>(expect_alloc_constructors<TypeParam>());
-}
-
-// TODO(alkis): Test non-propagating allocators on copy constructors.
-
-TYPED_TEST_P(ConstructorTest, MoveConstructor) {
- using T = hash_internal::GeneratedType<TypeParam>;
- using H = typename TypeParam::hasher;
- using E = typename TypeParam::key_equal;
- using A = typename TypeParam::allocator_type;
- H hasher;
- E equal;
- A alloc(0);
- hash_internal::UniqueGenerator<T> gen;
- TypeParam m(123, hasher, equal, alloc);
- for (size_t i = 0; i != 10; ++i) m.insert(gen());
- TypeParam t(m);
- TypeParam n(std::move(t));
- EXPECT_EQ(m.hash_function(), n.hash_function());
- EXPECT_EQ(m.key_eq(), n.key_eq());
- EXPECT_EQ(m.get_allocator(), n.get_allocator());
- EXPECT_EQ(m, n);
-}
-
-template <typename TypeParam>
-void MoveConstructorAllocTest(std::false_type) {}
-
-template <typename TypeParam>
-void MoveConstructorAllocTest(std::true_type) {
- using T = hash_internal::GeneratedType<TypeParam>;
- using H = typename TypeParam::hasher;
- using E = typename TypeParam::key_equal;
- using A = typename TypeParam::allocator_type;
- H hasher;
- E equal;
- A alloc(0);
- hash_internal::UniqueGenerator<T> gen;
- TypeParam m(123, hasher, equal, alloc);
- for (size_t i = 0; i != 10; ++i) m.insert(gen());
- TypeParam t(m);
- TypeParam n(std::move(t), A(1));
- EXPECT_EQ(m.hash_function(), n.hash_function());
- EXPECT_EQ(m.key_eq(), n.key_eq());
- EXPECT_NE(m.get_allocator(), n.get_allocator());
- EXPECT_EQ(m, n);
-}
-
-TYPED_TEST_P(ConstructorTest, MoveConstructorAlloc) {
- MoveConstructorAllocTest<TypeParam>(expect_alloc_constructors<TypeParam>());
-}
-
-// TODO(alkis): Test non-propagating allocators on move constructors.
-
-TYPED_TEST_P(ConstructorTest, InitializerListBucketHashEqualAlloc) {
- using T = hash_internal::GeneratedType<TypeParam>;
- hash_internal::UniqueGenerator<T> gen;
- std::initializer_list<T> values = {gen(), gen(), gen(), gen(), gen()};
- using H = typename TypeParam::hasher;
- using E = typename TypeParam::key_equal;
- using A = typename TypeParam::allocator_type;
- H hasher;
- E equal;
- A alloc(0);
- TypeParam m(values, 123, hasher, equal, alloc);
- EXPECT_EQ(m.hash_function(), hasher);
- EXPECT_EQ(m.key_eq(), equal);
- EXPECT_EQ(m.get_allocator(), alloc);
- EXPECT_THAT(items(m), ::testing::UnorderedElementsAreArray(values));
- EXPECT_GE(m.bucket_count(), 123);
-}
-
-template <typename TypeParam>
-void InitializerListBucketAllocTest(std::false_type) {}
-
-template <typename TypeParam>
-void InitializerListBucketAllocTest(std::true_type) {
- using T = hash_internal::GeneratedType<TypeParam>;
- using A = typename TypeParam::allocator_type;
- hash_internal::UniqueGenerator<T> gen;
- std::initializer_list<T> values = {gen(), gen(), gen(), gen(), gen()};
- A alloc(0);
- TypeParam m(values, 123, alloc);
- EXPECT_EQ(m.get_allocator(), alloc);
- EXPECT_THAT(items(m), ::testing::UnorderedElementsAreArray(values));
- EXPECT_GE(m.bucket_count(), 123);
-}
-
-TYPED_TEST_P(ConstructorTest, InitializerListBucketAlloc) {
- InitializerListBucketAllocTest<TypeParam>(expect_cxx14_apis<TypeParam>());
-}
-
-template <typename TypeParam>
-void InitializerListBucketHashAllocTest(std::false_type) {}
-
-template <typename TypeParam>
-void InitializerListBucketHashAllocTest(std::true_type) {
- using T = hash_internal::GeneratedType<TypeParam>;
- using H = typename TypeParam::hasher;
- using A = typename TypeParam::allocator_type;
- H hasher;
- A alloc(0);
- hash_internal::UniqueGenerator<T> gen;
- std::initializer_list<T> values = {gen(), gen(), gen(), gen(), gen()};
- TypeParam m(values, 123, hasher, alloc);
- EXPECT_EQ(m.hash_function(), hasher);
- EXPECT_EQ(m.get_allocator(), alloc);
- EXPECT_THAT(items(m), ::testing::UnorderedElementsAreArray(values));
- EXPECT_GE(m.bucket_count(), 123);
-}
-
-TYPED_TEST_P(ConstructorTest, InitializerListBucketHashAlloc) {
- InitializerListBucketHashAllocTest<TypeParam>(expect_cxx14_apis<TypeParam>());
-}
-
-TYPED_TEST_P(ConstructorTest, Assignment) {
- using T = hash_internal::GeneratedType<TypeParam>;
- using H = typename TypeParam::hasher;
- using E = typename TypeParam::key_equal;
- using A = typename TypeParam::allocator_type;
- H hasher;
- E equal;
- A alloc(0);
- hash_internal::UniqueGenerator<T> gen;
- TypeParam m({gen(), gen(), gen()}, 123, hasher, equal, alloc);
- TypeParam n;
- n = m;
- EXPECT_EQ(m.hash_function(), n.hash_function());
- EXPECT_EQ(m.key_eq(), n.key_eq());
- EXPECT_EQ(m, n);
-}
-
-// TODO(alkis): Test [non-]propagating allocators on move/copy assignments
-// (it depends on traits).
-
-TYPED_TEST_P(ConstructorTest, MoveAssignment) {
- using T = hash_internal::GeneratedType<TypeParam>;
- using H = typename TypeParam::hasher;
- using E = typename TypeParam::key_equal;
- using A = typename TypeParam::allocator_type;
- H hasher;
- E equal;
- A alloc(0);
- hash_internal::UniqueGenerator<T> gen;
- TypeParam m({gen(), gen(), gen()}, 123, hasher, equal, alloc);
- TypeParam t(m);
- TypeParam n;
- n = std::move(t);
- EXPECT_EQ(m.hash_function(), n.hash_function());
- EXPECT_EQ(m.key_eq(), n.key_eq());
- EXPECT_EQ(m, n);
-}
-
-TYPED_TEST_P(ConstructorTest, AssignmentFromInitializerList) {
- using T = hash_internal::GeneratedType<TypeParam>;
- hash_internal::UniqueGenerator<T> gen;
- std::initializer_list<T> values = {gen(), gen(), gen(), gen(), gen()};
- TypeParam m;
- m = values;
- EXPECT_THAT(items(m), ::testing::UnorderedElementsAreArray(values));
-}
-
-TYPED_TEST_P(ConstructorTest, AssignmentOverwritesExisting) {
- using T = hash_internal::GeneratedType<TypeParam>;
- hash_internal::UniqueGenerator<T> gen;
- TypeParam m({gen(), gen(), gen()});
- TypeParam n({gen()});
- n = m;
- EXPECT_EQ(m, n);
-}
-
-TYPED_TEST_P(ConstructorTest, MoveAssignmentOverwritesExisting) {
- using T = hash_internal::GeneratedType<TypeParam>;
- hash_internal::UniqueGenerator<T> gen;
- TypeParam m({gen(), gen(), gen()});
- TypeParam t(m);
- TypeParam n({gen()});
- n = std::move(t);
- EXPECT_EQ(m, n);
-}
-
-TYPED_TEST_P(ConstructorTest, AssignmentFromInitializerListOverwritesExisting) {
- using T = hash_internal::GeneratedType<TypeParam>;
- hash_internal::UniqueGenerator<T> gen;
- std::initializer_list<T> values = {gen(), gen(), gen(), gen(), gen()};
- TypeParam m;
- m = values;
- EXPECT_THAT(items(m), ::testing::UnorderedElementsAreArray(values));
-}
-
-TYPED_TEST_P(ConstructorTest, AssignmentOnSelf) {
- using T = hash_internal::GeneratedType<TypeParam>;
- hash_internal::UniqueGenerator<T> gen;
- std::initializer_list<T> values = {gen(), gen(), gen(), gen(), gen()};
- TypeParam m(values);
- m = *&m; // Avoid -Wself-assign
- EXPECT_THAT(items(m), ::testing::UnorderedElementsAreArray(values));
-}
-
-// We cannot test self move as standard states that it leaves standard
-// containers in unspecified state (and in practice in causes memory-leak
-// according to heap-checker!).
-
-REGISTER_TYPED_TEST_SUITE_P(
- ConstructorTest, NoArgs, BucketCount, BucketCountHash, BucketCountHashEqual,
- BucketCountHashEqualAlloc, BucketCountAlloc, BucketCountHashAlloc, Alloc,
- InputIteratorBucketHashEqualAlloc, InputIteratorBucketAlloc,
- InputIteratorBucketHashAlloc, CopyConstructor, CopyConstructorAlloc,
- MoveConstructor, MoveConstructorAlloc, InitializerListBucketHashEqualAlloc,
- InitializerListBucketAlloc, InitializerListBucketHashAlloc, Assignment,
- MoveAssignment, AssignmentFromInitializerList, AssignmentOverwritesExisting,
- MoveAssignmentOverwritesExisting,
- AssignmentFromInitializerListOverwritesExisting, AssignmentOnSelf);
-
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_INTERNAL_UNORDERED_MAP_CONSTRUCTOR_TEST_H_
diff --git a/third_party/abseil-cpp/absl/container/internal/unordered_map_lookup_test.h b/third_party/abseil-cpp/absl/container/internal/unordered_map_lookup_test.h
deleted file mode 100644
index 3713cd9..0000000
--- a/third_party/abseil-cpp/absl/container/internal/unordered_map_lookup_test.h
+++ /dev/null
@@ -1,117 +0,0 @@
-// Copyright 2018 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_CONTAINER_INTERNAL_UNORDERED_MAP_LOOKUP_TEST_H_
-#define ABSL_CONTAINER_INTERNAL_UNORDERED_MAP_LOOKUP_TEST_H_
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/container/internal/hash_generator_testing.h"
-#include "absl/container/internal/hash_policy_testing.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-
-template <class UnordMap>
-class LookupTest : public ::testing::Test {};
-
-TYPED_TEST_SUITE_P(LookupTest);
-
-TYPED_TEST_P(LookupTest, At) {
- using T = hash_internal::GeneratedType<TypeParam>;
- std::vector<T> values;
- std::generate_n(std::back_inserter(values), 10,
- hash_internal::Generator<T>());
- TypeParam m(values.begin(), values.end());
- for (const auto& p : values) {
- const auto& val = m.at(p.first);
- EXPECT_EQ(p.second, val) << ::testing::PrintToString(p.first);
- }
-}
-
-TYPED_TEST_P(LookupTest, OperatorBracket) {
- using T = hash_internal::GeneratedType<TypeParam>;
- using V = typename TypeParam::mapped_type;
- std::vector<T> values;
- std::generate_n(std::back_inserter(values), 10,
- hash_internal::Generator<T>());
- TypeParam m;
- for (const auto& p : values) {
- auto& val = m[p.first];
- EXPECT_EQ(V(), val) << ::testing::PrintToString(p.first);
- val = p.second;
- }
- for (const auto& p : values)
- EXPECT_EQ(p.second, m[p.first]) << ::testing::PrintToString(p.first);
-}
-
-TYPED_TEST_P(LookupTest, Count) {
- using T = hash_internal::GeneratedType<TypeParam>;
- std::vector<T> values;
- std::generate_n(std::back_inserter(values), 10,
- hash_internal::Generator<T>());
- TypeParam m;
- for (const auto& p : values)
- EXPECT_EQ(0, m.count(p.first)) << ::testing::PrintToString(p.first);
- m.insert(values.begin(), values.end());
- for (const auto& p : values)
- EXPECT_EQ(1, m.count(p.first)) << ::testing::PrintToString(p.first);
-}
-
-TYPED_TEST_P(LookupTest, Find) {
- using std::get;
- using T = hash_internal::GeneratedType<TypeParam>;
- std::vector<T> values;
- std::generate_n(std::back_inserter(values), 10,
- hash_internal::Generator<T>());
- TypeParam m;
- for (const auto& p : values)
- EXPECT_TRUE(m.end() == m.find(p.first))
- << ::testing::PrintToString(p.first);
- m.insert(values.begin(), values.end());
- for (const auto& p : values) {
- auto it = m.find(p.first);
- EXPECT_TRUE(m.end() != it) << ::testing::PrintToString(p.first);
- EXPECT_EQ(p.second, get<1>(*it)) << ::testing::PrintToString(p.first);
- }
-}
-
-TYPED_TEST_P(LookupTest, EqualRange) {
- using std::get;
- using T = hash_internal::GeneratedType<TypeParam>;
- std::vector<T> values;
- std::generate_n(std::back_inserter(values), 10,
- hash_internal::Generator<T>());
- TypeParam m;
- for (const auto& p : values) {
- auto r = m.equal_range(p.first);
- ASSERT_EQ(0, std::distance(r.first, r.second));
- }
- m.insert(values.begin(), values.end());
- for (const auto& p : values) {
- auto r = m.equal_range(p.first);
- ASSERT_EQ(1, std::distance(r.first, r.second));
- EXPECT_EQ(p.second, get<1>(*r.first)) << ::testing::PrintToString(p.first);
- }
-}
-
-REGISTER_TYPED_TEST_SUITE_P(LookupTest, At, OperatorBracket, Count, Find,
- EqualRange);
-
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_INTERNAL_UNORDERED_MAP_LOOKUP_TEST_H_
diff --git a/third_party/abseil-cpp/absl/container/internal/unordered_map_members_test.h b/third_party/abseil-cpp/absl/container/internal/unordered_map_members_test.h
deleted file mode 100644
index 7d48cdb..0000000
--- a/third_party/abseil-cpp/absl/container/internal/unordered_map_members_test.h
+++ /dev/null
@@ -1,87 +0,0 @@
-// Copyright 2019 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_CONTAINER_INTERNAL_UNORDERED_MAP_MEMBERS_TEST_H_
-#define ABSL_CONTAINER_INTERNAL_UNORDERED_MAP_MEMBERS_TEST_H_
-
-#include <type_traits>
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/meta/type_traits.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-
-template <class UnordMap>
-class MembersTest : public ::testing::Test {};
-
-TYPED_TEST_SUITE_P(MembersTest);
-
-template <typename T>
-void UseType() {}
-
-TYPED_TEST_P(MembersTest, Typedefs) {
- EXPECT_TRUE((std::is_same<std::pair<const typename TypeParam::key_type,
- typename TypeParam::mapped_type>,
- typename TypeParam::value_type>()));
- EXPECT_TRUE((absl::conjunction<
- absl::negation<std::is_signed<typename TypeParam::size_type>>,
- std::is_integral<typename TypeParam::size_type>>()));
- EXPECT_TRUE((absl::conjunction<
- std::is_signed<typename TypeParam::difference_type>,
- std::is_integral<typename TypeParam::difference_type>>()));
- EXPECT_TRUE((std::is_convertible<
- decltype(std::declval<const typename TypeParam::hasher&>()(
- std::declval<const typename TypeParam::key_type&>())),
- size_t>()));
- EXPECT_TRUE((std::is_convertible<
- decltype(std::declval<const typename TypeParam::key_equal&>()(
- std::declval<const typename TypeParam::key_type&>(),
- std::declval<const typename TypeParam::key_type&>())),
- bool>()));
- EXPECT_TRUE((std::is_same<typename TypeParam::allocator_type::value_type,
- typename TypeParam::value_type>()));
- EXPECT_TRUE((std::is_same<typename TypeParam::value_type&,
- typename TypeParam::reference>()));
- EXPECT_TRUE((std::is_same<const typename TypeParam::value_type&,
- typename TypeParam::const_reference>()));
- EXPECT_TRUE((std::is_same<typename std::allocator_traits<
- typename TypeParam::allocator_type>::pointer,
- typename TypeParam::pointer>()));
- EXPECT_TRUE(
- (std::is_same<typename std::allocator_traits<
- typename TypeParam::allocator_type>::const_pointer,
- typename TypeParam::const_pointer>()));
-}
-
-TYPED_TEST_P(MembersTest, SimpleFunctions) {
- EXPECT_GT(TypeParam().max_size(), 0);
-}
-
-TYPED_TEST_P(MembersTest, BeginEnd) {
- TypeParam t = {typename TypeParam::value_type{}};
- EXPECT_EQ(t.begin(), t.cbegin());
- EXPECT_EQ(t.end(), t.cend());
- EXPECT_NE(t.begin(), t.end());
- EXPECT_NE(t.cbegin(), t.cend());
-}
-
-REGISTER_TYPED_TEST_SUITE_P(MembersTest, Typedefs, SimpleFunctions, BeginEnd);
-
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_INTERNAL_UNORDERED_MAP_MEMBERS_TEST_H_
diff --git a/third_party/abseil-cpp/absl/container/internal/unordered_map_modifiers_test.h b/third_party/abseil-cpp/absl/container/internal/unordered_map_modifiers_test.h
deleted file mode 100644
index 4d9ab30..0000000
--- a/third_party/abseil-cpp/absl/container/internal/unordered_map_modifiers_test.h
+++ /dev/null
@@ -1,352 +0,0 @@
-// Copyright 2018 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_CONTAINER_INTERNAL_UNORDERED_MAP_MODIFIERS_TEST_H_
-#define ABSL_CONTAINER_INTERNAL_UNORDERED_MAP_MODIFIERS_TEST_H_
-
-#include <memory>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/container/internal/hash_generator_testing.h"
-#include "absl/container/internal/hash_policy_testing.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-
-template <class UnordMap>
-class ModifiersTest : public ::testing::Test {};
-
-TYPED_TEST_SUITE_P(ModifiersTest);
-
-TYPED_TEST_P(ModifiersTest, Clear) {
- using T = hash_internal::GeneratedType<TypeParam>;
- std::vector<T> values;
- std::generate_n(std::back_inserter(values), 10,
- hash_internal::Generator<T>());
- TypeParam m(values.begin(), values.end());
- ASSERT_THAT(items(m), ::testing::UnorderedElementsAreArray(values));
- m.clear();
- EXPECT_THAT(items(m), ::testing::UnorderedElementsAre());
- EXPECT_TRUE(m.empty());
-}
-
-TYPED_TEST_P(ModifiersTest, Insert) {
- using T = hash_internal::GeneratedType<TypeParam>;
- using V = typename TypeParam::mapped_type;
- T val = hash_internal::Generator<T>()();
- TypeParam m;
- auto p = m.insert(val);
- EXPECT_TRUE(p.second);
- EXPECT_EQ(val, *p.first);
- T val2 = {val.first, hash_internal::Generator<V>()()};
- p = m.insert(val2);
- EXPECT_FALSE(p.second);
- EXPECT_EQ(val, *p.first);
-}
-
-TYPED_TEST_P(ModifiersTest, InsertHint) {
- using T = hash_internal::GeneratedType<TypeParam>;
- using V = typename TypeParam::mapped_type;
- T val = hash_internal::Generator<T>()();
- TypeParam m;
- auto it = m.insert(m.end(), val);
- EXPECT_TRUE(it != m.end());
- EXPECT_EQ(val, *it);
- T val2 = {val.first, hash_internal::Generator<V>()()};
- it = m.insert(it, val2);
- EXPECT_TRUE(it != m.end());
- EXPECT_EQ(val, *it);
-}
-
-TYPED_TEST_P(ModifiersTest, InsertRange) {
- using T = hash_internal::GeneratedType<TypeParam>;
- std::vector<T> values;
- std::generate_n(std::back_inserter(values), 10,
- hash_internal::Generator<T>());
- TypeParam m;
- m.insert(values.begin(), values.end());
- ASSERT_THAT(items(m), ::testing::UnorderedElementsAreArray(values));
-}
-
-TYPED_TEST_P(ModifiersTest, InsertWithinCapacity) {
- using T = hash_internal::GeneratedType<TypeParam>;
- using V = typename TypeParam::mapped_type;
- T val = hash_internal::Generator<T>()();
- TypeParam m;
- m.reserve(10);
- const size_t original_capacity = m.bucket_count();
- m.insert(val);
- EXPECT_EQ(m.bucket_count(), original_capacity);
- T val2 = {val.first, hash_internal::Generator<V>()()};
- m.insert(val2);
- EXPECT_EQ(m.bucket_count(), original_capacity);
-}
-
-TYPED_TEST_P(ModifiersTest, InsertRangeWithinCapacity) {
-#if !defined(__GLIBCXX__)
- using T = hash_internal::GeneratedType<TypeParam>;
- std::vector<T> base_values;
- std::generate_n(std::back_inserter(base_values), 10,
- hash_internal::Generator<T>());
- std::vector<T> values;
- while (values.size() != 100) {
- std::copy_n(base_values.begin(), 10, std::back_inserter(values));
- }
- TypeParam m;
- m.reserve(10);
- const size_t original_capacity = m.bucket_count();
- m.insert(values.begin(), values.end());
- EXPECT_EQ(m.bucket_count(), original_capacity);
-#endif
-}
-
-TYPED_TEST_P(ModifiersTest, InsertOrAssign) {
-#ifdef UNORDERED_MAP_CXX17
- using std::get;
- using K = typename TypeParam::key_type;
- using V = typename TypeParam::mapped_type;
- K k = hash_internal::Generator<K>()();
- V val = hash_internal::Generator<V>()();
- TypeParam m;
- auto p = m.insert_or_assign(k, val);
- EXPECT_TRUE(p.second);
- EXPECT_EQ(k, get<0>(*p.first));
- EXPECT_EQ(val, get<1>(*p.first));
- V val2 = hash_internal::Generator<V>()();
- p = m.insert_or_assign(k, val2);
- EXPECT_FALSE(p.second);
- EXPECT_EQ(k, get<0>(*p.first));
- EXPECT_EQ(val2, get<1>(*p.first));
-#endif
-}
-
-TYPED_TEST_P(ModifiersTest, InsertOrAssignHint) {
-#ifdef UNORDERED_MAP_CXX17
- using std::get;
- using K = typename TypeParam::key_type;
- using V = typename TypeParam::mapped_type;
- K k = hash_internal::Generator<K>()();
- V val = hash_internal::Generator<V>()();
- TypeParam m;
- auto it = m.insert_or_assign(m.end(), k, val);
- EXPECT_TRUE(it != m.end());
- EXPECT_EQ(k, get<0>(*it));
- EXPECT_EQ(val, get<1>(*it));
- V val2 = hash_internal::Generator<V>()();
- it = m.insert_or_assign(it, k, val2);
- EXPECT_EQ(k, get<0>(*it));
- EXPECT_EQ(val2, get<1>(*it));
-#endif
-}
-
-TYPED_TEST_P(ModifiersTest, Emplace) {
- using T = hash_internal::GeneratedType<TypeParam>;
- using V = typename TypeParam::mapped_type;
- T val = hash_internal::Generator<T>()();
- TypeParam m;
- // TODO(alkis): We need a way to run emplace in a more meaningful way. Perhaps
- // with test traits/policy.
- auto p = m.emplace(val);
- EXPECT_TRUE(p.second);
- EXPECT_EQ(val, *p.first);
- T val2 = {val.first, hash_internal::Generator<V>()()};
- p = m.emplace(val2);
- EXPECT_FALSE(p.second);
- EXPECT_EQ(val, *p.first);
-}
-
-TYPED_TEST_P(ModifiersTest, EmplaceHint) {
- using T = hash_internal::GeneratedType<TypeParam>;
- using V = typename TypeParam::mapped_type;
- T val = hash_internal::Generator<T>()();
- TypeParam m;
- // TODO(alkis): We need a way to run emplace in a more meaningful way. Perhaps
- // with test traits/policy.
- auto it = m.emplace_hint(m.end(), val);
- EXPECT_EQ(val, *it);
- T val2 = {val.first, hash_internal::Generator<V>()()};
- it = m.emplace_hint(it, val2);
- EXPECT_EQ(val, *it);
-}
-
-TYPED_TEST_P(ModifiersTest, TryEmplace) {
-#ifdef UNORDERED_MAP_CXX17
- using T = hash_internal::GeneratedType<TypeParam>;
- using V = typename TypeParam::mapped_type;
- T val = hash_internal::Generator<T>()();
- TypeParam m;
- // TODO(alkis): We need a way to run emplace in a more meaningful way. Perhaps
- // with test traits/policy.
- auto p = m.try_emplace(val.first, val.second);
- EXPECT_TRUE(p.second);
- EXPECT_EQ(val, *p.first);
- T val2 = {val.first, hash_internal::Generator<V>()()};
- p = m.try_emplace(val2.first, val2.second);
- EXPECT_FALSE(p.second);
- EXPECT_EQ(val, *p.first);
-#endif
-}
-
-TYPED_TEST_P(ModifiersTest, TryEmplaceHint) {
-#ifdef UNORDERED_MAP_CXX17
- using T = hash_internal::GeneratedType<TypeParam>;
- using V = typename TypeParam::mapped_type;
- T val = hash_internal::Generator<T>()();
- TypeParam m;
- // TODO(alkis): We need a way to run emplace in a more meaningful way. Perhaps
- // with test traits/policy.
- auto it = m.try_emplace(m.end(), val.first, val.second);
- EXPECT_EQ(val, *it);
- T val2 = {val.first, hash_internal::Generator<V>()()};
- it = m.try_emplace(it, val2.first, val2.second);
- EXPECT_EQ(val, *it);
-#endif
-}
-
-template <class V>
-using IfNotVoid = typename std::enable_if<!std::is_void<V>::value, V>::type;
-
-// In openmap we chose not to return the iterator from erase because that's
-// more expensive. As such we adapt erase to return an iterator here.
-struct EraseFirst {
- template <class Map>
- auto operator()(Map* m, int) const
- -> IfNotVoid<decltype(m->erase(m->begin()))> {
- return m->erase(m->begin());
- }
- template <class Map>
- typename Map::iterator operator()(Map* m, ...) const {
- auto it = m->begin();
- m->erase(it++);
- return it;
- }
-};
-
-TYPED_TEST_P(ModifiersTest, Erase) {
- using T = hash_internal::GeneratedType<TypeParam>;
- using std::get;
- std::vector<T> values;
- std::generate_n(std::back_inserter(values), 10,
- hash_internal::Generator<T>());
- TypeParam m(values.begin(), values.end());
- ASSERT_THAT(items(m), ::testing::UnorderedElementsAreArray(values));
- auto& first = *m.begin();
- std::vector<T> values2;
- for (const auto& val : values)
- if (get<0>(val) != get<0>(first)) values2.push_back(val);
- auto it = EraseFirst()(&m, 0);
- ASSERT_TRUE(it != m.end());
- EXPECT_EQ(1, std::count(values2.begin(), values2.end(), *it));
- EXPECT_THAT(items(m), ::testing::UnorderedElementsAreArray(values2.begin(),
- values2.end()));
-}
-
-TYPED_TEST_P(ModifiersTest, EraseRange) {
- using T = hash_internal::GeneratedType<TypeParam>;
- std::vector<T> values;
- std::generate_n(std::back_inserter(values), 10,
- hash_internal::Generator<T>());
- TypeParam m(values.begin(), values.end());
- ASSERT_THAT(items(m), ::testing::UnorderedElementsAreArray(values));
- auto it = m.erase(m.begin(), m.end());
- EXPECT_THAT(items(m), ::testing::UnorderedElementsAre());
- EXPECT_TRUE(it == m.end());
-}
-
-TYPED_TEST_P(ModifiersTest, EraseKey) {
- using T = hash_internal::GeneratedType<TypeParam>;
- std::vector<T> values;
- std::generate_n(std::back_inserter(values), 10,
- hash_internal::Generator<T>());
- TypeParam m(values.begin(), values.end());
- ASSERT_THAT(items(m), ::testing::UnorderedElementsAreArray(values));
- EXPECT_EQ(1, m.erase(values[0].first));
- EXPECT_EQ(0, std::count(m.begin(), m.end(), values[0]));
- EXPECT_THAT(items(m), ::testing::UnorderedElementsAreArray(values.begin() + 1,
- values.end()));
-}
-
-TYPED_TEST_P(ModifiersTest, Swap) {
- using T = hash_internal::GeneratedType<TypeParam>;
- std::vector<T> v1;
- std::vector<T> v2;
- std::generate_n(std::back_inserter(v1), 5, hash_internal::Generator<T>());
- std::generate_n(std::back_inserter(v2), 5, hash_internal::Generator<T>());
- TypeParam m1(v1.begin(), v1.end());
- TypeParam m2(v2.begin(), v2.end());
- EXPECT_THAT(items(m1), ::testing::UnorderedElementsAreArray(v1));
- EXPECT_THAT(items(m2), ::testing::UnorderedElementsAreArray(v2));
- m1.swap(m2);
- EXPECT_THAT(items(m1), ::testing::UnorderedElementsAreArray(v2));
- EXPECT_THAT(items(m2), ::testing::UnorderedElementsAreArray(v1));
-}
-
-// TODO(alkis): Write tests for extract.
-// TODO(alkis): Write tests for merge.
-
-REGISTER_TYPED_TEST_SUITE_P(ModifiersTest, Clear, Insert, InsertHint,
- InsertRange, InsertWithinCapacity,
- InsertRangeWithinCapacity, InsertOrAssign,
- InsertOrAssignHint, Emplace, EmplaceHint,
- TryEmplace, TryEmplaceHint, Erase, EraseRange,
- EraseKey, Swap);
-
-template <typename Type>
-struct is_unique_ptr : std::false_type {};
-
-template <typename Type>
-struct is_unique_ptr<std::unique_ptr<Type>> : std::true_type {};
-
-template <class UnordMap>
-class UniquePtrModifiersTest : public ::testing::Test {
- protected:
- UniquePtrModifiersTest() {
- static_assert(is_unique_ptr<typename UnordMap::mapped_type>::value,
- "UniquePtrModifiersTyest may only be called with a "
- "std::unique_ptr value type.");
- }
-};
-
-GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(UniquePtrModifiersTest);
-
-TYPED_TEST_SUITE_P(UniquePtrModifiersTest);
-
-// Test that we do not move from rvalue arguments if an insertion does not
-// happen.
-TYPED_TEST_P(UniquePtrModifiersTest, TryEmplace) {
-#ifdef UNORDERED_MAP_CXX17
- using T = hash_internal::GeneratedType<TypeParam>;
- using V = typename TypeParam::mapped_type;
- T val = hash_internal::Generator<T>()();
- TypeParam m;
- auto p = m.try_emplace(val.first, std::move(val.second));
- EXPECT_TRUE(p.second);
- // A moved from std::unique_ptr is guaranteed to be nullptr.
- EXPECT_EQ(val.second, nullptr);
- T val2 = {val.first, hash_internal::Generator<V>()()};
- p = m.try_emplace(val2.first, std::move(val2.second));
- EXPECT_FALSE(p.second);
- EXPECT_NE(val2.second, nullptr);
-#endif
-}
-
-REGISTER_TYPED_TEST_SUITE_P(UniquePtrModifiersTest, TryEmplace);
-
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_INTERNAL_UNORDERED_MAP_MODIFIERS_TEST_H_
diff --git a/third_party/abseil-cpp/absl/container/internal/unordered_map_test.cc b/third_party/abseil-cpp/absl/container/internal/unordered_map_test.cc
deleted file mode 100644
index 9cbf512..0000000
--- a/third_party/abseil-cpp/absl/container/internal/unordered_map_test.cc
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright 2018 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 <memory>
-#include <unordered_map>
-
-#include "absl/container/internal/unordered_map_constructor_test.h"
-#include "absl/container/internal/unordered_map_lookup_test.h"
-#include "absl/container/internal/unordered_map_members_test.h"
-#include "absl/container/internal/unordered_map_modifiers_test.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-namespace {
-
-using MapTypes = ::testing::Types<
- std::unordered_map<int, int, StatefulTestingHash, StatefulTestingEqual,
- Alloc<std::pair<const int, int>>>,
- std::unordered_map<std::string, std::string, StatefulTestingHash,
- StatefulTestingEqual,
- Alloc<std::pair<const std::string, std::string>>>>;
-
-INSTANTIATE_TYPED_TEST_SUITE_P(UnorderedMap, ConstructorTest, MapTypes);
-INSTANTIATE_TYPED_TEST_SUITE_P(UnorderedMap, LookupTest, MapTypes);
-INSTANTIATE_TYPED_TEST_SUITE_P(UnorderedMap, MembersTest, MapTypes);
-INSTANTIATE_TYPED_TEST_SUITE_P(UnorderedMap, ModifiersTest, MapTypes);
-
-using UniquePtrMapTypes = ::testing::Types<std::unordered_map<
- int, std::unique_ptr<int>, StatefulTestingHash, StatefulTestingEqual,
- Alloc<std::pair<const int, std::unique_ptr<int>>>>>;
-
-INSTANTIATE_TYPED_TEST_SUITE_P(UnorderedMap, UniquePtrModifiersTest,
- UniquePtrMapTypes);
-
-} // namespace
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/container/internal/unordered_set_constructor_test.h b/third_party/abseil-cpp/absl/container/internal/unordered_set_constructor_test.h
deleted file mode 100644
index af1116e..0000000
--- a/third_party/abseil-cpp/absl/container/internal/unordered_set_constructor_test.h
+++ /dev/null
@@ -1,496 +0,0 @@
-// Copyright 2018 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_CONTAINER_INTERNAL_UNORDERED_SET_CONSTRUCTOR_TEST_H_
-#define ABSL_CONTAINER_INTERNAL_UNORDERED_SET_CONSTRUCTOR_TEST_H_
-
-#include <algorithm>
-#include <unordered_set>
-#include <vector>
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/container/internal/hash_generator_testing.h"
-#include "absl/container/internal/hash_policy_testing.h"
-#include "absl/meta/type_traits.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-
-template <class UnordMap>
-class ConstructorTest : public ::testing::Test {};
-
-TYPED_TEST_SUITE_P(ConstructorTest);
-
-TYPED_TEST_P(ConstructorTest, NoArgs) {
- TypeParam m;
- EXPECT_TRUE(m.empty());
- EXPECT_THAT(keys(m), ::testing::UnorderedElementsAre());
-}
-
-TYPED_TEST_P(ConstructorTest, BucketCount) {
- TypeParam m(123);
- EXPECT_TRUE(m.empty());
- EXPECT_THAT(keys(m), ::testing::UnorderedElementsAre());
- EXPECT_GE(m.bucket_count(), 123);
-}
-
-TYPED_TEST_P(ConstructorTest, BucketCountHash) {
- using H = typename TypeParam::hasher;
- H hasher;
- TypeParam m(123, hasher);
- EXPECT_EQ(m.hash_function(), hasher);
- EXPECT_TRUE(m.empty());
- EXPECT_THAT(keys(m), ::testing::UnorderedElementsAre());
- EXPECT_GE(m.bucket_count(), 123);
-}
-
-TYPED_TEST_P(ConstructorTest, BucketCountHashEqual) {
- using H = typename TypeParam::hasher;
- using E = typename TypeParam::key_equal;
- H hasher;
- E equal;
- TypeParam m(123, hasher, equal);
- EXPECT_EQ(m.hash_function(), hasher);
- EXPECT_EQ(m.key_eq(), equal);
- EXPECT_TRUE(m.empty());
- EXPECT_THAT(keys(m), ::testing::UnorderedElementsAre());
- EXPECT_GE(m.bucket_count(), 123);
-}
-
-TYPED_TEST_P(ConstructorTest, BucketCountHashEqualAlloc) {
- using H = typename TypeParam::hasher;
- using E = typename TypeParam::key_equal;
- using A = typename TypeParam::allocator_type;
- H hasher;
- E equal;
- A alloc(0);
- TypeParam m(123, hasher, equal, alloc);
- EXPECT_EQ(m.hash_function(), hasher);
- EXPECT_EQ(m.key_eq(), equal);
- EXPECT_EQ(m.get_allocator(), alloc);
- EXPECT_TRUE(m.empty());
- EXPECT_THAT(keys(m), ::testing::UnorderedElementsAre());
- EXPECT_GE(m.bucket_count(), 123);
-
- const auto& cm = m;
- EXPECT_EQ(cm.hash_function(), hasher);
- EXPECT_EQ(cm.key_eq(), equal);
- EXPECT_EQ(cm.get_allocator(), alloc);
- EXPECT_TRUE(cm.empty());
- EXPECT_THAT(keys(cm), ::testing::UnorderedElementsAre());
- EXPECT_GE(cm.bucket_count(), 123);
-}
-
-template <typename T>
-struct is_std_unordered_set : std::false_type {};
-
-template <typename... T>
-struct is_std_unordered_set<std::unordered_set<T...>> : std::true_type {};
-
-#if defined(UNORDERED_SET_CXX14) || defined(UNORDERED_SET_CXX17)
-using has_cxx14_std_apis = std::true_type;
-#else
-using has_cxx14_std_apis = std::false_type;
-#endif
-
-template <typename T>
-using expect_cxx14_apis =
- absl::disjunction<absl::negation<is_std_unordered_set<T>>,
- has_cxx14_std_apis>;
-
-template <typename TypeParam>
-void BucketCountAllocTest(std::false_type) {}
-
-template <typename TypeParam>
-void BucketCountAllocTest(std::true_type) {
- using A = typename TypeParam::allocator_type;
- A alloc(0);
- TypeParam m(123, alloc);
- EXPECT_EQ(m.get_allocator(), alloc);
- EXPECT_TRUE(m.empty());
- EXPECT_THAT(keys(m), ::testing::UnorderedElementsAre());
- EXPECT_GE(m.bucket_count(), 123);
-}
-
-TYPED_TEST_P(ConstructorTest, BucketCountAlloc) {
- BucketCountAllocTest<TypeParam>(expect_cxx14_apis<TypeParam>());
-}
-
-template <typename TypeParam>
-void BucketCountHashAllocTest(std::false_type) {}
-
-template <typename TypeParam>
-void BucketCountHashAllocTest(std::true_type) {
- using H = typename TypeParam::hasher;
- using A = typename TypeParam::allocator_type;
- H hasher;
- A alloc(0);
- TypeParam m(123, hasher, alloc);
- EXPECT_EQ(m.hash_function(), hasher);
- EXPECT_EQ(m.get_allocator(), alloc);
- EXPECT_TRUE(m.empty());
- EXPECT_THAT(keys(m), ::testing::UnorderedElementsAre());
- EXPECT_GE(m.bucket_count(), 123);
-}
-
-TYPED_TEST_P(ConstructorTest, BucketCountHashAlloc) {
- BucketCountHashAllocTest<TypeParam>(expect_cxx14_apis<TypeParam>());
-}
-
-#if ABSL_UNORDERED_SUPPORTS_ALLOC_CTORS
-using has_alloc_std_constructors = std::true_type;
-#else
-using has_alloc_std_constructors = std::false_type;
-#endif
-
-template <typename T>
-using expect_alloc_constructors =
- absl::disjunction<absl::negation<is_std_unordered_set<T>>,
- has_alloc_std_constructors>;
-
-template <typename TypeParam>
-void AllocTest(std::false_type) {}
-
-template <typename TypeParam>
-void AllocTest(std::true_type) {
- using A = typename TypeParam::allocator_type;
- A alloc(0);
- TypeParam m(alloc);
- EXPECT_EQ(m.get_allocator(), alloc);
- EXPECT_TRUE(m.empty());
- EXPECT_THAT(keys(m), ::testing::UnorderedElementsAre());
-}
-
-TYPED_TEST_P(ConstructorTest, Alloc) {
- AllocTest<TypeParam>(expect_alloc_constructors<TypeParam>());
-}
-
-TYPED_TEST_P(ConstructorTest, InputIteratorBucketHashEqualAlloc) {
- using T = hash_internal::GeneratedType<TypeParam>;
- using H = typename TypeParam::hasher;
- using E = typename TypeParam::key_equal;
- using A = typename TypeParam::allocator_type;
- H hasher;
- E equal;
- A alloc(0);
- std::vector<T> values;
- for (size_t i = 0; i != 10; ++i)
- values.push_back(hash_internal::Generator<T>()());
- TypeParam m(values.begin(), values.end(), 123, hasher, equal, alloc);
- EXPECT_EQ(m.hash_function(), hasher);
- EXPECT_EQ(m.key_eq(), equal);
- EXPECT_EQ(m.get_allocator(), alloc);
- EXPECT_THAT(keys(m), ::testing::UnorderedElementsAreArray(values));
- EXPECT_GE(m.bucket_count(), 123);
-}
-
-template <typename TypeParam>
-void InputIteratorBucketAllocTest(std::false_type) {}
-
-template <typename TypeParam>
-void InputIteratorBucketAllocTest(std::true_type) {
- using T = hash_internal::GeneratedType<TypeParam>;
- using A = typename TypeParam::allocator_type;
- A alloc(0);
- std::vector<T> values;
- for (size_t i = 0; i != 10; ++i)
- values.push_back(hash_internal::Generator<T>()());
- TypeParam m(values.begin(), values.end(), 123, alloc);
- EXPECT_EQ(m.get_allocator(), alloc);
- EXPECT_THAT(keys(m), ::testing::UnorderedElementsAreArray(values));
- EXPECT_GE(m.bucket_count(), 123);
-}
-
-TYPED_TEST_P(ConstructorTest, InputIteratorBucketAlloc) {
- InputIteratorBucketAllocTest<TypeParam>(expect_cxx14_apis<TypeParam>());
-}
-
-template <typename TypeParam>
-void InputIteratorBucketHashAllocTest(std::false_type) {}
-
-template <typename TypeParam>
-void InputIteratorBucketHashAllocTest(std::true_type) {
- using T = hash_internal::GeneratedType<TypeParam>;
- using H = typename TypeParam::hasher;
- using A = typename TypeParam::allocator_type;
- H hasher;
- A alloc(0);
- std::vector<T> values;
- for (size_t i = 0; i != 10; ++i)
- values.push_back(hash_internal::Generator<T>()());
- TypeParam m(values.begin(), values.end(), 123, hasher, alloc);
- EXPECT_EQ(m.hash_function(), hasher);
- EXPECT_EQ(m.get_allocator(), alloc);
- EXPECT_THAT(keys(m), ::testing::UnorderedElementsAreArray(values));
- EXPECT_GE(m.bucket_count(), 123);
-}
-
-TYPED_TEST_P(ConstructorTest, InputIteratorBucketHashAlloc) {
- InputIteratorBucketHashAllocTest<TypeParam>(expect_cxx14_apis<TypeParam>());
-}
-
-TYPED_TEST_P(ConstructorTest, CopyConstructor) {
- using T = hash_internal::GeneratedType<TypeParam>;
- using H = typename TypeParam::hasher;
- using E = typename TypeParam::key_equal;
- using A = typename TypeParam::allocator_type;
- H hasher;
- E equal;
- A alloc(0);
- TypeParam m(123, hasher, equal, alloc);
- for (size_t i = 0; i != 10; ++i) m.insert(hash_internal::Generator<T>()());
- TypeParam n(m);
- EXPECT_EQ(m.hash_function(), n.hash_function());
- EXPECT_EQ(m.key_eq(), n.key_eq());
- EXPECT_EQ(m.get_allocator(), n.get_allocator());
- EXPECT_EQ(m, n);
- EXPECT_NE(TypeParam(0, hasher, equal, alloc), n);
-}
-
-template <typename TypeParam>
-void CopyConstructorAllocTest(std::false_type) {}
-
-template <typename TypeParam>
-void CopyConstructorAllocTest(std::true_type) {
- using T = hash_internal::GeneratedType<TypeParam>;
- using H = typename TypeParam::hasher;
- using E = typename TypeParam::key_equal;
- using A = typename TypeParam::allocator_type;
- H hasher;
- E equal;
- A alloc(0);
- TypeParam m(123, hasher, equal, alloc);
- for (size_t i = 0; i != 10; ++i) m.insert(hash_internal::Generator<T>()());
- TypeParam n(m, A(11));
- EXPECT_EQ(m.hash_function(), n.hash_function());
- EXPECT_EQ(m.key_eq(), n.key_eq());
- EXPECT_NE(m.get_allocator(), n.get_allocator());
- EXPECT_EQ(m, n);
-}
-
-TYPED_TEST_P(ConstructorTest, CopyConstructorAlloc) {
- CopyConstructorAllocTest<TypeParam>(expect_alloc_constructors<TypeParam>());
-}
-
-// TODO(alkis): Test non-propagating allocators on copy constructors.
-
-TYPED_TEST_P(ConstructorTest, MoveConstructor) {
- using T = hash_internal::GeneratedType<TypeParam>;
- using H = typename TypeParam::hasher;
- using E = typename TypeParam::key_equal;
- using A = typename TypeParam::allocator_type;
- H hasher;
- E equal;
- A alloc(0);
- TypeParam m(123, hasher, equal, alloc);
- for (size_t i = 0; i != 10; ++i) m.insert(hash_internal::Generator<T>()());
- TypeParam t(m);
- TypeParam n(std::move(t));
- EXPECT_EQ(m.hash_function(), n.hash_function());
- EXPECT_EQ(m.key_eq(), n.key_eq());
- EXPECT_EQ(m.get_allocator(), n.get_allocator());
- EXPECT_EQ(m, n);
-}
-
-template <typename TypeParam>
-void MoveConstructorAllocTest(std::false_type) {}
-
-template <typename TypeParam>
-void MoveConstructorAllocTest(std::true_type) {
- using T = hash_internal::GeneratedType<TypeParam>;
- using H = typename TypeParam::hasher;
- using E = typename TypeParam::key_equal;
- using A = typename TypeParam::allocator_type;
- H hasher;
- E equal;
- A alloc(0);
- TypeParam m(123, hasher, equal, alloc);
- for (size_t i = 0; i != 10; ++i) m.insert(hash_internal::Generator<T>()());
- TypeParam t(m);
- TypeParam n(std::move(t), A(1));
- EXPECT_EQ(m.hash_function(), n.hash_function());
- EXPECT_EQ(m.key_eq(), n.key_eq());
- EXPECT_NE(m.get_allocator(), n.get_allocator());
- EXPECT_EQ(m, n);
-}
-
-TYPED_TEST_P(ConstructorTest, MoveConstructorAlloc) {
- MoveConstructorAllocTest<TypeParam>(expect_alloc_constructors<TypeParam>());
-}
-
-// TODO(alkis): Test non-propagating allocators on move constructors.
-
-TYPED_TEST_P(ConstructorTest, InitializerListBucketHashEqualAlloc) {
- using T = hash_internal::GeneratedType<TypeParam>;
- hash_internal::Generator<T> gen;
- std::initializer_list<T> values = {gen(), gen(), gen(), gen(), gen()};
- using H = typename TypeParam::hasher;
- using E = typename TypeParam::key_equal;
- using A = typename TypeParam::allocator_type;
- H hasher;
- E equal;
- A alloc(0);
- TypeParam m(values, 123, hasher, equal, alloc);
- EXPECT_EQ(m.hash_function(), hasher);
- EXPECT_EQ(m.key_eq(), equal);
- EXPECT_EQ(m.get_allocator(), alloc);
- EXPECT_THAT(keys(m), ::testing::UnorderedElementsAreArray(values));
- EXPECT_GE(m.bucket_count(), 123);
-}
-
-template <typename TypeParam>
-void InitializerListBucketAllocTest(std::false_type) {}
-
-template <typename TypeParam>
-void InitializerListBucketAllocTest(std::true_type) {
- using T = hash_internal::GeneratedType<TypeParam>;
- using A = typename TypeParam::allocator_type;
- hash_internal::Generator<T> gen;
- std::initializer_list<T> values = {gen(), gen(), gen(), gen(), gen()};
- A alloc(0);
- TypeParam m(values, 123, alloc);
- EXPECT_EQ(m.get_allocator(), alloc);
- EXPECT_THAT(keys(m), ::testing::UnorderedElementsAreArray(values));
- EXPECT_GE(m.bucket_count(), 123);
-}
-
-TYPED_TEST_P(ConstructorTest, InitializerListBucketAlloc) {
- InitializerListBucketAllocTest<TypeParam>(expect_cxx14_apis<TypeParam>());
-}
-
-template <typename TypeParam>
-void InitializerListBucketHashAllocTest(std::false_type) {}
-
-template <typename TypeParam>
-void InitializerListBucketHashAllocTest(std::true_type) {
- using T = hash_internal::GeneratedType<TypeParam>;
- using H = typename TypeParam::hasher;
- using A = typename TypeParam::allocator_type;
- H hasher;
- A alloc(0);
- hash_internal::Generator<T> gen;
- std::initializer_list<T> values = {gen(), gen(), gen(), gen(), gen()};
- TypeParam m(values, 123, hasher, alloc);
- EXPECT_EQ(m.hash_function(), hasher);
- EXPECT_EQ(m.get_allocator(), alloc);
- EXPECT_THAT(keys(m), ::testing::UnorderedElementsAreArray(values));
- EXPECT_GE(m.bucket_count(), 123);
-}
-
-TYPED_TEST_P(ConstructorTest, InitializerListBucketHashAlloc) {
- InitializerListBucketHashAllocTest<TypeParam>(expect_cxx14_apis<TypeParam>());
-}
-
-TYPED_TEST_P(ConstructorTest, CopyAssignment) {
- using T = hash_internal::GeneratedType<TypeParam>;
- using H = typename TypeParam::hasher;
- using E = typename TypeParam::key_equal;
- using A = typename TypeParam::allocator_type;
- H hasher;
- E equal;
- A alloc(0);
- hash_internal::Generator<T> gen;
- TypeParam m({gen(), gen(), gen()}, 123, hasher, equal, alloc);
- TypeParam n;
- n = m;
- EXPECT_EQ(m.hash_function(), n.hash_function());
- EXPECT_EQ(m.key_eq(), n.key_eq());
- EXPECT_EQ(m, n);
-}
-
-// TODO(alkis): Test [non-]propagating allocators on move/copy assignments
-// (it depends on traits).
-
-TYPED_TEST_P(ConstructorTest, MoveAssignment) {
- using T = hash_internal::GeneratedType<TypeParam>;
- using H = typename TypeParam::hasher;
- using E = typename TypeParam::key_equal;
- using A = typename TypeParam::allocator_type;
- H hasher;
- E equal;
- A alloc(0);
- hash_internal::Generator<T> gen;
- TypeParam m({gen(), gen(), gen()}, 123, hasher, equal, alloc);
- TypeParam t(m);
- TypeParam n;
- n = std::move(t);
- EXPECT_EQ(m.hash_function(), n.hash_function());
- EXPECT_EQ(m.key_eq(), n.key_eq());
- EXPECT_EQ(m, n);
-}
-
-TYPED_TEST_P(ConstructorTest, AssignmentFromInitializerList) {
- using T = hash_internal::GeneratedType<TypeParam>;
- hash_internal::Generator<T> gen;
- std::initializer_list<T> values = {gen(), gen(), gen(), gen(), gen()};
- TypeParam m;
- m = values;
- EXPECT_THAT(keys(m), ::testing::UnorderedElementsAreArray(values));
-}
-
-TYPED_TEST_P(ConstructorTest, AssignmentOverwritesExisting) {
- using T = hash_internal::GeneratedType<TypeParam>;
- hash_internal::Generator<T> gen;
- TypeParam m({gen(), gen(), gen()});
- TypeParam n({gen()});
- n = m;
- EXPECT_EQ(m, n);
-}
-
-TYPED_TEST_P(ConstructorTest, MoveAssignmentOverwritesExisting) {
- using T = hash_internal::GeneratedType<TypeParam>;
- hash_internal::Generator<T> gen;
- TypeParam m({gen(), gen(), gen()});
- TypeParam t(m);
- TypeParam n({gen()});
- n = std::move(t);
- EXPECT_EQ(m, n);
-}
-
-TYPED_TEST_P(ConstructorTest, AssignmentFromInitializerListOverwritesExisting) {
- using T = hash_internal::GeneratedType<TypeParam>;
- hash_internal::Generator<T> gen;
- std::initializer_list<T> values = {gen(), gen(), gen(), gen(), gen()};
- TypeParam m;
- m = values;
- EXPECT_THAT(keys(m), ::testing::UnorderedElementsAreArray(values));
-}
-
-TYPED_TEST_P(ConstructorTest, AssignmentOnSelf) {
- using T = hash_internal::GeneratedType<TypeParam>;
- hash_internal::Generator<T> gen;
- std::initializer_list<T> values = {gen(), gen(), gen(), gen(), gen()};
- TypeParam m(values);
- m = *&m; // Avoid -Wself-assign.
- EXPECT_THAT(keys(m), ::testing::UnorderedElementsAreArray(values));
-}
-
-REGISTER_TYPED_TEST_SUITE_P(
- ConstructorTest, NoArgs, BucketCount, BucketCountHash, BucketCountHashEqual,
- BucketCountHashEqualAlloc, BucketCountAlloc, BucketCountHashAlloc, Alloc,
- InputIteratorBucketHashEqualAlloc, InputIteratorBucketAlloc,
- InputIteratorBucketHashAlloc, CopyConstructor, CopyConstructorAlloc,
- MoveConstructor, MoveConstructorAlloc, InitializerListBucketHashEqualAlloc,
- InitializerListBucketAlloc, InitializerListBucketHashAlloc, CopyAssignment,
- MoveAssignment, AssignmentFromInitializerList, AssignmentOverwritesExisting,
- MoveAssignmentOverwritesExisting,
- AssignmentFromInitializerListOverwritesExisting, AssignmentOnSelf);
-
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_INTERNAL_UNORDERED_SET_CONSTRUCTOR_TEST_H_
diff --git a/third_party/abseil-cpp/absl/container/internal/unordered_set_lookup_test.h b/third_party/abseil-cpp/absl/container/internal/unordered_set_lookup_test.h
deleted file mode 100644
index b35f766..0000000
--- a/third_party/abseil-cpp/absl/container/internal/unordered_set_lookup_test.h
+++ /dev/null
@@ -1,91 +0,0 @@
-// Copyright 2018 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_CONTAINER_INTERNAL_UNORDERED_SET_LOOKUP_TEST_H_
-#define ABSL_CONTAINER_INTERNAL_UNORDERED_SET_LOOKUP_TEST_H_
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/container/internal/hash_generator_testing.h"
-#include "absl/container/internal/hash_policy_testing.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-
-template <class UnordSet>
-class LookupTest : public ::testing::Test {};
-
-TYPED_TEST_SUITE_P(LookupTest);
-
-TYPED_TEST_P(LookupTest, Count) {
- using T = hash_internal::GeneratedType<TypeParam>;
- std::vector<T> values;
- std::generate_n(std::back_inserter(values), 10,
- hash_internal::Generator<T>());
- TypeParam m;
- for (const auto& v : values)
- EXPECT_EQ(0, m.count(v)) << ::testing::PrintToString(v);
- m.insert(values.begin(), values.end());
- for (const auto& v : values)
- EXPECT_EQ(1, m.count(v)) << ::testing::PrintToString(v);
-}
-
-TYPED_TEST_P(LookupTest, Find) {
- using T = hash_internal::GeneratedType<TypeParam>;
- std::vector<T> values;
- std::generate_n(std::back_inserter(values), 10,
- hash_internal::Generator<T>());
- TypeParam m;
- for (const auto& v : values)
- EXPECT_TRUE(m.end() == m.find(v)) << ::testing::PrintToString(v);
- m.insert(values.begin(), values.end());
- for (const auto& v : values) {
- typename TypeParam::iterator it = m.find(v);
- static_assert(std::is_same<const typename TypeParam::value_type&,
- decltype(*it)>::value,
- "");
- static_assert(std::is_same<const typename TypeParam::value_type*,
- decltype(it.operator->())>::value,
- "");
- EXPECT_TRUE(m.end() != it) << ::testing::PrintToString(v);
- EXPECT_EQ(v, *it) << ::testing::PrintToString(v);
- }
-}
-
-TYPED_TEST_P(LookupTest, EqualRange) {
- using T = hash_internal::GeneratedType<TypeParam>;
- std::vector<T> values;
- std::generate_n(std::back_inserter(values), 10,
- hash_internal::Generator<T>());
- TypeParam m;
- for (const auto& v : values) {
- auto r = m.equal_range(v);
- ASSERT_EQ(0, std::distance(r.first, r.second));
- }
- m.insert(values.begin(), values.end());
- for (const auto& v : values) {
- auto r = m.equal_range(v);
- ASSERT_EQ(1, std::distance(r.first, r.second));
- EXPECT_EQ(v, *r.first);
- }
-}
-
-REGISTER_TYPED_TEST_SUITE_P(LookupTest, Count, Find, EqualRange);
-
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_INTERNAL_UNORDERED_SET_LOOKUP_TEST_H_
diff --git a/third_party/abseil-cpp/absl/container/internal/unordered_set_members_test.h b/third_party/abseil-cpp/absl/container/internal/unordered_set_members_test.h
deleted file mode 100644
index 4c5e104..0000000
--- a/third_party/abseil-cpp/absl/container/internal/unordered_set_members_test.h
+++ /dev/null
@@ -1,86 +0,0 @@
-// Copyright 2019 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_CONTAINER_INTERNAL_UNORDERED_SET_MEMBERS_TEST_H_
-#define ABSL_CONTAINER_INTERNAL_UNORDERED_SET_MEMBERS_TEST_H_
-
-#include <type_traits>
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/meta/type_traits.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-
-template <class UnordSet>
-class MembersTest : public ::testing::Test {};
-
-TYPED_TEST_SUITE_P(MembersTest);
-
-template <typename T>
-void UseType() {}
-
-TYPED_TEST_P(MembersTest, Typedefs) {
- EXPECT_TRUE((std::is_same<typename TypeParam::key_type,
- typename TypeParam::value_type>()));
- EXPECT_TRUE((absl::conjunction<
- absl::negation<std::is_signed<typename TypeParam::size_type>>,
- std::is_integral<typename TypeParam::size_type>>()));
- EXPECT_TRUE((absl::conjunction<
- std::is_signed<typename TypeParam::difference_type>,
- std::is_integral<typename TypeParam::difference_type>>()));
- EXPECT_TRUE((std::is_convertible<
- decltype(std::declval<const typename TypeParam::hasher&>()(
- std::declval<const typename TypeParam::key_type&>())),
- size_t>()));
- EXPECT_TRUE((std::is_convertible<
- decltype(std::declval<const typename TypeParam::key_equal&>()(
- std::declval<const typename TypeParam::key_type&>(),
- std::declval<const typename TypeParam::key_type&>())),
- bool>()));
- EXPECT_TRUE((std::is_same<typename TypeParam::allocator_type::value_type,
- typename TypeParam::value_type>()));
- EXPECT_TRUE((std::is_same<typename TypeParam::value_type&,
- typename TypeParam::reference>()));
- EXPECT_TRUE((std::is_same<const typename TypeParam::value_type&,
- typename TypeParam::const_reference>()));
- EXPECT_TRUE((std::is_same<typename std::allocator_traits<
- typename TypeParam::allocator_type>::pointer,
- typename TypeParam::pointer>()));
- EXPECT_TRUE(
- (std::is_same<typename std::allocator_traits<
- typename TypeParam::allocator_type>::const_pointer,
- typename TypeParam::const_pointer>()));
-}
-
-TYPED_TEST_P(MembersTest, SimpleFunctions) {
- EXPECT_GT(TypeParam().max_size(), 0);
-}
-
-TYPED_TEST_P(MembersTest, BeginEnd) {
- TypeParam t = {typename TypeParam::value_type{}};
- EXPECT_EQ(t.begin(), t.cbegin());
- EXPECT_EQ(t.end(), t.cend());
- EXPECT_NE(t.begin(), t.end());
- EXPECT_NE(t.cbegin(), t.cend());
-}
-
-REGISTER_TYPED_TEST_SUITE_P(MembersTest, Typedefs, SimpleFunctions, BeginEnd);
-
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_INTERNAL_UNORDERED_SET_MEMBERS_TEST_H_
diff --git a/third_party/abseil-cpp/absl/container/internal/unordered_set_modifiers_test.h b/third_party/abseil-cpp/absl/container/internal/unordered_set_modifiers_test.h
deleted file mode 100644
index d8864bb..0000000
--- a/third_party/abseil-cpp/absl/container/internal/unordered_set_modifiers_test.h
+++ /dev/null
@@ -1,221 +0,0 @@
-// Copyright 2018 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_CONTAINER_INTERNAL_UNORDERED_SET_MODIFIERS_TEST_H_
-#define ABSL_CONTAINER_INTERNAL_UNORDERED_SET_MODIFIERS_TEST_H_
-
-#include "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/container/internal/hash_generator_testing.h"
-#include "absl/container/internal/hash_policy_testing.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-
-template <class UnordSet>
-class ModifiersTest : public ::testing::Test {};
-
-TYPED_TEST_SUITE_P(ModifiersTest);
-
-TYPED_TEST_P(ModifiersTest, Clear) {
- using T = hash_internal::GeneratedType<TypeParam>;
- std::vector<T> values;
- std::generate_n(std::back_inserter(values), 10,
- hash_internal::Generator<T>());
- TypeParam m(values.begin(), values.end());
- ASSERT_THAT(keys(m), ::testing::UnorderedElementsAreArray(values));
- m.clear();
- EXPECT_THAT(keys(m), ::testing::UnorderedElementsAre());
- EXPECT_TRUE(m.empty());
-}
-
-TYPED_TEST_P(ModifiersTest, Insert) {
- using T = hash_internal::GeneratedType<TypeParam>;
- T val = hash_internal::Generator<T>()();
- TypeParam m;
- auto p = m.insert(val);
- EXPECT_TRUE(p.second);
- EXPECT_EQ(val, *p.first);
- p = m.insert(val);
- EXPECT_FALSE(p.second);
-}
-
-TYPED_TEST_P(ModifiersTest, InsertHint) {
- using T = hash_internal::GeneratedType<TypeParam>;
- T val = hash_internal::Generator<T>()();
- TypeParam m;
- auto it = m.insert(m.end(), val);
- EXPECT_TRUE(it != m.end());
- EXPECT_EQ(val, *it);
- it = m.insert(it, val);
- EXPECT_TRUE(it != m.end());
- EXPECT_EQ(val, *it);
-}
-
-TYPED_TEST_P(ModifiersTest, InsertRange) {
- using T = hash_internal::GeneratedType<TypeParam>;
- std::vector<T> values;
- std::generate_n(std::back_inserter(values), 10,
- hash_internal::Generator<T>());
- TypeParam m;
- m.insert(values.begin(), values.end());
- ASSERT_THAT(keys(m), ::testing::UnorderedElementsAreArray(values));
-}
-
-TYPED_TEST_P(ModifiersTest, InsertWithinCapacity) {
- using T = hash_internal::GeneratedType<TypeParam>;
- T val = hash_internal::Generator<T>()();
- TypeParam m;
- m.reserve(10);
- const size_t original_capacity = m.bucket_count();
- m.insert(val);
- EXPECT_EQ(m.bucket_count(), original_capacity);
- m.insert(val);
- EXPECT_EQ(m.bucket_count(), original_capacity);
-}
-
-TYPED_TEST_P(ModifiersTest, InsertRangeWithinCapacity) {
-#if !defined(__GLIBCXX__)
- using T = hash_internal::GeneratedType<TypeParam>;
- std::vector<T> base_values;
- std::generate_n(std::back_inserter(base_values), 10,
- hash_internal::Generator<T>());
- std::vector<T> values;
- while (values.size() != 100) {
- values.insert(values.end(), base_values.begin(), base_values.end());
- }
- TypeParam m;
- m.reserve(10);
- const size_t original_capacity = m.bucket_count();
- m.insert(values.begin(), values.end());
- EXPECT_EQ(m.bucket_count(), original_capacity);
-#endif
-}
-
-TYPED_TEST_P(ModifiersTest, Emplace) {
- using T = hash_internal::GeneratedType<TypeParam>;
- T val = hash_internal::Generator<T>()();
- TypeParam m;
- // TODO(alkis): We need a way to run emplace in a more meaningful way. Perhaps
- // with test traits/policy.
- auto p = m.emplace(val);
- EXPECT_TRUE(p.second);
- EXPECT_EQ(val, *p.first);
- p = m.emplace(val);
- EXPECT_FALSE(p.second);
- EXPECT_EQ(val, *p.first);
-}
-
-TYPED_TEST_P(ModifiersTest, EmplaceHint) {
- using T = hash_internal::GeneratedType<TypeParam>;
- T val = hash_internal::Generator<T>()();
- TypeParam m;
- // TODO(alkis): We need a way to run emplace in a more meaningful way. Perhaps
- // with test traits/policy.
- auto it = m.emplace_hint(m.end(), val);
- EXPECT_EQ(val, *it);
- it = m.emplace_hint(it, val);
- EXPECT_EQ(val, *it);
-}
-
-template <class V>
-using IfNotVoid = typename std::enable_if<!std::is_void<V>::value, V>::type;
-
-// In openmap we chose not to return the iterator from erase because that's
-// more expensive. As such we adapt erase to return an iterator here.
-struct EraseFirst {
- template <class Map>
- auto operator()(Map* m, int) const
- -> IfNotVoid<decltype(m->erase(m->begin()))> {
- return m->erase(m->begin());
- }
- template <class Map>
- typename Map::iterator operator()(Map* m, ...) const {
- auto it = m->begin();
- m->erase(it++);
- return it;
- }
-};
-
-TYPED_TEST_P(ModifiersTest, Erase) {
- using T = hash_internal::GeneratedType<TypeParam>;
- std::vector<T> values;
- std::generate_n(std::back_inserter(values), 10,
- hash_internal::Generator<T>());
- TypeParam m(values.begin(), values.end());
- ASSERT_THAT(keys(m), ::testing::UnorderedElementsAreArray(values));
- std::vector<T> values2;
- for (const auto& val : values)
- if (val != *m.begin()) values2.push_back(val);
- auto it = EraseFirst()(&m, 0);
- ASSERT_TRUE(it != m.end());
- EXPECT_EQ(1, std::count(values2.begin(), values2.end(), *it));
- EXPECT_THAT(keys(m), ::testing::UnorderedElementsAreArray(values2.begin(),
- values2.end()));
-}
-
-TYPED_TEST_P(ModifiersTest, EraseRange) {
- using T = hash_internal::GeneratedType<TypeParam>;
- std::vector<T> values;
- std::generate_n(std::back_inserter(values), 10,
- hash_internal::Generator<T>());
- TypeParam m(values.begin(), values.end());
- ASSERT_THAT(keys(m), ::testing::UnorderedElementsAreArray(values));
- auto it = m.erase(m.begin(), m.end());
- EXPECT_THAT(keys(m), ::testing::UnorderedElementsAre());
- EXPECT_TRUE(it == m.end());
-}
-
-TYPED_TEST_P(ModifiersTest, EraseKey) {
- using T = hash_internal::GeneratedType<TypeParam>;
- std::vector<T> values;
- std::generate_n(std::back_inserter(values), 10,
- hash_internal::Generator<T>());
- TypeParam m(values.begin(), values.end());
- ASSERT_THAT(keys(m), ::testing::UnorderedElementsAreArray(values));
- EXPECT_EQ(1, m.erase(values[0]));
- EXPECT_EQ(0, std::count(m.begin(), m.end(), values[0]));
- EXPECT_THAT(keys(m), ::testing::UnorderedElementsAreArray(values.begin() + 1,
- values.end()));
-}
-
-TYPED_TEST_P(ModifiersTest, Swap) {
- using T = hash_internal::GeneratedType<TypeParam>;
- std::vector<T> v1;
- std::vector<T> v2;
- std::generate_n(std::back_inserter(v1), 5, hash_internal::Generator<T>());
- std::generate_n(std::back_inserter(v2), 5, hash_internal::Generator<T>());
- TypeParam m1(v1.begin(), v1.end());
- TypeParam m2(v2.begin(), v2.end());
- EXPECT_THAT(keys(m1), ::testing::UnorderedElementsAreArray(v1));
- EXPECT_THAT(keys(m2), ::testing::UnorderedElementsAreArray(v2));
- m1.swap(m2);
- EXPECT_THAT(keys(m1), ::testing::UnorderedElementsAreArray(v2));
- EXPECT_THAT(keys(m2), ::testing::UnorderedElementsAreArray(v1));
-}
-
-// TODO(alkis): Write tests for extract.
-// TODO(alkis): Write tests for merge.
-
-REGISTER_TYPED_TEST_SUITE_P(ModifiersTest, Clear, Insert, InsertHint,
- InsertRange, InsertWithinCapacity,
- InsertRangeWithinCapacity, Emplace, EmplaceHint,
- Erase, EraseRange, EraseKey, Swap);
-
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_INTERNAL_UNORDERED_SET_MODIFIERS_TEST_H_
diff --git a/third_party/abseil-cpp/absl/container/internal/unordered_set_test.cc b/third_party/abseil-cpp/absl/container/internal/unordered_set_test.cc
deleted file mode 100644
index a134b53..0000000
--- a/third_party/abseil-cpp/absl/container/internal/unordered_set_test.cc
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright 2018 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 <unordered_set>
-
-#include "absl/container/internal/unordered_set_constructor_test.h"
-#include "absl/container/internal/unordered_set_lookup_test.h"
-#include "absl/container/internal/unordered_set_members_test.h"
-#include "absl/container/internal/unordered_set_modifiers_test.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-namespace {
-
-using SetTypes = ::testing::Types<
- std::unordered_set<int, StatefulTestingHash, StatefulTestingEqual,
- Alloc<int>>,
- std::unordered_set<std::string, StatefulTestingHash, StatefulTestingEqual,
- Alloc<std::string>>>;
-
-INSTANTIATE_TYPED_TEST_SUITE_P(UnorderedSet, ConstructorTest, SetTypes);
-INSTANTIATE_TYPED_TEST_SUITE_P(UnorderedSet, LookupTest, SetTypes);
-INSTANTIATE_TYPED_TEST_SUITE_P(UnorderedSet, MembersTest, SetTypes);
-INSTANTIATE_TYPED_TEST_SUITE_P(UnorderedSet, ModifiersTest, SetTypes);
-
-} // namespace
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/container/node_hash_map.h b/third_party/abseil-cpp/absl/container/node_hash_map.h
deleted file mode 100644
index 6868e63..0000000
--- a/third_party/abseil-cpp/absl/container/node_hash_map.h
+++ /dev/null
@@ -1,604 +0,0 @@
-// Copyright 2018 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.
-//
-// -----------------------------------------------------------------------------
-// File: node_hash_map.h
-// -----------------------------------------------------------------------------
-//
-// An `absl::node_hash_map<K, V>` is an unordered associative container of
-// unique keys and associated values designed to be a more efficient replacement
-// for `std::unordered_map`. Like `unordered_map`, search, insertion, and
-// deletion of map elements can be done as an `O(1)` operation. However,
-// `node_hash_map` (and other unordered associative containers known as the
-// collection of Abseil "Swiss tables") contain other optimizations that result
-// in both memory and computation advantages.
-//
-// In most cases, your default choice for a hash map should be a map of type
-// `flat_hash_map`. However, if you need pointer stability and cannot store
-// a `flat_hash_map` with `unique_ptr` elements, a `node_hash_map` may be a
-// valid alternative. As well, if you are migrating your code from using
-// `std::unordered_map`, a `node_hash_map` provides a more straightforward
-// migration, because it guarantees pointer stability. Consider migrating to
-// `node_hash_map` and perhaps converting to a more efficient `flat_hash_map`
-// upon further review.
-
-#ifndef ABSL_CONTAINER_NODE_HASH_MAP_H_
-#define ABSL_CONTAINER_NODE_HASH_MAP_H_
-
-#include <tuple>
-#include <type_traits>
-#include <utility>
-
-#include "absl/algorithm/container.h"
-#include "absl/base/macros.h"
-#include "absl/container/internal/container_memory.h"
-#include "absl/container/internal/hash_function_defaults.h" // IWYU pragma: export
-#include "absl/container/internal/node_slot_policy.h"
-#include "absl/container/internal/raw_hash_map.h" // IWYU pragma: export
-#include "absl/memory/memory.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-template <class Key, class Value>
-class NodeHashMapPolicy;
-} // namespace container_internal
-
-// -----------------------------------------------------------------------------
-// absl::node_hash_map
-// -----------------------------------------------------------------------------
-//
-// An `absl::node_hash_map<K, V>` is an unordered associative container which
-// has been optimized for both speed and memory footprint in most common use
-// cases. Its interface is similar to that of `std::unordered_map<K, V>` with
-// the following notable differences:
-//
-// * Supports heterogeneous lookup, through `find()`, `operator[]()` and
-// `insert()`, provided that the map is provided a compatible heterogeneous
-// hashing function and equality operator.
-// * Contains a `capacity()` member function indicating the number of element
-// slots (open, deleted, and empty) within the hash map.
-// * Returns `void` from the `erase(iterator)` overload.
-//
-// By default, `node_hash_map` uses the `absl::Hash` hashing framework.
-// All fundamental and Abseil types that support the `absl::Hash` framework have
-// a compatible equality operator for comparing insertions into `node_hash_map`.
-// If your type is not yet supported by the `absl::Hash` framework, see
-// absl/hash/hash.h for information on extending Abseil hashing to user-defined
-// types.
-//
-// Using `absl::node_hash_map` at interface boundaries in dynamically loaded
-// libraries (e.g. .dll, .so) is unsupported due to way `absl::Hash` values may
-// be randomized across dynamically loaded libraries.
-//
-// Example:
-//
-// // Create a node hash map of three strings (that map to strings)
-// absl::node_hash_map<std::string, std::string> ducks =
-// {{"a", "huey"}, {"b", "dewey"}, {"c", "louie"}};
-//
-// // Insert a new element into the node hash map
-// ducks.insert({"d", "donald"}};
-//
-// // Force a rehash of the node hash map
-// ducks.rehash(0);
-//
-// // Find the element with the key "b"
-// std::string search_key = "b";
-// auto result = ducks.find(search_key);
-// if (result != ducks.end()) {
-// std::cout << "Result: " << result->second << std::endl;
-// }
-template <class Key, class Value,
- class Hash = absl::container_internal::hash_default_hash<Key>,
- class Eq = absl::container_internal::hash_default_eq<Key>,
- class Alloc = std::allocator<std::pair<const Key, Value>>>
-class node_hash_map
- : public absl::container_internal::raw_hash_map<
- absl::container_internal::NodeHashMapPolicy<Key, Value>, Hash, Eq,
- Alloc> {
- using Base = typename node_hash_map::raw_hash_map;
-
- public:
- // Constructors and Assignment Operators
- //
- // A node_hash_map supports the same overload set as `std::unordered_map`
- // for construction and assignment:
- //
- // * Default constructor
- //
- // // No allocation for the table's elements is made.
- // absl::node_hash_map<int, std::string> map1;
- //
- // * Initializer List constructor
- //
- // absl::node_hash_map<int, std::string> map2 =
- // {{1, "huey"}, {2, "dewey"}, {3, "louie"},};
- //
- // * Copy constructor
- //
- // absl::node_hash_map<int, std::string> map3(map2);
- //
- // * Copy assignment operator
- //
- // // Hash functor and Comparator are copied as well
- // absl::node_hash_map<int, std::string> map4;
- // map4 = map3;
- //
- // * Move constructor
- //
- // // Move is guaranteed efficient
- // absl::node_hash_map<int, std::string> map5(std::move(map4));
- //
- // * Move assignment operator
- //
- // // May be efficient if allocators are compatible
- // absl::node_hash_map<int, std::string> map6;
- // map6 = std::move(map5);
- //
- // * Range constructor
- //
- // std::vector<std::pair<int, std::string>> v = {{1, "a"}, {2, "b"}};
- // absl::node_hash_map<int, std::string> map7(v.begin(), v.end());
- node_hash_map() {}
- using Base::Base;
-
- // node_hash_map::begin()
- //
- // Returns an iterator to the beginning of the `node_hash_map`.
- using Base::begin;
-
- // node_hash_map::cbegin()
- //
- // Returns a const iterator to the beginning of the `node_hash_map`.
- using Base::cbegin;
-
- // node_hash_map::cend()
- //
- // Returns a const iterator to the end of the `node_hash_map`.
- using Base::cend;
-
- // node_hash_map::end()
- //
- // Returns an iterator to the end of the `node_hash_map`.
- using Base::end;
-
- // node_hash_map::capacity()
- //
- // Returns the number of element slots (assigned, deleted, and empty)
- // available within the `node_hash_map`.
- //
- // NOTE: this member function is particular to `absl::node_hash_map` and is
- // not provided in the `std::unordered_map` API.
- using Base::capacity;
-
- // node_hash_map::empty()
- //
- // Returns whether or not the `node_hash_map` is empty.
- using Base::empty;
-
- // node_hash_map::max_size()
- //
- // Returns the largest theoretical possible number of elements within a
- // `node_hash_map` under current memory constraints. This value can be thought
- // of as the largest value of `std::distance(begin(), end())` for a
- // `node_hash_map<K, V>`.
- using Base::max_size;
-
- // node_hash_map::size()
- //
- // Returns the number of elements currently within the `node_hash_map`.
- using Base::size;
-
- // node_hash_map::clear()
- //
- // Removes all elements from the `node_hash_map`. Invalidates any references,
- // pointers, or iterators referring to contained elements.
- //
- // NOTE: this operation may shrink the underlying buffer. To avoid shrinking
- // the underlying buffer call `erase(begin(), end())`.
- using Base::clear;
-
- // node_hash_map::erase()
- //
- // Erases elements within the `node_hash_map`. Erasing does not trigger a
- // rehash. Overloads are listed below.
- //
- // void erase(const_iterator pos):
- //
- // Erases the element at `position` of the `node_hash_map`, returning
- // `void`.
- //
- // NOTE: this return behavior is different than that of STL containers in
- // general and `std::unordered_map` in particular.
- //
- // iterator erase(const_iterator first, const_iterator last):
- //
- // Erases the elements in the open interval [`first`, `last`), returning an
- // iterator pointing to `last`.
- //
- // size_type erase(const key_type& key):
- //
- // Erases the element with the matching key, if it exists, returning the
- // number of elements erased (0 or 1).
- using Base::erase;
-
- // node_hash_map::insert()
- //
- // Inserts an element of the specified value into the `node_hash_map`,
- // returning an iterator pointing to the newly inserted element, provided that
- // an element with the given key does not already exist. If rehashing occurs
- // due to the insertion, all iterators are invalidated. Overloads are listed
- // below.
- //
- // std::pair<iterator,bool> insert(const init_type& value):
- //
- // Inserts a value into the `node_hash_map`. Returns a pair consisting of an
- // iterator to the inserted element (or to the element that prevented the
- // insertion) and a `bool` denoting whether the insertion took place.
- //
- // std::pair<iterator,bool> insert(T&& value):
- // std::pair<iterator,bool> insert(init_type&& value):
- //
- // Inserts a moveable value into the `node_hash_map`. Returns a `std::pair`
- // consisting of an iterator to the inserted element (or to the element that
- // prevented the insertion) and a `bool` denoting whether the insertion took
- // place.
- //
- // iterator insert(const_iterator hint, const init_type& value):
- // iterator insert(const_iterator hint, T&& value):
- // iterator insert(const_iterator hint, init_type&& value);
- //
- // Inserts a value, using the position of `hint` as a non-binding suggestion
- // for where to begin the insertion search. Returns an iterator to the
- // inserted element, or to the existing element that prevented the
- // insertion.
- //
- // void insert(InputIterator first, InputIterator last):
- //
- // Inserts a range of values [`first`, `last`).
- //
- // NOTE: Although the STL does not specify which element may be inserted if
- // multiple keys compare equivalently, for `node_hash_map` we guarantee the
- // first match is inserted.
- //
- // void insert(std::initializer_list<init_type> ilist):
- //
- // Inserts the elements within the initializer list `ilist`.
- //
- // NOTE: Although the STL does not specify which element may be inserted if
- // multiple keys compare equivalently within the initializer list, for
- // `node_hash_map` we guarantee the first match is inserted.
- using Base::insert;
-
- // node_hash_map::insert_or_assign()
- //
- // Inserts an element of the specified value into the `node_hash_map` provided
- // that a value with the given key does not already exist, or replaces it with
- // the element value if a key for that value already exists, returning an
- // iterator pointing to the newly inserted element. If rehashing occurs due to
- // the insertion, all iterators are invalidated. Overloads are listed
- // below.
- //
- // std::pair<iterator, bool> insert_or_assign(const init_type& k, T&& obj):
- // std::pair<iterator, bool> insert_or_assign(init_type&& k, T&& obj):
- //
- // Inserts/Assigns (or moves) the element of the specified key into the
- // `node_hash_map`.
- //
- // iterator insert_or_assign(const_iterator hint,
- // const init_type& k, T&& obj):
- // iterator insert_or_assign(const_iterator hint, init_type&& k, T&& obj):
- //
- // Inserts/Assigns (or moves) the element of the specified key into the
- // `node_hash_map` using the position of `hint` as a non-binding suggestion
- // for where to begin the insertion search.
- using Base::insert_or_assign;
-
- // node_hash_map::emplace()
- //
- // Inserts an element of the specified value by constructing it in-place
- // within the `node_hash_map`, provided that no element with the given key
- // already exists.
- //
- // The element may be constructed even if there already is an element with the
- // key in the container, in which case the newly constructed element will be
- // destroyed immediately. Prefer `try_emplace()` unless your key is not
- // copyable or moveable.
- //
- // If rehashing occurs due to the insertion, all iterators are invalidated.
- using Base::emplace;
-
- // node_hash_map::emplace_hint()
- //
- // Inserts an element of the specified value by constructing it in-place
- // within the `node_hash_map`, using the position of `hint` as a non-binding
- // suggestion for where to begin the insertion search, and only inserts
- // provided that no element with the given key already exists.
- //
- // The element may be constructed even if there already is an element with the
- // key in the container, in which case the newly constructed element will be
- // destroyed immediately. Prefer `try_emplace()` unless your key is not
- // copyable or moveable.
- //
- // If rehashing occurs due to the insertion, all iterators are invalidated.
- using Base::emplace_hint;
-
- // node_hash_map::try_emplace()
- //
- // Inserts an element of the specified value by constructing it in-place
- // within the `node_hash_map`, provided that no element with the given key
- // already exists. Unlike `emplace()`, if an element with the given key
- // already exists, we guarantee that no element is constructed.
- //
- // If rehashing occurs due to the insertion, all iterators are invalidated.
- // Overloads are listed below.
- //
- // std::pair<iterator, bool> try_emplace(const key_type& k, Args&&... args):
- // std::pair<iterator, bool> try_emplace(key_type&& k, Args&&... args):
- //
- // Inserts (via copy or move) the element of the specified key into the
- // `node_hash_map`.
- //
- // iterator try_emplace(const_iterator hint,
- // const key_type& k, Args&&... args):
- // iterator try_emplace(const_iterator hint, key_type&& k, Args&&... args):
- //
- // Inserts (via copy or move) the element of the specified key into the
- // `node_hash_map` using the position of `hint` as a non-binding suggestion
- // for where to begin the insertion search.
- //
- // All `try_emplace()` overloads make the same guarantees regarding rvalue
- // arguments as `std::unordered_map::try_emplace()`, namely that these
- // functions will not move from rvalue arguments if insertions do not happen.
- using Base::try_emplace;
-
- // node_hash_map::extract()
- //
- // Extracts the indicated element, erasing it in the process, and returns it
- // as a C++17-compatible node handle. Overloads are listed below.
- //
- // node_type extract(const_iterator position):
- //
- // Extracts the key,value pair of the element at the indicated position and
- // returns a node handle owning that extracted data.
- //
- // node_type extract(const key_type& x):
- //
- // Extracts the key,value pair of the element with a key matching the passed
- // key value and returns a node handle owning that extracted data. If the
- // `node_hash_map` does not contain an element with a matching key, this
- // function returns an empty node handle.
- //
- // NOTE: when compiled in an earlier version of C++ than C++17,
- // `node_type::key()` returns a const reference to the key instead of a
- // mutable reference. We cannot safely return a mutable reference without
- // std::launder (which is not available before C++17).
- using Base::extract;
-
- // node_hash_map::merge()
- //
- // Extracts elements from a given `source` node hash map into this
- // `node_hash_map`. If the destination `node_hash_map` already contains an
- // element with an equivalent key, that element is not extracted.
- using Base::merge;
-
- // node_hash_map::swap(node_hash_map& other)
- //
- // Exchanges the contents of this `node_hash_map` with those of the `other`
- // node hash map, avoiding invocation of any move, copy, or swap operations on
- // individual elements.
- //
- // All iterators and references on the `node_hash_map` remain valid, excepting
- // for the past-the-end iterator, which is invalidated.
- //
- // `swap()` requires that the node hash map's hashing and key equivalence
- // functions be Swappable, and are exchaged using unqualified calls to
- // non-member `swap()`. If the map's allocator has
- // `std::allocator_traits<allocator_type>::propagate_on_container_swap::value`
- // set to `true`, the allocators are also exchanged using an unqualified call
- // to non-member `swap()`; otherwise, the allocators are not swapped.
- using Base::swap;
-
- // node_hash_map::rehash(count)
- //
- // Rehashes the `node_hash_map`, setting the number of slots to be at least
- // the passed value. If the new number of slots increases the load factor more
- // than the current maximum load factor
- // (`count` < `size()` / `max_load_factor()`), then the new number of slots
- // will be at least `size()` / `max_load_factor()`.
- //
- // To force a rehash, pass rehash(0).
- using Base::rehash;
-
- // node_hash_map::reserve(count)
- //
- // Sets the number of slots in the `node_hash_map` to the number needed to
- // accommodate at least `count` total elements without exceeding the current
- // maximum load factor, and may rehash the container if needed.
- using Base::reserve;
-
- // node_hash_map::at()
- //
- // Returns a reference to the mapped value of the element with key equivalent
- // to the passed key.
- using Base::at;
-
- // node_hash_map::contains()
- //
- // Determines whether an element with a key comparing equal to the given `key`
- // exists within the `node_hash_map`, returning `true` if so or `false`
- // otherwise.
- using Base::contains;
-
- // node_hash_map::count(const Key& key) const
- //
- // Returns the number of elements with a key comparing equal to the given
- // `key` within the `node_hash_map`. note that this function will return
- // either `1` or `0` since duplicate keys are not allowed within a
- // `node_hash_map`.
- using Base::count;
-
- // node_hash_map::equal_range()
- //
- // Returns a closed range [first, last], defined by a `std::pair` of two
- // iterators, containing all elements with the passed key in the
- // `node_hash_map`.
- using Base::equal_range;
-
- // node_hash_map::find()
- //
- // Finds an element with the passed `key` within the `node_hash_map`.
- using Base::find;
-
- // node_hash_map::operator[]()
- //
- // Returns a reference to the value mapped to the passed key within the
- // `node_hash_map`, performing an `insert()` if the key does not already
- // exist. If an insertion occurs and results in a rehashing of the container,
- // all iterators are invalidated. Otherwise iterators are not affected and
- // references are not invalidated. Overloads are listed below.
- //
- // T& operator[](const Key& key):
- //
- // Inserts an init_type object constructed in-place if the element with the
- // given key does not exist.
- //
- // T& operator[](Key&& key):
- //
- // Inserts an init_type object constructed in-place provided that an element
- // with the given key does not exist.
- using Base::operator[];
-
- // node_hash_map::bucket_count()
- //
- // Returns the number of "buckets" within the `node_hash_map`.
- using Base::bucket_count;
-
- // node_hash_map::load_factor()
- //
- // Returns the current load factor of the `node_hash_map` (the average number
- // of slots occupied with a value within the hash map).
- using Base::load_factor;
-
- // node_hash_map::max_load_factor()
- //
- // Manages the maximum load factor of the `node_hash_map`. Overloads are
- // listed below.
- //
- // float node_hash_map::max_load_factor()
- //
- // Returns the current maximum load factor of the `node_hash_map`.
- //
- // void node_hash_map::max_load_factor(float ml)
- //
- // Sets the maximum load factor of the `node_hash_map` to the passed value.
- //
- // NOTE: This overload is provided only for API compatibility with the STL;
- // `node_hash_map` will ignore any set load factor and manage its rehashing
- // internally as an implementation detail.
- using Base::max_load_factor;
-
- // node_hash_map::get_allocator()
- //
- // Returns the allocator function associated with this `node_hash_map`.
- using Base::get_allocator;
-
- // node_hash_map::hash_function()
- //
- // Returns the hashing function used to hash the keys within this
- // `node_hash_map`.
- using Base::hash_function;
-
- // node_hash_map::key_eq()
- //
- // Returns the function used for comparing keys equality.
- using Base::key_eq;
-};
-
-// erase_if(node_hash_map<>, Pred)
-//
-// Erases all elements that satisfy the predicate `pred` from the container `c`.
-// Returns the number of erased elements.
-template <typename K, typename V, typename H, typename E, typename A,
- typename Predicate>
-typename node_hash_map<K, V, H, E, A>::size_type erase_if(
- node_hash_map<K, V, H, E, A>& c, Predicate pred) {
- return container_internal::EraseIf(pred, &c);
-}
-
-namespace container_internal {
-
-template <class Key, class Value>
-class NodeHashMapPolicy
- : public absl::container_internal::node_slot_policy<
- std::pair<const Key, Value>&, NodeHashMapPolicy<Key, Value>> {
- using value_type = std::pair<const Key, Value>;
-
- public:
- using key_type = Key;
- using mapped_type = Value;
- using init_type = std::pair</*non const*/ key_type, mapped_type>;
-
- template <class Allocator, class... Args>
- static value_type* new_element(Allocator* alloc, Args&&... args) {
- using PairAlloc = typename absl::allocator_traits<
- Allocator>::template rebind_alloc<value_type>;
- PairAlloc pair_alloc(*alloc);
- value_type* res =
- absl::allocator_traits<PairAlloc>::allocate(pair_alloc, 1);
- absl::allocator_traits<PairAlloc>::construct(pair_alloc, res,
- std::forward<Args>(args)...);
- return res;
- }
-
- template <class Allocator>
- static void delete_element(Allocator* alloc, value_type* pair) {
- using PairAlloc = typename absl::allocator_traits<
- Allocator>::template rebind_alloc<value_type>;
- PairAlloc pair_alloc(*alloc);
- absl::allocator_traits<PairAlloc>::destroy(pair_alloc, pair);
- absl::allocator_traits<PairAlloc>::deallocate(pair_alloc, pair, 1);
- }
-
- template <class F, class... Args>
- static decltype(absl::container_internal::DecomposePair(
- std::declval<F>(), std::declval<Args>()...))
- apply(F&& f, Args&&... args) {
- return absl::container_internal::DecomposePair(std::forward<F>(f),
- std::forward<Args>(args)...);
- }
-
- static size_t element_space_used(const value_type*) {
- return sizeof(value_type);
- }
-
- static Value& value(value_type* elem) { return elem->second; }
- static const Value& value(const value_type* elem) { return elem->second; }
-};
-} // namespace container_internal
-
-namespace container_algorithm_internal {
-
-// Specialization of trait in absl/algorithm/container.h
-template <class Key, class T, class Hash, class KeyEqual, class Allocator>
-struct IsUnorderedContainer<
- absl::node_hash_map<Key, T, Hash, KeyEqual, Allocator>> : std::true_type {};
-
-} // namespace container_algorithm_internal
-
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_NODE_HASH_MAP_H_
diff --git a/third_party/abseil-cpp/absl/container/node_hash_map_test.cc b/third_party/abseil-cpp/absl/container/node_hash_map_test.cc
deleted file mode 100644
index e941a83..0000000
--- a/third_party/abseil-cpp/absl/container/node_hash_map_test.cc
+++ /dev/null
@@ -1,278 +0,0 @@
-// Copyright 2018 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/container/node_hash_map.h"
-
-#include "absl/container/internal/tracked.h"
-#include "absl/container/internal/unordered_map_constructor_test.h"
-#include "absl/container/internal/unordered_map_lookup_test.h"
-#include "absl/container/internal/unordered_map_members_test.h"
-#include "absl/container/internal/unordered_map_modifiers_test.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-namespace {
-
-using ::testing::Field;
-using ::testing::IsEmpty;
-using ::testing::Pair;
-using ::testing::UnorderedElementsAre;
-
-using MapTypes = ::testing::Types<
- absl::node_hash_map<int, int, StatefulTestingHash, StatefulTestingEqual,
- Alloc<std::pair<const int, int>>>,
- absl::node_hash_map<std::string, std::string, StatefulTestingHash,
- StatefulTestingEqual,
- Alloc<std::pair<const std::string, std::string>>>>;
-
-INSTANTIATE_TYPED_TEST_SUITE_P(NodeHashMap, ConstructorTest, MapTypes);
-INSTANTIATE_TYPED_TEST_SUITE_P(NodeHashMap, LookupTest, MapTypes);
-INSTANTIATE_TYPED_TEST_SUITE_P(NodeHashMap, MembersTest, MapTypes);
-INSTANTIATE_TYPED_TEST_SUITE_P(NodeHashMap, ModifiersTest, MapTypes);
-
-using M = absl::node_hash_map<std::string, Tracked<int>>;
-
-TEST(NodeHashMap, Emplace) {
- M m;
- Tracked<int> t(53);
- m.emplace("a", t);
- ASSERT_EQ(0, t.num_moves());
- ASSERT_EQ(1, t.num_copies());
-
- m.emplace(std::string("a"), t);
- ASSERT_EQ(0, t.num_moves());
- ASSERT_EQ(1, t.num_copies());
-
- std::string a("a");
- m.emplace(a, t);
- ASSERT_EQ(0, t.num_moves());
- ASSERT_EQ(1, t.num_copies());
-
- const std::string ca("a");
- m.emplace(a, t);
- ASSERT_EQ(0, t.num_moves());
- ASSERT_EQ(1, t.num_copies());
-
- m.emplace(std::make_pair("a", t));
- ASSERT_EQ(0, t.num_moves());
- ASSERT_EQ(2, t.num_copies());
-
- m.emplace(std::make_pair(std::string("a"), t));
- ASSERT_EQ(0, t.num_moves());
- ASSERT_EQ(3, t.num_copies());
-
- std::pair<std::string, Tracked<int>> p("a", t);
- ASSERT_EQ(0, t.num_moves());
- ASSERT_EQ(4, t.num_copies());
- m.emplace(p);
- ASSERT_EQ(0, t.num_moves());
- ASSERT_EQ(4, t.num_copies());
-
- const std::pair<std::string, Tracked<int>> cp("a", t);
- ASSERT_EQ(0, t.num_moves());
- ASSERT_EQ(5, t.num_copies());
- m.emplace(cp);
- ASSERT_EQ(0, t.num_moves());
- ASSERT_EQ(5, t.num_copies());
-
- std::pair<const std::string, Tracked<int>> pc("a", t);
- ASSERT_EQ(0, t.num_moves());
- ASSERT_EQ(6, t.num_copies());
- m.emplace(pc);
- ASSERT_EQ(0, t.num_moves());
- ASSERT_EQ(6, t.num_copies());
-
- const std::pair<const std::string, Tracked<int>> cpc("a", t);
- ASSERT_EQ(0, t.num_moves());
- ASSERT_EQ(7, t.num_copies());
- m.emplace(cpc);
- ASSERT_EQ(0, t.num_moves());
- ASSERT_EQ(7, t.num_copies());
-
- m.emplace(std::piecewise_construct, std::forward_as_tuple("a"),
- std::forward_as_tuple(t));
- ASSERT_EQ(0, t.num_moves());
- ASSERT_EQ(7, t.num_copies());
-
- m.emplace(std::piecewise_construct, std::forward_as_tuple(std::string("a")),
- std::forward_as_tuple(t));
- ASSERT_EQ(0, t.num_moves());
- ASSERT_EQ(7, t.num_copies());
-}
-
-TEST(NodeHashMap, AssignRecursive) {
- struct Tree {
- // Verify that unordered_map<K, IncompleteType> can be instantiated.
- absl::node_hash_map<int, Tree> children;
- };
- Tree root;
- const Tree& child = root.children.emplace().first->second;
- // Verify that `lhs = rhs` doesn't read rhs after clearing lhs.
- root = child;
-}
-
-TEST(FlatHashMap, MoveOnlyKey) {
- struct Key {
- Key() = default;
- Key(Key&&) = default;
- Key& operator=(Key&&) = default;
- };
- struct Eq {
- bool operator()(const Key&, const Key&) const { return true; }
- };
- struct Hash {
- size_t operator()(const Key&) const { return 0; }
- };
- absl::node_hash_map<Key, int, Hash, Eq> m;
- m[Key()];
-}
-
-struct NonMovableKey {
- explicit NonMovableKey(int i) : i(i) {}
- NonMovableKey(NonMovableKey&&) = delete;
- int i;
-};
-struct NonMovableKeyHash {
- using is_transparent = void;
- size_t operator()(const NonMovableKey& k) const { return k.i; }
- size_t operator()(int k) const { return k; }
-};
-struct NonMovableKeyEq {
- using is_transparent = void;
- bool operator()(const NonMovableKey& a, const NonMovableKey& b) const {
- return a.i == b.i;
- }
- bool operator()(const NonMovableKey& a, int b) const { return a.i == b; }
-};
-
-TEST(NodeHashMap, MergeExtractInsert) {
- absl::node_hash_map<NonMovableKey, int, NonMovableKeyHash, NonMovableKeyEq>
- set1, set2;
- set1.emplace(std::piecewise_construct, std::make_tuple(7),
- std::make_tuple(-7));
- set1.emplace(std::piecewise_construct, std::make_tuple(17),
- std::make_tuple(-17));
-
- set2.emplace(std::piecewise_construct, std::make_tuple(7),
- std::make_tuple(-70));
- set2.emplace(std::piecewise_construct, std::make_tuple(19),
- std::make_tuple(-190));
-
- auto Elem = [](int key, int value) {
- return Pair(Field(&NonMovableKey::i, key), value);
- };
-
- EXPECT_THAT(set1, UnorderedElementsAre(Elem(7, -7), Elem(17, -17)));
- EXPECT_THAT(set2, UnorderedElementsAre(Elem(7, -70), Elem(19, -190)));
-
- // NonMovableKey is neither copyable nor movable. We should still be able to
- // move nodes around.
- static_assert(!std::is_move_constructible<NonMovableKey>::value, "");
- set1.merge(set2);
-
- EXPECT_THAT(set1,
- UnorderedElementsAre(Elem(7, -7), Elem(17, -17), Elem(19, -190)));
- EXPECT_THAT(set2, UnorderedElementsAre(Elem(7, -70)));
-
- auto node = set1.extract(7);
- EXPECT_TRUE(node);
- EXPECT_EQ(node.key().i, 7);
- EXPECT_EQ(node.mapped(), -7);
- EXPECT_THAT(set1, UnorderedElementsAre(Elem(17, -17), Elem(19, -190)));
-
- auto insert_result = set2.insert(std::move(node));
- EXPECT_FALSE(node);
- EXPECT_FALSE(insert_result.inserted);
- EXPECT_TRUE(insert_result.node);
- EXPECT_EQ(insert_result.node.key().i, 7);
- EXPECT_EQ(insert_result.node.mapped(), -7);
- EXPECT_THAT(*insert_result.position, Elem(7, -70));
- EXPECT_THAT(set2, UnorderedElementsAre(Elem(7, -70)));
-
- node = set1.extract(17);
- EXPECT_TRUE(node);
- EXPECT_EQ(node.key().i, 17);
- EXPECT_EQ(node.mapped(), -17);
- EXPECT_THAT(set1, UnorderedElementsAre(Elem(19, -190)));
-
- node.mapped() = 23;
-
- insert_result = set2.insert(std::move(node));
- EXPECT_FALSE(node);
- EXPECT_TRUE(insert_result.inserted);
- EXPECT_FALSE(insert_result.node);
- EXPECT_THAT(*insert_result.position, Elem(17, 23));
- EXPECT_THAT(set2, UnorderedElementsAre(Elem(7, -70), Elem(17, 23)));
-}
-
-bool FirstIsEven(std::pair<const int, int> p) { return p.first % 2 == 0; }
-
-TEST(NodeHashMap, EraseIf) {
- // Erase all elements.
- {
- node_hash_map<int, int> s = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}};
- EXPECT_EQ(erase_if(s, [](std::pair<const int, int>) { return true; }), 5);
- EXPECT_THAT(s, IsEmpty());
- }
- // Erase no elements.
- {
- node_hash_map<int, int> s = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}};
- EXPECT_EQ(erase_if(s, [](std::pair<const int, int>) { return false; }), 0);
- EXPECT_THAT(s, UnorderedElementsAre(Pair(1, 1), Pair(2, 2), Pair(3, 3),
- Pair(4, 4), Pair(5, 5)));
- }
- // Erase specific elements.
- {
- node_hash_map<int, int> s = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}};
- EXPECT_EQ(erase_if(s,
- [](std::pair<const int, int> kvp) {
- return kvp.first % 2 == 1;
- }),
- 3);
- EXPECT_THAT(s, UnorderedElementsAre(Pair(2, 2), Pair(4, 4)));
- }
- // Predicate is function reference.
- {
- node_hash_map<int, int> s = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}};
- EXPECT_EQ(erase_if(s, FirstIsEven), 2);
- EXPECT_THAT(s, UnorderedElementsAre(Pair(1, 1), Pair(3, 3), Pair(5, 5)));
- }
- // Predicate is function pointer.
- {
- node_hash_map<int, int> s = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}};
- EXPECT_EQ(erase_if(s, &FirstIsEven), 2);
- EXPECT_THAT(s, UnorderedElementsAre(Pair(1, 1), Pair(3, 3), Pair(5, 5)));
- }
-}
-
-// This test requires std::launder for mutable key access in node handles.
-#if defined(__cpp_lib_launder) && __cpp_lib_launder >= 201606
-TEST(NodeHashMap, NodeHandleMutableKeyAccess) {
- node_hash_map<std::string, std::string> map;
-
- map["key1"] = "mapped";
-
- auto nh = map.extract(map.begin());
- nh.key().resize(3);
- map.insert(std::move(nh));
-
- EXPECT_THAT(map, testing::ElementsAre(Pair("key", "mapped")));
-}
-#endif
-
-} // namespace
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/container/node_hash_set.h b/third_party/abseil-cpp/absl/container/node_hash_set.h
deleted file mode 100644
index f2cc70c..0000000
--- a/third_party/abseil-cpp/absl/container/node_hash_set.h
+++ /dev/null
@@ -1,500 +0,0 @@
-// Copyright 2018 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.
-//
-// -----------------------------------------------------------------------------
-// File: node_hash_set.h
-// -----------------------------------------------------------------------------
-//
-// An `absl::node_hash_set<T>` is an unordered associative container designed to
-// be a more efficient replacement for `std::unordered_set`. Like
-// `unordered_set`, search, insertion, and deletion of set elements can be done
-// as an `O(1)` operation. However, `node_hash_set` (and other unordered
-// associative containers known as the collection of Abseil "Swiss tables")
-// contain other optimizations that result in both memory and computation
-// advantages.
-//
-// In most cases, your default choice for a hash table should be a map of type
-// `flat_hash_map` or a set of type `flat_hash_set`. However, if you need
-// pointer stability, a `node_hash_set` should be your preferred choice. As
-// well, if you are migrating your code from using `std::unordered_set`, a
-// `node_hash_set` should be an easy migration. Consider migrating to
-// `node_hash_set` and perhaps converting to a more efficient `flat_hash_set`
-// upon further review.
-
-#ifndef ABSL_CONTAINER_NODE_HASH_SET_H_
-#define ABSL_CONTAINER_NODE_HASH_SET_H_
-
-#include <type_traits>
-
-#include "absl/algorithm/container.h"
-#include "absl/base/macros.h"
-#include "absl/container/internal/hash_function_defaults.h" // IWYU pragma: export
-#include "absl/container/internal/node_slot_policy.h"
-#include "absl/container/internal/raw_hash_set.h" // IWYU pragma: export
-#include "absl/memory/memory.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-template <typename T>
-struct NodeHashSetPolicy;
-} // namespace container_internal
-
-// -----------------------------------------------------------------------------
-// absl::node_hash_set
-// -----------------------------------------------------------------------------
-//
-// An `absl::node_hash_set<T>` is an unordered associative container which
-// has been optimized for both speed and memory footprint in most common use
-// cases. Its interface is similar to that of `std::unordered_set<T>` with the
-// following notable differences:
-//
-// * Supports heterogeneous lookup, through `find()`, `operator[]()` and
-// `insert()`, provided that the set is provided a compatible heterogeneous
-// hashing function and equality operator.
-// * Contains a `capacity()` member function indicating the number of element
-// slots (open, deleted, and empty) within the hash set.
-// * Returns `void` from the `erase(iterator)` overload.
-//
-// By default, `node_hash_set` uses the `absl::Hash` hashing framework.
-// All fundamental and Abseil types that support the `absl::Hash` framework have
-// a compatible equality operator for comparing insertions into `node_hash_set`.
-// If your type is not yet supported by the `absl::Hash` framework, see
-// absl/hash/hash.h for information on extending Abseil hashing to user-defined
-// types.
-//
-// Using `absl::node_hash_set` at interface boundaries in dynamically loaded
-// libraries (e.g. .dll, .so) is unsupported due to way `absl::Hash` values may
-// be randomized across dynamically loaded libraries.
-//
-// Example:
-//
-// // Create a node hash set of three strings
-// absl::node_hash_set<std::string> ducks =
-// {"huey", "dewey", "louie"};
-//
-// // Insert a new element into the node hash set
-// ducks.insert("donald");
-//
-// // Force a rehash of the node hash set
-// ducks.rehash(0);
-//
-// // See if "dewey" is present
-// if (ducks.contains("dewey")) {
-// std::cout << "We found dewey!" << std::endl;
-// }
-template <class T, class Hash = absl::container_internal::hash_default_hash<T>,
- class Eq = absl::container_internal::hash_default_eq<T>,
- class Alloc = std::allocator<T>>
-class node_hash_set
- : public absl::container_internal::raw_hash_set<
- absl::container_internal::NodeHashSetPolicy<T>, Hash, Eq, Alloc> {
- using Base = typename node_hash_set::raw_hash_set;
-
- public:
- // Constructors and Assignment Operators
- //
- // A node_hash_set supports the same overload set as `std::unordered_set`
- // for construction and assignment:
- //
- // * Default constructor
- //
- // // No allocation for the table's elements is made.
- // absl::node_hash_set<std::string> set1;
- //
- // * Initializer List constructor
- //
- // absl::node_hash_set<std::string> set2 =
- // {{"huey"}, {"dewey"}, {"louie"}};
- //
- // * Copy constructor
- //
- // absl::node_hash_set<std::string> set3(set2);
- //
- // * Copy assignment operator
- //
- // // Hash functor and Comparator are copied as well
- // absl::node_hash_set<std::string> set4;
- // set4 = set3;
- //
- // * Move constructor
- //
- // // Move is guaranteed efficient
- // absl::node_hash_set<std::string> set5(std::move(set4));
- //
- // * Move assignment operator
- //
- // // May be efficient if allocators are compatible
- // absl::node_hash_set<std::string> set6;
- // set6 = std::move(set5);
- //
- // * Range constructor
- //
- // std::vector<std::string> v = {"a", "b"};
- // absl::node_hash_set<std::string> set7(v.begin(), v.end());
- node_hash_set() {}
- using Base::Base;
-
- // node_hash_set::begin()
- //
- // Returns an iterator to the beginning of the `node_hash_set`.
- using Base::begin;
-
- // node_hash_set::cbegin()
- //
- // Returns a const iterator to the beginning of the `node_hash_set`.
- using Base::cbegin;
-
- // node_hash_set::cend()
- //
- // Returns a const iterator to the end of the `node_hash_set`.
- using Base::cend;
-
- // node_hash_set::end()
- //
- // Returns an iterator to the end of the `node_hash_set`.
- using Base::end;
-
- // node_hash_set::capacity()
- //
- // Returns the number of element slots (assigned, deleted, and empty)
- // available within the `node_hash_set`.
- //
- // NOTE: this member function is particular to `absl::node_hash_set` and is
- // not provided in the `std::unordered_set` API.
- using Base::capacity;
-
- // node_hash_set::empty()
- //
- // Returns whether or not the `node_hash_set` is empty.
- using Base::empty;
-
- // node_hash_set::max_size()
- //
- // Returns the largest theoretical possible number of elements within a
- // `node_hash_set` under current memory constraints. This value can be thought
- // of the largest value of `std::distance(begin(), end())` for a
- // `node_hash_set<T>`.
- using Base::max_size;
-
- // node_hash_set::size()
- //
- // Returns the number of elements currently within the `node_hash_set`.
- using Base::size;
-
- // node_hash_set::clear()
- //
- // Removes all elements from the `node_hash_set`. Invalidates any references,
- // pointers, or iterators referring to contained elements.
- //
- // NOTE: this operation may shrink the underlying buffer. To avoid shrinking
- // the underlying buffer call `erase(begin(), end())`.
- using Base::clear;
-
- // node_hash_set::erase()
- //
- // Erases elements within the `node_hash_set`. Erasing does not trigger a
- // rehash. Overloads are listed below.
- //
- // void erase(const_iterator pos):
- //
- // Erases the element at `position` of the `node_hash_set`, returning
- // `void`.
- //
- // NOTE: this return behavior is different than that of STL containers in
- // general and `std::unordered_set` in particular.
- //
- // iterator erase(const_iterator first, const_iterator last):
- //
- // Erases the elements in the open interval [`first`, `last`), returning an
- // iterator pointing to `last`.
- //
- // size_type erase(const key_type& key):
- //
- // Erases the element with the matching key, if it exists, returning the
- // number of elements erased (0 or 1).
- using Base::erase;
-
- // node_hash_set::insert()
- //
- // Inserts an element of the specified value into the `node_hash_set`,
- // returning an iterator pointing to the newly inserted element, provided that
- // an element with the given key does not already exist. If rehashing occurs
- // due to the insertion, all iterators are invalidated. Overloads are listed
- // below.
- //
- // std::pair<iterator,bool> insert(const T& value):
- //
- // Inserts a value into the `node_hash_set`. Returns a pair consisting of an
- // iterator to the inserted element (or to the element that prevented the
- // insertion) and a bool denoting whether the insertion took place.
- //
- // std::pair<iterator,bool> insert(T&& value):
- //
- // Inserts a moveable value into the `node_hash_set`. Returns a pair
- // consisting of an iterator to the inserted element (or to the element that
- // prevented the insertion) and a bool denoting whether the insertion took
- // place.
- //
- // iterator insert(const_iterator hint, const T& value):
- // iterator insert(const_iterator hint, T&& value):
- //
- // Inserts a value, using the position of `hint` as a non-binding suggestion
- // for where to begin the insertion search. Returns an iterator to the
- // inserted element, or to the existing element that prevented the
- // insertion.
- //
- // void insert(InputIterator first, InputIterator last):
- //
- // Inserts a range of values [`first`, `last`).
- //
- // NOTE: Although the STL does not specify which element may be inserted if
- // multiple keys compare equivalently, for `node_hash_set` we guarantee the
- // first match is inserted.
- //
- // void insert(std::initializer_list<T> ilist):
- //
- // Inserts the elements within the initializer list `ilist`.
- //
- // NOTE: Although the STL does not specify which element may be inserted if
- // multiple keys compare equivalently within the initializer list, for
- // `node_hash_set` we guarantee the first match is inserted.
- using Base::insert;
-
- // node_hash_set::emplace()
- //
- // Inserts an element of the specified value by constructing it in-place
- // within the `node_hash_set`, provided that no element with the given key
- // already exists.
- //
- // The element may be constructed even if there already is an element with the
- // key in the container, in which case the newly constructed element will be
- // destroyed immediately.
- //
- // If rehashing occurs due to the insertion, all iterators are invalidated.
- using Base::emplace;
-
- // node_hash_set::emplace_hint()
- //
- // Inserts an element of the specified value by constructing it in-place
- // within the `node_hash_set`, using the position of `hint` as a non-binding
- // suggestion for where to begin the insertion search, and only inserts
- // provided that no element with the given key already exists.
- //
- // The element may be constructed even if there already is an element with the
- // key in the container, in which case the newly constructed element will be
- // destroyed immediately.
- //
- // If rehashing occurs due to the insertion, all iterators are invalidated.
- using Base::emplace_hint;
-
- // node_hash_set::extract()
- //
- // Extracts the indicated element, erasing it in the process, and returns it
- // as a C++17-compatible node handle. Overloads are listed below.
- //
- // node_type extract(const_iterator position):
- //
- // Extracts the element at the indicated position and returns a node handle
- // owning that extracted data.
- //
- // node_type extract(const key_type& x):
- //
- // Extracts the element with the key matching the passed key value and
- // returns a node handle owning that extracted data. If the `node_hash_set`
- // does not contain an element with a matching key, this function returns an
- // empty node handle.
- using Base::extract;
-
- // node_hash_set::merge()
- //
- // Extracts elements from a given `source` node hash set into this
- // `node_hash_set`. If the destination `node_hash_set` already contains an
- // element with an equivalent key, that element is not extracted.
- using Base::merge;
-
- // node_hash_set::swap(node_hash_set& other)
- //
- // Exchanges the contents of this `node_hash_set` with those of the `other`
- // node hash set, avoiding invocation of any move, copy, or swap operations on
- // individual elements.
- //
- // All iterators and references on the `node_hash_set` remain valid, excepting
- // for the past-the-end iterator, which is invalidated.
- //
- // `swap()` requires that the node hash set's hashing and key equivalence
- // functions be Swappable, and are exchaged using unqualified calls to
- // non-member `swap()`. If the set's allocator has
- // `std::allocator_traits<allocator_type>::propagate_on_container_swap::value`
- // set to `true`, the allocators are also exchanged using an unqualified call
- // to non-member `swap()`; otherwise, the allocators are not swapped.
- using Base::swap;
-
- // node_hash_set::rehash(count)
- //
- // Rehashes the `node_hash_set`, setting the number of slots to be at least
- // the passed value. If the new number of slots increases the load factor more
- // than the current maximum load factor
- // (`count` < `size()` / `max_load_factor()`), then the new number of slots
- // will be at least `size()` / `max_load_factor()`.
- //
- // To force a rehash, pass rehash(0).
- //
- // NOTE: unlike behavior in `std::unordered_set`, references are also
- // invalidated upon a `rehash()`.
- using Base::rehash;
-
- // node_hash_set::reserve(count)
- //
- // Sets the number of slots in the `node_hash_set` to the number needed to
- // accommodate at least `count` total elements without exceeding the current
- // maximum load factor, and may rehash the container if needed.
- using Base::reserve;
-
- // node_hash_set::contains()
- //
- // Determines whether an element comparing equal to the given `key` exists
- // within the `node_hash_set`, returning `true` if so or `false` otherwise.
- using Base::contains;
-
- // node_hash_set::count(const Key& key) const
- //
- // Returns the number of elements comparing equal to the given `key` within
- // the `node_hash_set`. note that this function will return either `1` or `0`
- // since duplicate elements are not allowed within a `node_hash_set`.
- using Base::count;
-
- // node_hash_set::equal_range()
- //
- // Returns a closed range [first, last], defined by a `std::pair` of two
- // iterators, containing all elements with the passed key in the
- // `node_hash_set`.
- using Base::equal_range;
-
- // node_hash_set::find()
- //
- // Finds an element with the passed `key` within the `node_hash_set`.
- using Base::find;
-
- // node_hash_set::bucket_count()
- //
- // Returns the number of "buckets" within the `node_hash_set`. Note that
- // because a node hash set contains all elements within its internal storage,
- // this value simply equals the current capacity of the `node_hash_set`.
- using Base::bucket_count;
-
- // node_hash_set::load_factor()
- //
- // Returns the current load factor of the `node_hash_set` (the average number
- // of slots occupied with a value within the hash set).
- using Base::load_factor;
-
- // node_hash_set::max_load_factor()
- //
- // Manages the maximum load factor of the `node_hash_set`. Overloads are
- // listed below.
- //
- // float node_hash_set::max_load_factor()
- //
- // Returns the current maximum load factor of the `node_hash_set`.
- //
- // void node_hash_set::max_load_factor(float ml)
- //
- // Sets the maximum load factor of the `node_hash_set` to the passed value.
- //
- // NOTE: This overload is provided only for API compatibility with the STL;
- // `node_hash_set` will ignore any set load factor and manage its rehashing
- // internally as an implementation detail.
- using Base::max_load_factor;
-
- // node_hash_set::get_allocator()
- //
- // Returns the allocator function associated with this `node_hash_set`.
- using Base::get_allocator;
-
- // node_hash_set::hash_function()
- //
- // Returns the hashing function used to hash the keys within this
- // `node_hash_set`.
- using Base::hash_function;
-
- // node_hash_set::key_eq()
- //
- // Returns the function used for comparing keys equality.
- using Base::key_eq;
-};
-
-// erase_if(node_hash_set<>, Pred)
-//
-// Erases all elements that satisfy the predicate `pred` from the container `c`.
-// Returns the number of erased elements.
-template <typename T, typename H, typename E, typename A, typename Predicate>
-typename node_hash_set<T, H, E, A>::size_type erase_if(
- node_hash_set<T, H, E, A>& c, Predicate pred) {
- return container_internal::EraseIf(pred, &c);
-}
-
-namespace container_internal {
-
-template <class T>
-struct NodeHashSetPolicy
- : absl::container_internal::node_slot_policy<T&, NodeHashSetPolicy<T>> {
- using key_type = T;
- using init_type = T;
- using constant_iterators = std::true_type;
-
- template <class Allocator, class... Args>
- static T* new_element(Allocator* alloc, Args&&... args) {
- using ValueAlloc =
- typename absl::allocator_traits<Allocator>::template rebind_alloc<T>;
- ValueAlloc value_alloc(*alloc);
- T* res = absl::allocator_traits<ValueAlloc>::allocate(value_alloc, 1);
- absl::allocator_traits<ValueAlloc>::construct(value_alloc, res,
- std::forward<Args>(args)...);
- return res;
- }
-
- template <class Allocator>
- static void delete_element(Allocator* alloc, T* elem) {
- using ValueAlloc =
- typename absl::allocator_traits<Allocator>::template rebind_alloc<T>;
- ValueAlloc value_alloc(*alloc);
- absl::allocator_traits<ValueAlloc>::destroy(value_alloc, elem);
- absl::allocator_traits<ValueAlloc>::deallocate(value_alloc, elem, 1);
- }
-
- template <class F, class... Args>
- static decltype(absl::container_internal::DecomposeValue(
- std::declval<F>(), std::declval<Args>()...))
- apply(F&& f, Args&&... args) {
- return absl::container_internal::DecomposeValue(
- std::forward<F>(f), std::forward<Args>(args)...);
- }
-
- static size_t element_space_used(const T*) { return sizeof(T); }
-};
-} // namespace container_internal
-
-namespace container_algorithm_internal {
-
-// Specialization of trait in absl/algorithm/container.h
-template <class Key, class Hash, class KeyEqual, class Allocator>
-struct IsUnorderedContainer<absl::node_hash_set<Key, Hash, KeyEqual, Allocator>>
- : std::true_type {};
-
-} // namespace container_algorithm_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_CONTAINER_NODE_HASH_SET_H_
diff --git a/third_party/abseil-cpp/absl/container/node_hash_set_test.cc b/third_party/abseil-cpp/absl/container/node_hash_set_test.cc
deleted file mode 100644
index 98a8dbd..0000000
--- a/third_party/abseil-cpp/absl/container/node_hash_set_test.cc
+++ /dev/null
@@ -1,143 +0,0 @@
-// Copyright 2018 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/container/node_hash_set.h"
-
-#include "absl/container/internal/unordered_set_constructor_test.h"
-#include "absl/container/internal/unordered_set_lookup_test.h"
-#include "absl/container/internal/unordered_set_members_test.h"
-#include "absl/container/internal/unordered_set_modifiers_test.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-namespace {
-using ::absl::container_internal::hash_internal::Enum;
-using ::absl::container_internal::hash_internal::EnumClass;
-using ::testing::IsEmpty;
-using ::testing::Pointee;
-using ::testing::UnorderedElementsAre;
-
-using SetTypes = ::testing::Types<
- node_hash_set<int, StatefulTestingHash, StatefulTestingEqual, Alloc<int>>,
- node_hash_set<std::string, StatefulTestingHash, StatefulTestingEqual,
- Alloc<std::string>>,
- node_hash_set<Enum, StatefulTestingHash, StatefulTestingEqual, Alloc<Enum>>,
- node_hash_set<EnumClass, StatefulTestingHash, StatefulTestingEqual,
- Alloc<EnumClass>>>;
-
-INSTANTIATE_TYPED_TEST_SUITE_P(NodeHashSet, ConstructorTest, SetTypes);
-INSTANTIATE_TYPED_TEST_SUITE_P(NodeHashSet, LookupTest, SetTypes);
-INSTANTIATE_TYPED_TEST_SUITE_P(NodeHashSet, MembersTest, SetTypes);
-INSTANTIATE_TYPED_TEST_SUITE_P(NodeHashSet, ModifiersTest, SetTypes);
-
-TEST(NodeHashSet, MoveableNotCopyableCompiles) {
- node_hash_set<std::unique_ptr<void*>> t;
- node_hash_set<std::unique_ptr<void*>> u;
- u = std::move(t);
-}
-
-TEST(NodeHashSet, MergeExtractInsert) {
- struct Hash {
- size_t operator()(const std::unique_ptr<int>& p) const { return *p; }
- };
- struct Eq {
- bool operator()(const std::unique_ptr<int>& a,
- const std::unique_ptr<int>& b) const {
- return *a == *b;
- }
- };
- absl::node_hash_set<std::unique_ptr<int>, Hash, Eq> set1, set2;
- set1.insert(absl::make_unique<int>(7));
- set1.insert(absl::make_unique<int>(17));
-
- set2.insert(absl::make_unique<int>(7));
- set2.insert(absl::make_unique<int>(19));
-
- EXPECT_THAT(set1, UnorderedElementsAre(Pointee(7), Pointee(17)));
- EXPECT_THAT(set2, UnorderedElementsAre(Pointee(7), Pointee(19)));
-
- set1.merge(set2);
-
- EXPECT_THAT(set1, UnorderedElementsAre(Pointee(7), Pointee(17), Pointee(19)));
- EXPECT_THAT(set2, UnorderedElementsAre(Pointee(7)));
-
- auto node = set1.extract(absl::make_unique<int>(7));
- EXPECT_TRUE(node);
- EXPECT_THAT(node.value(), Pointee(7));
- EXPECT_THAT(set1, UnorderedElementsAre(Pointee(17), Pointee(19)));
-
- auto insert_result = set2.insert(std::move(node));
- EXPECT_FALSE(node);
- EXPECT_FALSE(insert_result.inserted);
- EXPECT_TRUE(insert_result.node);
- EXPECT_THAT(insert_result.node.value(), Pointee(7));
- EXPECT_EQ(**insert_result.position, 7);
- EXPECT_NE(insert_result.position->get(), insert_result.node.value().get());
- EXPECT_THAT(set2, UnorderedElementsAre(Pointee(7)));
-
- node = set1.extract(absl::make_unique<int>(17));
- EXPECT_TRUE(node);
- EXPECT_THAT(node.value(), Pointee(17));
- EXPECT_THAT(set1, UnorderedElementsAre(Pointee(19)));
-
- node.value() = absl::make_unique<int>(23);
-
- insert_result = set2.insert(std::move(node));
- EXPECT_FALSE(node);
- EXPECT_TRUE(insert_result.inserted);
- EXPECT_FALSE(insert_result.node);
- EXPECT_EQ(**insert_result.position, 23);
- EXPECT_THAT(set2, UnorderedElementsAre(Pointee(7), Pointee(23)));
-}
-
-bool IsEven(int k) { return k % 2 == 0; }
-
-TEST(NodeHashSet, EraseIf) {
- // Erase all elements.
- {
- node_hash_set<int> s = {1, 2, 3, 4, 5};
- EXPECT_EQ(erase_if(s, [](int) { return true; }), 5);
- EXPECT_THAT(s, IsEmpty());
- }
- // Erase no elements.
- {
- node_hash_set<int> s = {1, 2, 3, 4, 5};
- EXPECT_EQ(erase_if(s, [](int) { return false; }), 0);
- EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
- }
- // Erase specific elements.
- {
- node_hash_set<int> s = {1, 2, 3, 4, 5};
- EXPECT_EQ(erase_if(s, [](int k) { return k % 2 == 1; }), 3);
- EXPECT_THAT(s, UnorderedElementsAre(2, 4));
- }
- // Predicate is function reference.
- {
- node_hash_set<int> s = {1, 2, 3, 4, 5};
- EXPECT_EQ(erase_if(s, IsEven), 2);
- EXPECT_THAT(s, UnorderedElementsAre(1, 3, 5));
- }
- // Predicate is function pointer.
- {
- node_hash_set<int> s = {1, 2, 3, 4, 5};
- EXPECT_EQ(erase_if(s, &IsEven), 2);
- EXPECT_THAT(s, UnorderedElementsAre(1, 3, 5));
- }
-}
-
-} // namespace
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/container/sample_element_size_test.cc b/third_party/abseil-cpp/absl/container/sample_element_size_test.cc
deleted file mode 100644
index b23626b..0000000
--- a/third_party/abseil-cpp/absl/container/sample_element_size_test.cc
+++ /dev/null
@@ -1,114 +0,0 @@
-// Copyright 2018 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 "gmock/gmock.h"
-#include "gtest/gtest.h"
-#include "absl/container/flat_hash_map.h"
-#include "absl/container/flat_hash_set.h"
-#include "absl/container/node_hash_map.h"
-#include "absl/container/node_hash_set.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace container_internal {
-namespace {
-
-#if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
-// Create some tables of type `Table`, then look at all the new
-// `HashtablezInfo`s to make sure that the `inline_element_size ==
-// expected_element_size`. The `inline_element_size` is the amount of memory
-// allocated for each slot of a hash table, that is `sizeof(slot_type)`. Add
-// the new `HashtablezInfo`s to `preexisting_info`. Store all the new tables
-// into `tables`.
-template <class Table>
-void TestInlineElementSize(
- HashtablezSampler& sampler,
- // clang-tidy gives a false positive on this declaration. This unordered
- // set cannot be flat_hash_set, however, since that would introduce a mutex
- // deadlock.
- std::unordered_set<const HashtablezInfo*>& preexisting_info, // NOLINT
- std::vector<Table>& tables, const typename Table::value_type& elt,
- size_t expected_element_size) {
- for (int i = 0; i < 10; ++i) {
- // We create a new table and must store it somewhere so that when we store
- // a pointer to the resulting `HashtablezInfo` into `preexisting_info`
- // that we aren't storing a dangling pointer.
- tables.emplace_back();
- // We must insert an element to get a hashtablez to instantiate.
- tables.back().insert(elt);
- }
- size_t new_count = 0;
- sampler.Iterate([&](const HashtablezInfo& info) {
- if (preexisting_info.insert(&info).second) {
- EXPECT_EQ(info.inline_element_size, expected_element_size);
- ++new_count;
- }
- });
- // Make sure we actually did get a new hashtablez.
- EXPECT_GT(new_count, 0);
-}
-
-struct bigstruct {
- char a[1000];
- friend bool operator==(const bigstruct& x, const bigstruct& y) {
- return memcmp(x.a, y.a, sizeof(x.a)) == 0;
- }
- template <typename H>
- friend H AbslHashValue(H h, const bigstruct& c) {
- return H::combine_contiguous(std::move(h), c.a, sizeof(c.a));
- }
-};
-#endif
-
-TEST(FlatHashMap, SampleElementSize) {
-#if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
- // Enable sampling even if the prod default is off.
- SetHashtablezEnabled(true);
- SetHashtablezSampleParameter(1);
-
- auto& sampler = GlobalHashtablezSampler();
- std::vector<flat_hash_map<int, bigstruct>> flat_map_tables;
- std::vector<flat_hash_set<bigstruct>> flat_set_tables;
- std::vector<node_hash_map<int, bigstruct>> node_map_tables;
- std::vector<node_hash_set<bigstruct>> node_set_tables;
-
- // It takes thousands of new tables after changing the sampling parameters
- // before you actually get some instrumentation. And if you must actually
- // put something into those tables.
- for (int i = 0; i < 10000; ++i) {
- flat_map_tables.emplace_back();
- flat_map_tables.back()[i] = bigstruct{};
- }
-
- // clang-tidy gives a false positive on this declaration. This unordered set
- // cannot be a flat_hash_set, however, since that would introduce a mutex
- // deadlock.
- std::unordered_set<const HashtablezInfo*> preexisting_info; // NOLINT
- sampler.Iterate(
- [&](const HashtablezInfo& info) { preexisting_info.insert(&info); });
- TestInlineElementSize(sampler, preexisting_info, flat_map_tables,
- {0, bigstruct{}}, sizeof(int) + sizeof(bigstruct));
- TestInlineElementSize(sampler, preexisting_info, node_map_tables,
- {0, bigstruct{}}, sizeof(void*));
- TestInlineElementSize(sampler, preexisting_info, flat_set_tables, //
- bigstruct{}, sizeof(bigstruct));
- TestInlineElementSize(sampler, preexisting_info, node_set_tables, //
- bigstruct{}, sizeof(void*));
-#endif
-}
-
-} // namespace
-} // namespace container_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/copts/AbseilConfigureCopts.cmake b/third_party/abseil-cpp/absl/copts/AbseilConfigureCopts.cmake
deleted file mode 100644
index f728c0e..0000000
--- a/third_party/abseil-cpp/absl/copts/AbseilConfigureCopts.cmake
+++ /dev/null
@@ -1,96 +0,0 @@
-# See absl/copts/copts.py and absl/copts/generate_copts.py
-include(GENERATED_AbseilCopts)
-
-set(ABSL_DEFAULT_LINKOPTS "")
-
-if (BUILD_SHARED_LIBS AND MSVC)
- set(ABSL_BUILD_DLL TRUE)
- set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)
-else()
- set(ABSL_BUILD_DLL FALSE)
-endif()
-
-if(APPLE AND CMAKE_CXX_COMPILER_ID MATCHES [[Clang]])
- # Some CMake targets (not known at the moment of processing) could be set to
- # compile for multiple architectures as specified by the OSX_ARCHITECTURES
- # property, which is target-specific. We should neither inspect nor rely on
- # any CMake property or variable to detect an architecture, in particular:
- #
- # - CMAKE_OSX_ARCHITECTURES
- # is just an initial value for OSX_ARCHITECTURES; set too early.
- #
- # - OSX_ARCHITECTURES
- # is a per-target property; targets could be defined later, and their
- # properties could be modified any time later.
- #
- # - CMAKE_SYSTEM_PROCESSOR
- # does not reflect multiple architectures at all.
- #
- # When compiling for multiple architectures, a build system can invoke a
- # compiler either
- #
- # - once: a single command line for multiple architectures (Ninja build)
- # - twice: two command lines per each architecture (Xcode build system)
- #
- # If case of Xcode, it would be possible to set an Xcode-specific attributes
- # like XCODE_ATTRIBUTE_OTHER_CPLUSPLUSFLAGS[arch=arm64] or similar.
- #
- # In both cases, the viable strategy is to pass all arguments at once, allowing
- # the compiler to dispatch arch-specific arguments to a designated backend.
- set(ABSL_RANDOM_RANDEN_COPTS "")
- foreach(_arch IN ITEMS "x86_64" "arm64")
- string(TOUPPER "${_arch}" _arch_uppercase)
- string(REPLACE "X86_64" "X64" _arch_uppercase ${_arch_uppercase})
- foreach(_flag IN LISTS ABSL_RANDOM_HWAES_${_arch_uppercase}_FLAGS)
- list(APPEND ABSL_RANDOM_RANDEN_COPTS "-Xarch_${_arch}" "${_flag}")
- endforeach()
- endforeach()
- # If a compiler happens to deal with an argument for a currently unused
- # architecture, it will warn about an unused command line argument.
- option(ABSL_RANDOM_RANDEN_COPTS_WARNING OFF
- "Warn if one of ABSL_RANDOM_RANDEN_COPTS is unused")
- if(ABSL_RANDOM_RANDEN_COPTS AND NOT ABSL_RANDOM_RANDEN_COPTS_WARNING)
- list(APPEND ABSL_RANDOM_RANDEN_COPTS "-Wno-unused-command-line-argument")
- endif()
-elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64|amd64|AMD64")
- if (MSVC)
- set(ABSL_RANDOM_RANDEN_COPTS "${ABSL_RANDOM_HWAES_MSVC_X64_FLAGS}")
- else()
- set(ABSL_RANDOM_RANDEN_COPTS "${ABSL_RANDOM_HWAES_X64_FLAGS}")
- endif()
-elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "arm.*|aarch64")
- if (CMAKE_SIZEOF_VOID_P STREQUAL "8")
- set(ABSL_RANDOM_RANDEN_COPTS "${ABSL_RANDOM_HWAES_ARM64_FLAGS}")
- elseif(CMAKE_SIZEOF_VOID_P STREQUAL "4")
- set(ABSL_RANDOM_RANDEN_COPTS "${ABSL_RANDOM_HWAES_ARM32_FLAGS}")
- else()
- message(WARNING "Value of CMAKE_SIZEOF_VOID_P (${CMAKE_SIZEOF_VOID_P}) is not supported.")
- endif()
-else()
- set(ABSL_RANDOM_RANDEN_COPTS "")
-endif()
-
-
-if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
- set(ABSL_DEFAULT_COPTS "${ABSL_GCC_FLAGS}")
- set(ABSL_TEST_COPTS "${ABSL_GCC_FLAGS};${ABSL_GCC_TEST_FLAGS}")
-elseif(CMAKE_CXX_COMPILER_ID MATCHES "Clang") # MATCHES so we get both Clang and AppleClang
- if(MSVC)
- # clang-cl is half MSVC, half LLVM
- set(ABSL_DEFAULT_COPTS "${ABSL_CLANG_CL_FLAGS}")
- set(ABSL_TEST_COPTS "${ABSL_CLANG_CL_FLAGS};${ABSL_CLANG_CL_TEST_FLAGS}")
- else()
- set(ABSL_DEFAULT_COPTS "${ABSL_LLVM_FLAGS}")
- set(ABSL_TEST_COPTS "${ABSL_LLVM_FLAGS};${ABSL_LLVM_TEST_FLAGS}")
- endif()
-elseif(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
- set(ABSL_DEFAULT_COPTS "${ABSL_MSVC_FLAGS}")
- set(ABSL_TEST_COPTS "${ABSL_MSVC_FLAGS};${ABSL_MSVC_TEST_FLAGS}")
- set(ABSL_DEFAULT_LINKOPTS "${ABSL_MSVC_LINKOPTS}")
-else()
- message(WARNING "Unknown compiler: ${CMAKE_CXX_COMPILER}. Building with no default flags")
- set(ABSL_DEFAULT_COPTS "")
- set(ABSL_TEST_COPTS "")
-endif()
-
-set(ABSL_CXX_STANDARD "${CMAKE_CXX_STANDARD}")
diff --git a/third_party/abseil-cpp/absl/copts/GENERATED_AbseilCopts.cmake b/third_party/abseil-cpp/absl/copts/GENERATED_AbseilCopts.cmake
deleted file mode 100644
index 46563d4..0000000
--- a/third_party/abseil-cpp/absl/copts/GENERATED_AbseilCopts.cmake
+++ /dev/null
@@ -1,170 +0,0 @@
-# GENERATED! DO NOT MANUALLY EDIT THIS FILE.
-#
-# (1) Edit absl/copts/copts.py.
-# (2) Run `python <path_to_absl>/copts/generate_copts.py`.
-
-list(APPEND ABSL_CLANG_CL_FLAGS
- "/W3"
- "/DNOMINMAX"
- "/DWIN32_LEAN_AND_MEAN"
- "/D_CRT_SECURE_NO_WARNINGS"
- "/D_SCL_SECURE_NO_WARNINGS"
- "/D_ENABLE_EXTENDED_ALIGNED_STORAGE"
-)
-
-list(APPEND ABSL_CLANG_CL_TEST_FLAGS
- "-Wno-c99-extensions"
- "-Wno-deprecated-declarations"
- "-Wno-implicit-int-conversion"
- "-Wno-missing-noreturn"
- "-Wno-missing-prototypes"
- "-Wno-missing-variable-declarations"
- "-Wno-null-conversion"
- "-Wno-shadow"
- "-Wno-shift-sign-overflow"
- "-Wno-shorten-64-to-32"
- "-Wno-sign-compare"
- "-Wno-sign-conversion"
- "-Wno-unreachable-code-loop-increment"
- "-Wno-unused-function"
- "-Wno-unused-member-function"
- "-Wno-unused-parameter"
- "-Wno-unused-private-field"
- "-Wno-unused-template"
- "-Wno-used-but-marked-unused"
- "-Wno-zero-as-null-pointer-constant"
- "-Wno-gnu-zero-variadic-macro-arguments"
-)
-
-list(APPEND ABSL_GCC_FLAGS
- "-Wall"
- "-Wextra"
- "-Wcast-qual"
- "-Wconversion-null"
- "-Wformat-security"
- "-Wmissing-declarations"
- "-Woverlength-strings"
- "-Wpointer-arith"
- "-Wundef"
- "-Wunused-local-typedefs"
- "-Wunused-result"
- "-Wvarargs"
- "-Wvla"
- "-Wwrite-strings"
- "-DNOMINMAX"
-)
-
-list(APPEND ABSL_GCC_TEST_FLAGS
- "-Wno-conversion-null"
- "-Wno-deprecated-declarations"
- "-Wno-missing-declarations"
- "-Wno-sign-compare"
- "-Wno-unused-function"
- "-Wno-unused-parameter"
- "-Wno-unused-private-field"
-)
-
-list(APPEND ABSL_LLVM_FLAGS
- "-Wall"
- "-Wextra"
- "-Wcast-qual"
- "-Wconversion"
- "-Wfloat-overflow-conversion"
- "-Wfloat-zero-conversion"
- "-Wfor-loop-analysis"
- "-Wformat-security"
- "-Wgnu-redeclared-enum"
- "-Winfinite-recursion"
- "-Winvalid-constexpr"
- "-Wliteral-conversion"
- "-Wmissing-declarations"
- "-Woverlength-strings"
- "-Wpointer-arith"
- "-Wself-assign"
- "-Wshadow-all"
- "-Wstring-conversion"
- "-Wtautological-overlap-compare"
- "-Wtautological-unsigned-zero-compare"
- "-Wundef"
- "-Wuninitialized"
- "-Wunreachable-code"
- "-Wunused-comparison"
- "-Wunused-local-typedefs"
- "-Wunused-result"
- "-Wvla"
- "-Wwrite-strings"
- "-Wno-float-conversion"
- "-Wno-implicit-float-conversion"
- "-Wno-implicit-int-float-conversion"
- "-Wno-unknown-warning-option"
- "-DNOMINMAX"
-)
-
-list(APPEND ABSL_LLVM_TEST_FLAGS
- "-Wno-c99-extensions"
- "-Wno-deprecated-declarations"
- "-Wno-implicit-int-conversion"
- "-Wno-missing-noreturn"
- "-Wno-missing-prototypes"
- "-Wno-missing-variable-declarations"
- "-Wno-null-conversion"
- "-Wno-shadow"
- "-Wno-shift-sign-overflow"
- "-Wno-shorten-64-to-32"
- "-Wno-sign-compare"
- "-Wno-sign-conversion"
- "-Wno-unreachable-code-loop-increment"
- "-Wno-unused-function"
- "-Wno-unused-member-function"
- "-Wno-unused-parameter"
- "-Wno-unused-private-field"
- "-Wno-unused-template"
- "-Wno-used-but-marked-unused"
- "-Wno-zero-as-null-pointer-constant"
- "-Wno-gnu-zero-variadic-macro-arguments"
-)
-
-list(APPEND ABSL_MSVC_FLAGS
- "/W3"
- "/DNOMINMAX"
- "/DWIN32_LEAN_AND_MEAN"
- "/D_CRT_SECURE_NO_WARNINGS"
- "/D_SCL_SECURE_NO_WARNINGS"
- "/D_ENABLE_EXTENDED_ALIGNED_STORAGE"
- "/bigobj"
- "/wd4005"
- "/wd4068"
- "/wd4180"
- "/wd4244"
- "/wd4267"
- "/wd4503"
- "/wd4800"
-)
-
-list(APPEND ABSL_MSVC_LINKOPTS
- "-ignore:4221"
-)
-
-list(APPEND ABSL_MSVC_TEST_FLAGS
- "/wd4018"
- "/wd4101"
- "/wd4503"
- "/wd4996"
- "/DNOMINMAX"
-)
-
-list(APPEND ABSL_RANDOM_HWAES_ARM32_FLAGS
- "-mfpu=neon"
-)
-
-list(APPEND ABSL_RANDOM_HWAES_ARM64_FLAGS
- "-march=armv8-a+crypto"
-)
-
-list(APPEND ABSL_RANDOM_HWAES_MSVC_X64_FLAGS
-)
-
-list(APPEND ABSL_RANDOM_HWAES_X64_FLAGS
- "-maes"
- "-msse4.1"
-)
diff --git a/third_party/abseil-cpp/absl/copts/GENERATED_copts.bzl b/third_party/abseil-cpp/absl/copts/GENERATED_copts.bzl
deleted file mode 100644
index 8518b63..0000000
--- a/third_party/abseil-cpp/absl/copts/GENERATED_copts.bzl
+++ /dev/null
@@ -1,171 +0,0 @@
-"""GENERATED! DO NOT MANUALLY EDIT THIS FILE.
-
-(1) Edit absl/copts/copts.py.
-(2) Run `python <path_to_absl>/copts/generate_copts.py`.
-"""
-
-ABSL_CLANG_CL_FLAGS = [
- "/W3",
- "/DNOMINMAX",
- "/DWIN32_LEAN_AND_MEAN",
- "/D_CRT_SECURE_NO_WARNINGS",
- "/D_SCL_SECURE_NO_WARNINGS",
- "/D_ENABLE_EXTENDED_ALIGNED_STORAGE",
-]
-
-ABSL_CLANG_CL_TEST_FLAGS = [
- "-Wno-c99-extensions",
- "-Wno-deprecated-declarations",
- "-Wno-implicit-int-conversion",
- "-Wno-missing-noreturn",
- "-Wno-missing-prototypes",
- "-Wno-missing-variable-declarations",
- "-Wno-null-conversion",
- "-Wno-shadow",
- "-Wno-shift-sign-overflow",
- "-Wno-shorten-64-to-32",
- "-Wno-sign-compare",
- "-Wno-sign-conversion",
- "-Wno-unreachable-code-loop-increment",
- "-Wno-unused-function",
- "-Wno-unused-member-function",
- "-Wno-unused-parameter",
- "-Wno-unused-private-field",
- "-Wno-unused-template",
- "-Wno-used-but-marked-unused",
- "-Wno-zero-as-null-pointer-constant",
- "-Wno-gnu-zero-variadic-macro-arguments",
-]
-
-ABSL_GCC_FLAGS = [
- "-Wall",
- "-Wextra",
- "-Wcast-qual",
- "-Wconversion-null",
- "-Wformat-security",
- "-Wmissing-declarations",
- "-Woverlength-strings",
- "-Wpointer-arith",
- "-Wundef",
- "-Wunused-local-typedefs",
- "-Wunused-result",
- "-Wvarargs",
- "-Wvla",
- "-Wwrite-strings",
- "-DNOMINMAX",
-]
-
-ABSL_GCC_TEST_FLAGS = [
- "-Wno-conversion-null",
- "-Wno-deprecated-declarations",
- "-Wno-missing-declarations",
- "-Wno-sign-compare",
- "-Wno-unused-function",
- "-Wno-unused-parameter",
- "-Wno-unused-private-field",
-]
-
-ABSL_LLVM_FLAGS = [
- "-Wall",
- "-Wextra",
- "-Wcast-qual",
- "-Wconversion",
- "-Wfloat-overflow-conversion",
- "-Wfloat-zero-conversion",
- "-Wfor-loop-analysis",
- "-Wformat-security",
- "-Wgnu-redeclared-enum",
- "-Winfinite-recursion",
- "-Winvalid-constexpr",
- "-Wliteral-conversion",
- "-Wmissing-declarations",
- "-Woverlength-strings",
- "-Wpointer-arith",
- "-Wself-assign",
- "-Wshadow-all",
- "-Wstring-conversion",
- "-Wtautological-overlap-compare",
- "-Wtautological-unsigned-zero-compare",
- "-Wundef",
- "-Wuninitialized",
- "-Wunreachable-code",
- "-Wunused-comparison",
- "-Wunused-local-typedefs",
- "-Wunused-result",
- "-Wvla",
- "-Wwrite-strings",
- "-Wno-float-conversion",
- "-Wno-implicit-float-conversion",
- "-Wno-implicit-int-float-conversion",
- "-Wno-unknown-warning-option",
- "-DNOMINMAX",
-]
-
-ABSL_LLVM_TEST_FLAGS = [
- "-Wno-c99-extensions",
- "-Wno-deprecated-declarations",
- "-Wno-implicit-int-conversion",
- "-Wno-missing-noreturn",
- "-Wno-missing-prototypes",
- "-Wno-missing-variable-declarations",
- "-Wno-null-conversion",
- "-Wno-shadow",
- "-Wno-shift-sign-overflow",
- "-Wno-shorten-64-to-32",
- "-Wno-sign-compare",
- "-Wno-sign-conversion",
- "-Wno-unreachable-code-loop-increment",
- "-Wno-unused-function",
- "-Wno-unused-member-function",
- "-Wno-unused-parameter",
- "-Wno-unused-private-field",
- "-Wno-unused-template",
- "-Wno-used-but-marked-unused",
- "-Wno-zero-as-null-pointer-constant",
- "-Wno-gnu-zero-variadic-macro-arguments",
-]
-
-ABSL_MSVC_FLAGS = [
- "/W3",
- "/DNOMINMAX",
- "/DWIN32_LEAN_AND_MEAN",
- "/D_CRT_SECURE_NO_WARNINGS",
- "/D_SCL_SECURE_NO_WARNINGS",
- "/D_ENABLE_EXTENDED_ALIGNED_STORAGE",
- "/bigobj",
- "/wd4005",
- "/wd4068",
- "/wd4180",
- "/wd4244",
- "/wd4267",
- "/wd4503",
- "/wd4800",
-]
-
-ABSL_MSVC_LINKOPTS = [
- "-ignore:4221",
-]
-
-ABSL_MSVC_TEST_FLAGS = [
- "/wd4018",
- "/wd4101",
- "/wd4503",
- "/wd4996",
- "/DNOMINMAX",
-]
-
-ABSL_RANDOM_HWAES_ARM32_FLAGS = [
- "-mfpu=neon",
-]
-
-ABSL_RANDOM_HWAES_ARM64_FLAGS = [
- "-march=armv8-a+crypto",
-]
-
-ABSL_RANDOM_HWAES_MSVC_X64_FLAGS = [
-]
-
-ABSL_RANDOM_HWAES_X64_FLAGS = [
- "-maes",
- "-msse4.1",
-]
diff --git a/third_party/abseil-cpp/absl/copts/configure_copts.bzl b/third_party/abseil-cpp/absl/copts/configure_copts.bzl
deleted file mode 100644
index c5e57b3..0000000
--- a/third_party/abseil-cpp/absl/copts/configure_copts.bzl
+++ /dev/null
@@ -1,82 +0,0 @@
-"""absl specific copts.
-
-This file simply selects the correct options from the generated files. To
-change Abseil copts, edit absl/copts/copts.py
-"""
-
-load(
- "//absl:copts/GENERATED_copts.bzl",
- "ABSL_CLANG_CL_FLAGS",
- "ABSL_CLANG_CL_TEST_FLAGS",
- "ABSL_GCC_FLAGS",
- "ABSL_GCC_TEST_FLAGS",
- "ABSL_LLVM_FLAGS",
- "ABSL_LLVM_TEST_FLAGS",
- "ABSL_MSVC_FLAGS",
- "ABSL_MSVC_LINKOPTS",
- "ABSL_MSVC_TEST_FLAGS",
- "ABSL_RANDOM_HWAES_ARM32_FLAGS",
- "ABSL_RANDOM_HWAES_ARM64_FLAGS",
- "ABSL_RANDOM_HWAES_MSVC_X64_FLAGS",
- "ABSL_RANDOM_HWAES_X64_FLAGS",
-)
-
-ABSL_DEFAULT_COPTS = select({
- "//absl:msvc_compiler": ABSL_MSVC_FLAGS,
- "//absl:clang-cl_compiler": ABSL_CLANG_CL_FLAGS,
- "//absl:clang_compiler": ABSL_LLVM_FLAGS,
- "//absl:gcc_compiler": ABSL_GCC_FLAGS,
- "//conditions:default": ABSL_GCC_FLAGS,
-})
-
-ABSL_TEST_COPTS = ABSL_DEFAULT_COPTS + select({
- "//absl:msvc_compiler": ABSL_MSVC_TEST_FLAGS,
- "//absl:clang-cl_compiler": ABSL_CLANG_CL_TEST_FLAGS,
- "//absl:clang_compiler": ABSL_LLVM_TEST_FLAGS,
- "//absl:gcc_compiler": ABSL_GCC_TEST_FLAGS,
- "//conditions:default": ABSL_GCC_TEST_FLAGS,
-})
-
-ABSL_DEFAULT_LINKOPTS = select({
- "//absl:msvc_compiler": ABSL_MSVC_LINKOPTS,
- "//conditions:default": [],
-})
-
-# ABSL_RANDOM_RANDEN_COPTS blaze copts flags which are required by each
-# environment to build an accelerated RandenHwAes library.
-ABSL_RANDOM_RANDEN_COPTS = select({
- # APPLE
- ":cpu_darwin_x86_64": ABSL_RANDOM_HWAES_X64_FLAGS,
- ":cpu_darwin": ABSL_RANDOM_HWAES_X64_FLAGS,
- ":cpu_x64_windows_msvc": ABSL_RANDOM_HWAES_MSVC_X64_FLAGS,
- ":cpu_x64_windows": ABSL_RANDOM_HWAES_MSVC_X64_FLAGS,
- ":cpu_k8": ABSL_RANDOM_HWAES_X64_FLAGS,
- ":cpu_ppc": ["-mcrypto"],
- ":cpu_aarch64": ABSL_RANDOM_HWAES_ARM64_FLAGS,
-
- # Supported by default or unsupported.
- "//conditions:default": [],
-})
-
-# absl_random_randen_copts_init:
-# Initialize the config targets based on cpu, os, etc. used to select
-# the required values for ABSL_RANDOM_RANDEN_COPTS
-def absl_random_randen_copts_init():
- """Initialize the config_settings used by ABSL_RANDOM_RANDEN_COPTS."""
-
- # CPU configs.
- # These configs have consistent flags to enable HWAES intsructions.
- cpu_configs = [
- "ppc",
- "k8",
- "darwin_x86_64",
- "darwin",
- "x64_windows_msvc",
- "x64_windows",
- "aarch64",
- ]
- for cpu in cpu_configs:
- native.config_setting(
- name = "cpu_%s" % cpu,
- values = {"cpu": cpu},
- )
diff --git a/third_party/abseil-cpp/absl/copts/copts.py b/third_party/abseil-cpp/absl/copts/copts.py
deleted file mode 100644
index 17c467c..0000000
--- a/third_party/abseil-cpp/absl/copts/copts.py
+++ /dev/null
@@ -1,168 +0,0 @@
-"""Abseil compiler options.
-
-This is the source of truth for Abseil compiler options. To modify Abseil
-compilation options:
-
- (1) Edit the appropriate list in this file based on the platform the flag is
- needed on.
- (2) Run `<path_to_absl>/copts/generate_copts.py`.
-
-The generated copts are consumed by configure_copts.bzl and
-AbseilConfigureCopts.cmake.
-"""
-
-# /Wall with msvc includes unhelpful warnings such as C4711, C4710, ...
-MSVC_BIG_WARNING_FLAGS = [
- "/W3",
-]
-
-LLVM_TEST_DISABLE_WARNINGS_FLAGS = [
- "-Wno-c99-extensions",
- "-Wno-deprecated-declarations",
- "-Wno-implicit-int-conversion",
- "-Wno-missing-noreturn",
- "-Wno-missing-prototypes",
- "-Wno-missing-variable-declarations",
- "-Wno-null-conversion",
- "-Wno-shadow",
- "-Wno-shift-sign-overflow",
- "-Wno-shorten-64-to-32",
- "-Wno-sign-compare",
- "-Wno-sign-conversion",
- "-Wno-unreachable-code-loop-increment",
- "-Wno-unused-function",
- "-Wno-unused-member-function",
- "-Wno-unused-parameter",
- "-Wno-unused-private-field",
- "-Wno-unused-template",
- "-Wno-used-but-marked-unused",
- "-Wno-zero-as-null-pointer-constant",
- # gtest depends on this GNU extension being offered.
- "-Wno-gnu-zero-variadic-macro-arguments",
-]
-
-MSVC_DEFINES = [
- "/DNOMINMAX", # Don't define min and max macros (windows.h)
- # Don't bloat namespace with incompatible winsock versions.
- "/DWIN32_LEAN_AND_MEAN",
- # Don't warn about usage of insecure C functions.
- "/D_CRT_SECURE_NO_WARNINGS",
- "/D_SCL_SECURE_NO_WARNINGS",
- # Introduced in VS 2017 15.8, allow overaligned types in aligned_storage
- "/D_ENABLE_EXTENDED_ALIGNED_STORAGE",
-]
-
-COPT_VARS = {
- "ABSL_GCC_FLAGS": [
- "-Wall",
- "-Wextra",
- "-Wcast-qual",
- "-Wconversion-null",
- "-Wformat-security",
- "-Wmissing-declarations",
- "-Woverlength-strings",
- "-Wpointer-arith",
- "-Wundef",
- "-Wunused-local-typedefs",
- "-Wunused-result",
- "-Wvarargs",
- "-Wvla", # variable-length array
- "-Wwrite-strings",
- # Don't define min and max macros (Build on Windows using gcc)
- "-DNOMINMAX",
- ],
- "ABSL_GCC_TEST_FLAGS": [
- "-Wno-conversion-null",
- "-Wno-deprecated-declarations",
- "-Wno-missing-declarations",
- "-Wno-sign-compare",
- "-Wno-unused-function",
- "-Wno-unused-parameter",
- "-Wno-unused-private-field",
- ],
- "ABSL_LLVM_FLAGS": [
- "-Wall",
- "-Wextra",
- "-Wcast-qual",
- "-Wconversion",
- "-Wfloat-overflow-conversion",
- "-Wfloat-zero-conversion",
- "-Wfor-loop-analysis",
- "-Wformat-security",
- "-Wgnu-redeclared-enum",
- "-Winfinite-recursion",
- "-Winvalid-constexpr",
- "-Wliteral-conversion",
- "-Wmissing-declarations",
- "-Woverlength-strings",
- "-Wpointer-arith",
- "-Wself-assign",
- "-Wshadow-all",
- "-Wstring-conversion",
- "-Wtautological-overlap-compare",
- "-Wtautological-unsigned-zero-compare",
- "-Wundef",
- "-Wuninitialized",
- "-Wunreachable-code",
- "-Wunused-comparison",
- "-Wunused-local-typedefs",
- "-Wunused-result",
- "-Wvla",
- "-Wwrite-strings",
- # Warnings that are enabled by group warning flags like -Wall that we
- # explicitly disable.
- "-Wno-float-conversion",
- "-Wno-implicit-float-conversion",
- "-Wno-implicit-int-float-conversion",
- # Disable warnings on unknown warning flags (when warning flags are
- # unknown on older compiler versions)
- "-Wno-unknown-warning-option",
- # Don't define min and max macros (Build on Windows using clang)
- "-DNOMINMAX",
- ],
- "ABSL_LLVM_TEST_FLAGS":
- LLVM_TEST_DISABLE_WARNINGS_FLAGS,
- "ABSL_CLANG_CL_FLAGS":
- (MSVC_BIG_WARNING_FLAGS + MSVC_DEFINES),
- "ABSL_CLANG_CL_TEST_FLAGS":
- LLVM_TEST_DISABLE_WARNINGS_FLAGS,
- "ABSL_MSVC_FLAGS":
- MSVC_BIG_WARNING_FLAGS + MSVC_DEFINES + [
- # Increase the number of sections available in object files
- "/bigobj",
- "/wd4005", # macro-redefinition
- "/wd4068", # unknown pragma
- # qualifier applied to function type has no meaning; ignored
- "/wd4180",
- # conversion from 'type1' to 'type2', possible loss of data
- "/wd4244",
- # conversion from 'size_t' to 'type', possible loss of data
- "/wd4267",
- # The decorated name was longer than the compiler limit
- "/wd4503",
- # forcing value to bool 'true' or 'false' (performance warning)
- "/wd4800",
- ],
- "ABSL_MSVC_TEST_FLAGS": [
- "/wd4018", # signed/unsigned mismatch
- "/wd4101", # unreferenced local variable
- "/wd4503", # decorated name length exceeded, name was truncated
- "/wd4996", # use of deprecated symbol
- "/DNOMINMAX", # disable the min() and max() macros from <windows.h>
- ],
- "ABSL_MSVC_LINKOPTS": [
- # Object file doesn't export any previously undefined symbols
- "-ignore:4221",
- ],
- # "HWAES" is an abbreviation for "hardware AES" (AES - Advanced Encryption
- # Standard). These flags are used for detecting whether or not the target
- # architecture has hardware support for AES instructions which can be used
- # to improve performance of some random bit generators.
- "ABSL_RANDOM_HWAES_ARM64_FLAGS": ["-march=armv8-a+crypto"],
- "ABSL_RANDOM_HWAES_ARM32_FLAGS": ["-mfpu=neon"],
- "ABSL_RANDOM_HWAES_X64_FLAGS": [
- "-maes",
- "-msse4.1",
- ],
- "ABSL_RANDOM_HWAES_MSVC_X64_FLAGS": [],
-}
diff --git a/third_party/abseil-cpp/absl/copts/generate_copts.py b/third_party/abseil-cpp/absl/copts/generate_copts.py
deleted file mode 100755
index 34be2fc..0000000
--- a/third_party/abseil-cpp/absl/copts/generate_copts.py
+++ /dev/null
@@ -1,109 +0,0 @@
-#!/usr/bin/env python3
-"""Generate Abseil compile compile option configs.
-
-Usage: <path_to_absl>/copts/generate_copts.py
-
-The configs are generated from copts.py.
-"""
-
-from os import path
-import sys
-from copts import COPT_VARS
-
-
-# Helper functions
-def file_header_lines():
- return [
- "GENERATED! DO NOT MANUALLY EDIT THIS FILE.", "",
- "(1) Edit absl/copts/copts.py.",
- "(2) Run `python <path_to_absl>/copts/generate_copts.py`."
- ]
-
-
-def flatten(*lists):
- return [item for sublist in lists for item in sublist]
-
-
-def relative_filename(filename):
- return path.join(path.dirname(__file__), filename)
-
-
-# Style classes. These contain all the syntactic styling needed to generate a
-# copt file for different build tools.
-class CMakeStyle(object):
- """Style object for CMake copts file."""
-
- def separator(self):
- return ""
-
- def list_introducer(self, name):
- return "list(APPEND " + name
-
- def list_closer(self):
- return ")\n"
-
- def docstring(self):
- return "\n".join((("# " + line).strip() for line in file_header_lines()))
-
- def filename(self):
- return "GENERATED_AbseilCopts.cmake"
-
-
-class StarlarkStyle(object):
- """Style object for Starlark copts file."""
-
- def separator(self):
- return ","
-
- def list_introducer(self, name):
- return name + " = ["
-
- def list_closer(self):
- return "]\n"
-
- def docstring(self):
- docstring_quotes = "\"\"\""
- return docstring_quotes + "\n".join(
- flatten(file_header_lines(), [docstring_quotes]))
-
- def filename(self):
- return "GENERATED_copts.bzl"
-
-
-def copt_list(name, arg_list, style):
- """Copt file generation."""
-
- make_line = lambda s: " \"" + s + "\"" + style.separator()
- external_str_list = [make_line(s) for s in arg_list]
-
- return "\n".join(
- flatten(
- [style.list_introducer(name)],
- external_str_list,
- [style.list_closer()]))
-
-
-def generate_copt_file(style):
- """Creates a generated copt file using the given style object.
-
- Args:
- style: either StarlarkStyle() or CMakeStyle()
- """
- with open(relative_filename(style.filename()), "w") as f:
- f.write(style.docstring())
- f.write("\n")
- for var_name, arg_list in sorted(COPT_VARS.items()):
- f.write("\n")
- f.write(copt_list(var_name, arg_list, style))
-
-
-def main(argv):
- if len(argv) > 1:
- raise RuntimeError("generate_copts needs no command line args")
-
- generate_copt_file(StarlarkStyle())
- generate_copt_file(CMakeStyle())
-
-
-if __name__ == "__main__":
- main(sys.argv)
diff --git a/third_party/abseil-cpp/absl/debugging/BUILD.bazel b/third_party/abseil-cpp/absl/debugging/BUILD.bazel
deleted file mode 100644
index a40285c..0000000
--- a/third_party/abseil-cpp/absl/debugging/BUILD.bazel
+++ /dev/null
@@ -1,310 +0,0 @@
-#
-# Copyright 2017 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.
-#
-
-load(
- "//absl:copts/configure_copts.bzl",
- "ABSL_DEFAULT_COPTS",
- "ABSL_DEFAULT_LINKOPTS",
- "ABSL_TEST_COPTS",
-)
-
-package(
- default_visibility = ["//visibility:public"],
-)
-
-licenses(["notice"])
-
-cc_library(
- name = "stacktrace",
- srcs = [
- "internal/stacktrace_aarch64-inl.inc",
- "internal/stacktrace_arm-inl.inc",
- "internal/stacktrace_config.h",
- "internal/stacktrace_emscripten-inl.inc",
- "internal/stacktrace_generic-inl.inc",
- "internal/stacktrace_powerpc-inl.inc",
- "internal/stacktrace_riscv-inl.inc",
- "internal/stacktrace_unimplemented-inl.inc",
- "internal/stacktrace_win32-inl.inc",
- "internal/stacktrace_x86-inl.inc",
- "stacktrace.cc",
- ],
- hdrs = ["stacktrace.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":debugging_internal",
- "//absl/base:config",
- "//absl/base:core_headers",
- "//absl/base:raw_logging_internal",
- ],
-)
-
-cc_library(
- name = "symbolize",
- srcs = [
- "symbolize.cc",
- "symbolize_darwin.inc",
- "symbolize_elf.inc",
- "symbolize_emscripten.inc",
- "symbolize_unimplemented.inc",
- "symbolize_win32.inc",
- ],
- hdrs = [
- "internal/symbolize.h",
- "symbolize.h",
- ],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS + select({
- "//absl:msvc_compiler": ["-DEFAULTLIB:dbghelp.lib"],
- "//absl:clang-cl_compiler": ["-DEFAULTLIB:dbghelp.lib"],
- "//conditions:default": [],
- }),
- deps = [
- ":debugging_internal",
- ":demangle_internal",
- "//absl/base",
- "//absl/base:config",
- "//absl/base:core_headers",
- "//absl/base:dynamic_annotations",
- "//absl/base:malloc_internal",
- "//absl/base:raw_logging_internal",
- "//absl/strings",
- ],
-)
-
-cc_test(
- name = "symbolize_test",
- srcs = ["symbolize_test.cc"],
- copts = ABSL_TEST_COPTS + select({
- "//absl:msvc_compiler": ["/Z7"],
- "//absl:clang-cl_compiler": ["/Z7"],
- "//conditions:default": [],
- }),
- linkopts = ABSL_DEFAULT_LINKOPTS + select({
- "//absl:msvc_compiler": ["/DEBUG"],
- "//absl:clang-cl_compiler": ["/DEBUG"],
- "//conditions:default": [],
- }),
- deps = [
- ":stack_consumption",
- ":symbolize",
- "//absl/base",
- "//absl/base:config",
- "//absl/base:core_headers",
- "//absl/base:raw_logging_internal",
- "//absl/memory",
- "//absl/strings",
- "@com_google_googletest//:gtest",
- ],
-)
-
-cc_library(
- name = "examine_stack",
- srcs = [
- "internal/examine_stack.cc",
- ],
- hdrs = [
- "internal/examine_stack.h",
- ],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- visibility = ["//absl/log/internal:__pkg__"],
- deps = [
- ":stacktrace",
- ":symbolize",
- "//absl/base:config",
- "//absl/base:core_headers",
- "//absl/base:raw_logging_internal",
- ],
-)
-
-cc_library(
- name = "failure_signal_handler",
- srcs = ["failure_signal_handler.cc"],
- hdrs = ["failure_signal_handler.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":examine_stack",
- ":stacktrace",
- "//absl/base",
- "//absl/base:config",
- "//absl/base:core_headers",
- "//absl/base:raw_logging_internal",
- ],
-)
-
-cc_test(
- name = "failure_signal_handler_test",
- srcs = ["failure_signal_handler_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = select({
- "//absl:msvc_compiler": [],
- "//absl:clang-cl_compiler": [],
- "//absl:wasm": [],
- "//conditions:default": ["-pthread"],
- }) + ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":failure_signal_handler",
- ":stacktrace",
- ":symbolize",
- "//absl/base:raw_logging_internal",
- "//absl/strings",
- "@com_google_googletest//:gtest",
- ],
-)
-
-cc_library(
- name = "debugging_internal",
- srcs = [
- "internal/address_is_readable.cc",
- "internal/elf_mem_image.cc",
- "internal/vdso_support.cc",
- ],
- hdrs = [
- "internal/address_is_readable.h",
- "internal/elf_mem_image.h",
- "internal/vdso_support.h",
- ],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- visibility = ["//visibility:private"],
- deps = [
- "//absl/base:config",
- "//absl/base:core_headers",
- "//absl/base:dynamic_annotations",
- "//absl/base:errno_saver",
- "//absl/base:raw_logging_internal",
- ],
-)
-
-cc_library(
- name = "demangle_internal",
- srcs = ["internal/demangle.cc"],
- hdrs = ["internal/demangle.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- visibility = ["//visibility:private"],
- deps = [
- "//absl/base",
- "//absl/base:config",
- "//absl/base:core_headers",
- ],
-)
-
-cc_test(
- name = "demangle_test",
- srcs = ["internal/demangle_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":demangle_internal",
- ":stack_consumption",
- "//absl/base:config",
- "//absl/base:core_headers",
- "//absl/base:raw_logging_internal",
- "//absl/memory",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_library(
- name = "leak_check",
- srcs = ["leak_check.cc"],
- hdrs = ["leak_check.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- "//absl/base:config",
- "//absl/base:core_headers",
- ],
-)
-
-cc_test(
- name = "leak_check_test",
- srcs = ["leak_check_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- tags = ["notsan"],
- deps = [
- ":leak_check",
- "//absl/base:config",
- "//absl/base:raw_logging_internal",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-# Binary that leaks memory and expects to fail on exit. This isn't a
-# test that expected to pass on its own; it exists to be called by a
-# script that checks exit status and output.
-# TODO(absl-team): Write a test to run this with a script that
-# verifies that it correctly fails.
-cc_binary(
- name = "leak_check_fail_test_binary",
- srcs = ["leak_check_fail_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- deps = [
- ":leak_check",
- "//absl/base:raw_logging_internal",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_library(
- name = "stack_consumption",
- testonly = 1,
- srcs = ["internal/stack_consumption.cc"],
- hdrs = ["internal/stack_consumption.h"],
- copts = ABSL_DEFAULT_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- visibility = ["//visibility:private"],
- deps = [
- "//absl/base:config",
- "//absl/base:core_headers",
- "//absl/base:raw_logging_internal",
- ],
-)
-
-cc_test(
- name = "stack_consumption_test",
- srcs = ["internal/stack_consumption_test.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- tags = ["notsan"],
- deps = [
- ":stack_consumption",
- "//absl/base:core_headers",
- "//absl/base:raw_logging_internal",
- "@com_google_googletest//:gtest_main",
- ],
-)
-
-cc_binary(
- name = "stacktrace_benchmark",
- testonly = 1,
- srcs = ["stacktrace_benchmark.cc"],
- copts = ABSL_TEST_COPTS,
- linkopts = ABSL_DEFAULT_LINKOPTS,
- tags = ["benchmark"],
- deps = [
- ":stacktrace",
- "//absl/base:config",
- "//absl/base:core_headers",
- "@com_github_google_benchmark//:benchmark_main",
- ],
-)
diff --git a/third_party/abseil-cpp/absl/debugging/BUILD.gn b/third_party/abseil-cpp/absl/debugging/BUILD.gn
deleted file mode 100644
index 7585fa7..0000000
--- a/third_party/abseil-cpp/absl/debugging/BUILD.gn
+++ /dev/null
@@ -1,146 +0,0 @@
-# Copyright 2018 The Chromium Authors
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-import("//build/config/sanitizers/sanitizers.gni")
-import("//third_party/abseil-cpp/absl.gni")
-
-absl_source_set("stacktrace") {
- sources = [
- "internal/stacktrace_aarch64-inl.inc",
- "internal/stacktrace_arm-inl.inc",
- "internal/stacktrace_config.h",
- "internal/stacktrace_emscripten-inl.inc",
- "internal/stacktrace_generic-inl.inc",
- "internal/stacktrace_powerpc-inl.inc",
- "internal/stacktrace_riscv-inl.inc",
- "internal/stacktrace_unimplemented-inl.inc",
- "internal/stacktrace_win32-inl.inc",
- "internal/stacktrace_x86-inl.inc",
- "stacktrace.cc",
- ]
- public = [ "stacktrace.h" ]
- deps = [
- ":debugging_internal",
- "//third_party/abseil-cpp/absl/base:config",
- "//third_party/abseil-cpp/absl/base:core_headers",
- "//third_party/abseil-cpp/absl/base:raw_logging_internal",
- ]
-}
-
-absl_source_set("symbolize") {
- sources = [
- "symbolize.cc",
- "symbolize_darwin.inc",
- "symbolize_elf.inc",
- "symbolize_emscripten.inc",
- "symbolize_unimplemented.inc",
- "symbolize_win32.inc",
- ]
- public = [
- "internal/symbolize.h",
- "symbolize.h",
- ]
- deps = [
- ":debugging_internal",
- ":demangle_internal",
- "//third_party/abseil-cpp/absl/base",
- "//third_party/abseil-cpp/absl/base:config",
- "//third_party/abseil-cpp/absl/base:core_headers",
- "//third_party/abseil-cpp/absl/base:dynamic_annotations",
- "//third_party/abseil-cpp/absl/base:malloc_internal",
- "//third_party/abseil-cpp/absl/base:raw_logging_internal",
- "//third_party/abseil-cpp/absl/strings",
- ]
-
- # TODO(mbonadei): The bazel file has:
- # -DEFAULTLIB:dbghelp.lib
- # evaluate if this needs to be added here as well.
-}
-
-absl_source_set("examine_stack") {
- sources = [ "internal/examine_stack.cc" ]
- public = [ "internal/examine_stack.h" ]
- visibility = [
- ":*",
- "//third_party/abseil-cpp/absl/log/internal:*",
- ]
- deps = [
- ":stacktrace",
- ":symbolize",
- "//third_party/abseil-cpp/absl/base:config",
- "//third_party/abseil-cpp/absl/base:core_headers",
- "//third_party/abseil-cpp/absl/base:raw_logging_internal",
- ]
-}
-
-absl_source_set("failure_signal_handler") {
- sources = [ "failure_signal_handler.cc" ]
- public = [ "failure_signal_handler.h" ]
- deps = [
- ":examine_stack",
- ":stacktrace",
- "//third_party/abseil-cpp/absl/base",
- "//third_party/abseil-cpp/absl/base:config",
- "//third_party/abseil-cpp/absl/base:core_headers",
- "//third_party/abseil-cpp/absl/base:raw_logging_internal",
- ]
-}
-
-absl_source_set("debugging_internal") {
- sources = [
- "internal/address_is_readable.cc",
- "internal/elf_mem_image.cc",
- "internal/vdso_support.cc",
- ]
- public = [
- "internal/address_is_readable.h",
- "internal/elf_mem_image.h",
- "internal/vdso_support.h",
- ]
- visibility = [ ":*" ]
- deps = [
- "//third_party/abseil-cpp/absl/base:config",
- "//third_party/abseil-cpp/absl/base:core_headers",
- "//third_party/abseil-cpp/absl/base:dynamic_annotations",
- "//third_party/abseil-cpp/absl/base:errno_saver",
- "//third_party/abseil-cpp/absl/base:raw_logging_internal",
- ]
-}
-
-absl_source_set("demangle_internal") {
- sources = [ "internal/demangle.cc" ]
- public = [ "internal/demangle.h" ]
- visibility = [ ":*" ]
- deps = [
- "//third_party/abseil-cpp/absl/base",
- "//third_party/abseil-cpp/absl/base:config",
- "//third_party/abseil-cpp/absl/base:core_headers",
- ]
-}
-
-absl_source_set("leak_check") {
- if (is_ios || is_win) {
- sources = []
- public = []
- } else {
- sources = [ "leak_check.cc" ]
- public = [ "leak_check.h" ]
- }
- deps = [
- "//third_party/abseil-cpp/absl/base:config",
- "//third_party/abseil-cpp/absl/base:core_headers",
- ]
-}
-
-absl_source_set("stack_consumption") {
- testonly = true
- sources = [ "internal/stack_consumption.cc" ]
- public = [ "internal/stack_consumption.h" ]
- deps = [
- "//third_party/abseil-cpp/absl/base:config",
- "//third_party/abseil-cpp/absl/base:core_headers",
- "//third_party/abseil-cpp/absl/base:raw_logging_internal",
- ]
- visibility = [ ":*" ]
-}
diff --git a/third_party/abseil-cpp/absl/debugging/CMakeLists.txt b/third_party/abseil-cpp/absl/debugging/CMakeLists.txt
deleted file mode 100644
index e823f15..0000000
--- a/third_party/abseil-cpp/absl/debugging/CMakeLists.txt
+++ /dev/null
@@ -1,281 +0,0 @@
-#
-# Copyright 2017 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.
-#
-
-find_library(EXECINFO_LIBRARY execinfo)
-
-absl_cc_library(
- NAME
- stacktrace
- HDRS
- "stacktrace.h"
- "internal/stacktrace_aarch64-inl.inc"
- "internal/stacktrace_arm-inl.inc"
- "internal/stacktrace_config.h"
- "internal/stacktrace_emscripten-inl.inc"
- "internal/stacktrace_generic-inl.inc"
- "internal/stacktrace_powerpc-inl.inc"
- "internal/stacktrace_riscv-inl.inc"
- "internal/stacktrace_unimplemented-inl.inc"
- "internal/stacktrace_win32-inl.inc"
- "internal/stacktrace_x86-inl.inc"
- SRCS
- "stacktrace.cc"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- LINKOPTS
- $<$<BOOL:${EXECINFO_LIBRARY}>:${EXECINFO_LIBRARY}>
- DEPS
- absl::debugging_internal
- absl::config
- absl::core_headers
- absl::raw_logging_internal
- PUBLIC
-)
-
-absl_cc_library(
- NAME
- symbolize
- HDRS
- "symbolize.h"
- "internal/symbolize.h"
- SRCS
- "symbolize.cc"
- "symbolize_darwin.inc"
- "symbolize_elf.inc"
- "symbolize_emscripten.inc"
- "symbolize_unimplemented.inc"
- "symbolize_win32.inc"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- LINKOPTS
- ${ABSL_DEFAULT_LINKOPTS}
- $<$<BOOL:${MINGW}>:-ldbghelp>
- DEPS
- absl::debugging_internal
- absl::demangle_internal
- absl::base
- absl::config
- absl::core_headers
- absl::dynamic_annotations
- absl::malloc_internal
- absl::raw_logging_internal
- absl::strings
- PUBLIC
-)
-
-absl_cc_test(
- NAME
- symbolize_test
- SRCS
- "symbolize_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- $<$<BOOL:${MSVC}>:-Z7>
- LINKOPTS
- $<$<BOOL:${MSVC}>:-DEBUG>
- DEPS
- absl::stack_consumption
- absl::symbolize
- absl::base
- absl::config
- absl::core_headers
- absl::memory
- absl::raw_logging_internal
- absl::strings
- GTest::gmock
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- examine_stack
- HDRS
- "internal/examine_stack.h"
- SRCS
- "internal/examine_stack.cc"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::stacktrace
- absl::symbolize
- absl::config
- absl::core_headers
- absl::raw_logging_internal
-)
-
-absl_cc_library(
- NAME
- failure_signal_handler
- HDRS
- "failure_signal_handler.h"
- SRCS
- "failure_signal_handler.cc"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::examine_stack
- absl::stacktrace
- absl::base
- absl::config
- absl::core_headers
- absl::raw_logging_internal
- PUBLIC
-)
-
-absl_cc_test(
- NAME
- failure_signal_handler_test
- SRCS
- "failure_signal_handler_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::failure_signal_handler
- absl::stacktrace
- absl::symbolize
- absl::strings
- absl::raw_logging_internal
- Threads::Threads
- GTest::gmock
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- debugging_internal
- HDRS
- "internal/address_is_readable.h"
- "internal/elf_mem_image.h"
- "internal/vdso_support.h"
- SRCS
- "internal/address_is_readable.cc"
- "internal/elf_mem_image.cc"
- "internal/vdso_support.cc"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::core_headers
- absl::config
- absl::dynamic_annotations
- absl::errno_saver
- absl::raw_logging_internal
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- demangle_internal
- HDRS
- "internal/demangle.h"
- SRCS
- "internal/demangle.cc"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::base
- absl::core_headers
- PUBLIC
-)
-
-absl_cc_test(
- NAME
- demangle_test
- SRCS
- "internal/demangle_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::demangle_internal
- absl::stack_consumption
- absl::config
- absl::core_headers
- absl::memory
- absl::raw_logging_internal
- GTest::gmock_main
-)
-
-absl_cc_library(
- NAME
- leak_check
- HDRS
- "leak_check.h"
- SRCS
- "leak_check.cc"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::config
- absl::core_headers
- PUBLIC
-)
-
-absl_cc_test(
- NAME
- leak_check_test
- SRCS
- "leak_check_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- LINKOPTS
- ${ABSL_DEFAULT_LINKOPTS}
- DEPS
- absl::leak_check
- absl::base
- GTest::gmock_main
-)
-
-# Internal-only target, do not depend on directly.
-absl_cc_library(
- NAME
- stack_consumption
- HDRS
- "internal/stack_consumption.h"
- SRCS
- "internal/stack_consumption.cc"
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::config
- absl::core_headers
- absl::raw_logging_internal
- TESTONLY
-)
-
-absl_cc_test(
- NAME
- stack_consumption_test
- SRCS
- "internal/stack_consumption_test.cc"
- COPTS
- ${ABSL_TEST_COPTS}
- DEPS
- absl::stack_consumption
- absl::core_headers
- absl::raw_logging_internal
- GTest::gmock_main
-)
-
-# component target
-absl_cc_library(
- NAME
- debugging
- COPTS
- ${ABSL_DEFAULT_COPTS}
- DEPS
- absl::stacktrace
- absl::leak_check
- PUBLIC
-)
diff --git a/third_party/abseil-cpp/absl/debugging/failure_signal_handler.cc b/third_party/abseil-cpp/absl/debugging/failure_signal_handler.cc
deleted file mode 100644
index ef8ab9e..0000000
--- a/third_party/abseil-cpp/absl/debugging/failure_signal_handler.cc
+++ /dev/null
@@ -1,389 +0,0 @@
-//
-// Copyright 2018 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/debugging/failure_signal_handler.h"
-
-#include "absl/base/config.h"
-
-#ifdef _WIN32
-#include <windows.h>
-#else
-#include <sched.h>
-#include <unistd.h>
-#endif
-
-#ifdef __APPLE__
-#include <TargetConditionals.h>
-#endif
-
-#ifdef ABSL_HAVE_MMAP
-#include <sys/mman.h>
-#endif
-
-#include <algorithm>
-#include <atomic>
-#include <cerrno>
-#include <csignal>
-#include <cstdio>
-#include <cstring>
-#include <ctime>
-
-#include "absl/base/attributes.h"
-#include "absl/base/internal/raw_logging.h"
-#include "absl/base/internal/sysinfo.h"
-#include "absl/debugging/internal/examine_stack.h"
-#include "absl/debugging/stacktrace.h"
-
-#ifndef _WIN32
-#define ABSL_HAVE_SIGACTION
-// Apple WatchOS and TVOS don't allow sigaltstack
-// Apple macOS has sigaltstack, but using it makes backtrace() unusable.
-#if !(defined(TARGET_OS_OSX) && TARGET_OS_OSX) && \
- !(defined(TARGET_OS_WATCH) && TARGET_OS_WATCH) && \
- !(defined(TARGET_OS_TV) && TARGET_OS_TV) && !defined(__QNX__)
-#define ABSL_HAVE_SIGALTSTACK
-#endif
-#endif
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-
-ABSL_CONST_INIT static FailureSignalHandlerOptions fsh_options;
-
-// Resets the signal handler for signo to the default action for that
-// signal, then raises the signal.
-static void RaiseToDefaultHandler(int signo) {
- signal(signo, SIG_DFL);
- raise(signo);
-}
-
-struct FailureSignalData {
- const int signo;
- const char* const as_string;
-#ifdef ABSL_HAVE_SIGACTION
- struct sigaction previous_action;
- // StructSigaction is used to silence -Wmissing-field-initializers.
- using StructSigaction = struct sigaction;
- #define FSD_PREVIOUS_INIT FailureSignalData::StructSigaction()
-#else
- void (*previous_handler)(int);
- #define FSD_PREVIOUS_INIT SIG_DFL
-#endif
-};
-
-ABSL_CONST_INIT static FailureSignalData failure_signal_data[] = {
- {SIGSEGV, "SIGSEGV", FSD_PREVIOUS_INIT},
- {SIGILL, "SIGILL", FSD_PREVIOUS_INIT},
- {SIGFPE, "SIGFPE", FSD_PREVIOUS_INIT},
- {SIGABRT, "SIGABRT", FSD_PREVIOUS_INIT},
- {SIGTERM, "SIGTERM", FSD_PREVIOUS_INIT},
-#ifndef _WIN32
- {SIGBUS, "SIGBUS", FSD_PREVIOUS_INIT},
- {SIGTRAP, "SIGTRAP", FSD_PREVIOUS_INIT},
-#endif
-};
-
-#undef FSD_PREVIOUS_INIT
-
-static void RaiseToPreviousHandler(int signo) {
- // Search for the previous handler.
- for (const auto& it : failure_signal_data) {
- if (it.signo == signo) {
-#ifdef ABSL_HAVE_SIGACTION
- sigaction(signo, &it.previous_action, nullptr);
-#else
- signal(signo, it.previous_handler);
-#endif
- raise(signo);
- return;
- }
- }
-
- // Not found, use the default handler.
- RaiseToDefaultHandler(signo);
-}
-
-namespace debugging_internal {
-
-const char* FailureSignalToString(int signo) {
- for (const auto& it : failure_signal_data) {
- if (it.signo == signo) {
- return it.as_string;
- }
- }
- return "";
-}
-
-} // namespace debugging_internal
-
-#ifdef ABSL_HAVE_SIGALTSTACK
-
-static bool SetupAlternateStackOnce() {
-#if defined(__wasm__) || defined (__asjms__)
- const size_t page_mask = getpagesize() - 1;
-#else
- const size_t page_mask = static_cast<size_t>(sysconf(_SC_PAGESIZE)) - 1;
-#endif
- size_t stack_size =
- (std::max(static_cast<size_t>(SIGSTKSZ), size_t{65536}) + page_mask) &
- ~page_mask;
-#if defined(ABSL_HAVE_ADDRESS_SANITIZER) || \
- defined(ABSL_HAVE_MEMORY_SANITIZER) || defined(ABSL_HAVE_THREAD_SANITIZER)
- // Account for sanitizer instrumentation requiring additional stack space.
- stack_size *= 5;
-#endif
-
- stack_t sigstk;
- memset(&sigstk, 0, sizeof(sigstk));
- sigstk.ss_size = stack_size;
-
-#ifdef ABSL_HAVE_MMAP
-#ifndef MAP_STACK
-#define MAP_STACK 0
-#endif
-#if defined(MAP_ANON) && !defined(MAP_ANONYMOUS)
-#define MAP_ANONYMOUS MAP_ANON
-#endif
- sigstk.ss_sp = mmap(nullptr, sigstk.ss_size, PROT_READ | PROT_WRITE,
- MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);
- if (sigstk.ss_sp == MAP_FAILED) {
- ABSL_RAW_LOG(FATAL, "mmap() for alternate signal stack failed");
- }
-#else
- sigstk.ss_sp = malloc(sigstk.ss_size);
- if (sigstk.ss_sp == nullptr) {
- ABSL_RAW_LOG(FATAL, "malloc() for alternate signal stack failed");
- }
-#endif
-
- if (sigaltstack(&sigstk, nullptr) != 0) {
- ABSL_RAW_LOG(FATAL, "sigaltstack() failed with errno=%d", errno);
- }
- return true;
-}
-
-#endif
-
-#ifdef ABSL_HAVE_SIGACTION
-
-// Sets up an alternate stack for signal handlers once.
-// Returns the appropriate flag for sig_action.sa_flags
-// if the system supports using an alternate stack.
-static int MaybeSetupAlternateStack() {
-#ifdef ABSL_HAVE_SIGALTSTACK
- ABSL_ATTRIBUTE_UNUSED static const bool kOnce = SetupAlternateStackOnce();
- return SA_ONSTACK;
-#else
- return 0;
-#endif
-}
-
-static void InstallOneFailureHandler(FailureSignalData* data,
- void (*handler)(int, siginfo_t*, void*)) {
- struct sigaction act;
- memset(&act, 0, sizeof(act));
- sigemptyset(&act.sa_mask);
- act.sa_flags |= SA_SIGINFO;
- // SA_NODEFER is required to handle SIGABRT from
- // ImmediateAbortSignalHandler().
- act.sa_flags |= SA_NODEFER;
- if (fsh_options.use_alternate_stack) {
- act.sa_flags |= MaybeSetupAlternateStack();
- }
- act.sa_sigaction = handler;
- ABSL_RAW_CHECK(sigaction(data->signo, &act, &data->previous_action) == 0,
- "sigaction() failed");
-}
-
-#else
-
-static void InstallOneFailureHandler(FailureSignalData* data,
- void (*handler)(int)) {
- data->previous_handler = signal(data->signo, handler);
- ABSL_RAW_CHECK(data->previous_handler != SIG_ERR, "signal() failed");
-}
-
-#endif
-
-static void WriteToStderr(const char* data) {
- absl::raw_log_internal::AsyncSignalSafeWriteToStderr(data, strlen(data));
-}
-
-static void WriteSignalMessage(int signo, int cpu,
- void (*writerfn)(const char*)) {
- char buf[96];
- char on_cpu[32] = {0};
- if (cpu != -1) {
- snprintf(on_cpu, sizeof(on_cpu), " on cpu %d", cpu);
- }
- const char* const signal_string =
- debugging_internal::FailureSignalToString(signo);
- if (signal_string != nullptr && signal_string[0] != '\0') {
- snprintf(buf, sizeof(buf), "*** %s received at time=%ld%s ***\n",
- signal_string,
- static_cast<long>(time(nullptr)), // NOLINT(runtime/int)
- on_cpu);
- } else {
- snprintf(buf, sizeof(buf), "*** Signal %d received at time=%ld%s ***\n",
- signo, static_cast<long>(time(nullptr)), // NOLINT(runtime/int)
- on_cpu);
- }
- writerfn(buf);
-}
-
-// `void*` might not be big enough to store `void(*)(const char*)`.
-struct WriterFnStruct {
- void (*writerfn)(const char*);
-};
-
-// Many of the absl::debugging_internal::Dump* functions in
-// examine_stack.h take a writer function pointer that has a void* arg
-// for historical reasons. failure_signal_handler_writer only takes a
-// data pointer. This function converts between these types.
-static void WriterFnWrapper(const char* data, void* arg) {
- static_cast<WriterFnStruct*>(arg)->writerfn(data);
-}
-
-// Convenient wrapper around DumpPCAndFrameSizesAndStackTrace() for signal
-// handlers. "noinline" so that GetStackFrames() skips the top-most stack
-// frame for this function.
-ABSL_ATTRIBUTE_NOINLINE static void WriteStackTrace(
- void* ucontext, bool symbolize_stacktrace,
- void (*writerfn)(const char*, void*), void* writerfn_arg) {
- constexpr int kNumStackFrames = 32;
- void* stack[kNumStackFrames];
- int frame_sizes[kNumStackFrames];
- int min_dropped_frames;
- int depth = absl::GetStackFramesWithContext(
- stack, frame_sizes, kNumStackFrames,
- 1, // Do not include this function in stack trace.
- ucontext, &min_dropped_frames);
- absl::debugging_internal::DumpPCAndFrameSizesAndStackTrace(
- absl::debugging_internal::GetProgramCounter(ucontext), stack, frame_sizes,
- depth, min_dropped_frames, symbolize_stacktrace, writerfn, writerfn_arg);
-}
-
-// Called by AbslFailureSignalHandler() to write the failure info. It is
-// called once with writerfn set to WriteToStderr() and then possibly
-// with writerfn set to the user provided function.
-static void WriteFailureInfo(int signo, void* ucontext, int cpu,
- void (*writerfn)(const char*)) {
- WriterFnStruct writerfn_struct{writerfn};
- WriteSignalMessage(signo, cpu, writerfn);
- WriteStackTrace(ucontext, fsh_options.symbolize_stacktrace, WriterFnWrapper,
- &writerfn_struct);
-}
-
-// absl::SleepFor() can't be used here since AbslInternalSleepFor()
-// may be overridden to do something that isn't async-signal-safe on
-// some platforms.
-static void PortableSleepForSeconds(int seconds) {
-#ifdef _WIN32
- Sleep(static_cast<DWORD>(seconds * 1000));
-#else
- struct timespec sleep_time;
- sleep_time.tv_sec = seconds;
- sleep_time.tv_nsec = 0;
- while (nanosleep(&sleep_time, &sleep_time) != 0 && errno == EINTR) {}
-#endif
-}
-
-#ifdef ABSL_HAVE_ALARM
-// AbslFailureSignalHandler() installs this as a signal handler for
-// SIGALRM, then sets an alarm to be delivered to the program after a
-// set amount of time. If AbslFailureSignalHandler() hangs for more than
-// the alarm timeout, ImmediateAbortSignalHandler() will abort the
-// program.
-static void ImmediateAbortSignalHandler(int) {
- RaiseToDefaultHandler(SIGABRT);
-}
-#endif
-
-// absl::base_internal::GetTID() returns pid_t on most platforms, but
-// returns absl::base_internal::pid_t on Windows.
-using GetTidType = decltype(absl::base_internal::GetTID());
-ABSL_CONST_INIT static std::atomic<GetTidType> failed_tid(0);
-
-#ifndef ABSL_HAVE_SIGACTION
-static void AbslFailureSignalHandler(int signo) {
- void* ucontext = nullptr;
-#else
-static void AbslFailureSignalHandler(int signo, siginfo_t*, void* ucontext) {
-#endif
-
- const GetTidType this_tid = absl::base_internal::GetTID();
- GetTidType previous_failed_tid = 0;
- if (!failed_tid.compare_exchange_strong(previous_failed_tid, this_tid,
- std::memory_order_acq_rel,
- std::memory_order_relaxed)) {
- ABSL_RAW_LOG(
- ERROR,
- "Signal %d raised at PC=%p while already in AbslFailureSignalHandler()",
- signo, absl::debugging_internal::GetProgramCounter(ucontext));
- if (this_tid != previous_failed_tid) {
- // Another thread is already in AbslFailureSignalHandler(), so wait
- // a bit for it to finish. If the other thread doesn't kill us,
- // we do so after sleeping.
- PortableSleepForSeconds(3);
- RaiseToDefaultHandler(signo);
- // The recursively raised signal may be blocked until we return.
- return;
- }
- }
-
- // Increase the chance that the CPU we report was the same CPU on which the
- // signal was received by doing this as early as possible, i.e. after
- // verifying that this is not a recursive signal handler invocation.
- int my_cpu = -1;
-#ifdef ABSL_HAVE_SCHED_GETCPU
- my_cpu = sched_getcpu();
-#endif
-
-#ifdef ABSL_HAVE_ALARM
- // Set an alarm to abort the program in case this code hangs or deadlocks.
- if (fsh_options.alarm_on_failure_secs > 0) {
- alarm(0); // Cancel any existing alarms.
- signal(SIGALRM, ImmediateAbortSignalHandler);
- alarm(static_cast<unsigned int>(fsh_options.alarm_on_failure_secs));
- }
-#endif
-
- // First write to stderr.
- WriteFailureInfo(signo, ucontext, my_cpu, WriteToStderr);
-
- // Riskier code (because it is less likely to be async-signal-safe)
- // goes after this point.
- if (fsh_options.writerfn != nullptr) {
- WriteFailureInfo(signo, ucontext, my_cpu, fsh_options.writerfn);
- fsh_options.writerfn(nullptr);
- }
-
- if (fsh_options.call_previous_handler) {
- RaiseToPreviousHandler(signo);
- } else {
- RaiseToDefaultHandler(signo);
- }
-}
-
-void InstallFailureSignalHandler(const FailureSignalHandlerOptions& options) {
- fsh_options = options;
- for (auto& it : failure_signal_data) {
- InstallOneFailureHandler(&it, AbslFailureSignalHandler);
- }
-}
-
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/debugging/failure_signal_handler.h b/third_party/abseil-cpp/absl/debugging/failure_signal_handler.h
deleted file mode 100644
index 500115c..0000000
--- a/third_party/abseil-cpp/absl/debugging/failure_signal_handler.h
+++ /dev/null
@@ -1,121 +0,0 @@
-// Copyright 2018 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.
-//
-// -----------------------------------------------------------------------------
-// File: failure_signal_handler.h
-// -----------------------------------------------------------------------------
-//
-// This file configures the Abseil *failure signal handler* to capture and dump
-// useful debugging information (such as a stacktrace) upon program failure.
-//
-// To use the failure signal handler, call `absl::InstallFailureSignalHandler()`
-// very early in your program, usually in the first few lines of main():
-//
-// int main(int argc, char** argv) {
-// // Initialize the symbolizer to get a human-readable stack trace
-// absl::InitializeSymbolizer(argv[0]);
-//
-// absl::FailureSignalHandlerOptions options;
-// absl::InstallFailureSignalHandler(options);
-// DoSomethingInteresting();
-// return 0;
-// }
-//
-// Any program that raises a fatal signal (such as `SIGSEGV`, `SIGILL`,
-// `SIGFPE`, `SIGABRT`, `SIGTERM`, `SIGBUG`, and `SIGTRAP`) will call the
-// installed failure signal handler and provide debugging information to stderr.
-//
-// Note that you should *not* install the Abseil failure signal handler more
-// than once. You may, of course, have another (non-Abseil) failure signal
-// handler installed (which would be triggered if Abseil's failure signal
-// handler sets `call_previous_handler` to `true`).
-
-#ifndef ABSL_DEBUGGING_FAILURE_SIGNAL_HANDLER_H_
-#define ABSL_DEBUGGING_FAILURE_SIGNAL_HANDLER_H_
-
-#include "absl/base/config.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-
-// FailureSignalHandlerOptions
-//
-// Struct for holding `absl::InstallFailureSignalHandler()` configuration
-// options.
-struct FailureSignalHandlerOptions {
- // If true, try to symbolize the stacktrace emitted on failure, provided that
- // you have initialized a symbolizer for that purpose. (See symbolize.h for
- // more information.)
- bool symbolize_stacktrace = true;
-
- // If true, try to run signal handlers on an alternate stack (if supported on
- // the given platform). An alternate stack is useful for program crashes due
- // to a stack overflow; by running on a alternate stack, the signal handler
- // may run even when normal stack space has been exausted. The downside of
- // using an alternate stack is that extra memory for the alternate stack needs
- // to be pre-allocated.
- bool use_alternate_stack = true;
-
- // If positive, indicates the number of seconds after which the failure signal
- // handler is invoked to abort the program. Setting such an alarm is useful in
- // cases where the failure signal handler itself may become hung or
- // deadlocked.
- int alarm_on_failure_secs = 3;
-
- // If true, call the previously registered signal handler for the signal that
- // was received (if one was registered) after the existing signal handler
- // runs. This mechanism can be used to chain signal handlers together.
- //
- // If false, the signal is raised to the default handler for that signal
- // (which normally terminates the program).
- //
- // IMPORTANT: If true, the chained fatal signal handlers must not try to
- // recover from the fatal signal. Instead, they should terminate the program
- // via some mechanism, like raising the default handler for the signal, or by
- // calling `_exit()`. Note that the failure signal handler may put parts of
- // the Abseil library into a state from which they cannot recover.
- bool call_previous_handler = false;
-
- // If non-null, indicates a pointer to a callback function that will be called
- // upon failure, with a string argument containing failure data. This function
- // may be used as a hook to write failure data to a secondary location, such
- // as a log file. This function will also be called with null data, as a hint
- // to flush any buffered data before the program may be terminated. Consider
- // flushing any buffered data in all calls to this function.
- //
- // Since this function runs within a signal handler, it should be
- // async-signal-safe if possible.
- // See http://man7.org/linux/man-pages/man7/signal-safety.7.html
- void (*writerfn)(const char*) = nullptr;
-};
-
-// InstallFailureSignalHandler()
-//
-// Installs a signal handler for the common failure signals `SIGSEGV`, `SIGILL`,
-// `SIGFPE`, `SIGABRT`, `SIGTERM`, `SIGBUG`, and `SIGTRAP` (provided they exist
-// on the given platform). The failure signal handler dumps program failure data
-// useful for debugging in an unspecified format to stderr. This data may
-// include the program counter, a stacktrace, and register information on some
-// systems; do not rely on an exact format for the output, as it is subject to
-// change.
-void InstallFailureSignalHandler(const FailureSignalHandlerOptions& options);
-
-namespace debugging_internal {
-const char* FailureSignalToString(int signo);
-} // namespace debugging_internal
-
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_DEBUGGING_FAILURE_SIGNAL_HANDLER_H_
diff --git a/third_party/abseil-cpp/absl/debugging/failure_signal_handler_test.cc b/third_party/abseil-cpp/absl/debugging/failure_signal_handler_test.cc
deleted file mode 100644
index 6a62428..0000000
--- a/third_party/abseil-cpp/absl/debugging/failure_signal_handler_test.cc
+++ /dev/null
@@ -1,165 +0,0 @@
-//
-// Copyright 2018 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/debugging/failure_signal_handler.h"
-
-#include <csignal>
-#include <cstdio>
-#include <cstdlib>
-#include <cstring>
-#include <fstream>
-
-#include "gtest/gtest.h"
-#include "gmock/gmock.h"
-#include "absl/base/internal/raw_logging.h"
-#include "absl/debugging/stacktrace.h"
-#include "absl/debugging/symbolize.h"
-#include "absl/strings/match.h"
-#include "absl/strings/str_cat.h"
-
-namespace {
-
-using testing::StartsWith;
-
-#if GTEST_HAS_DEATH_TEST
-
-// For the parameterized death tests. GetParam() returns the signal number.
-using FailureSignalHandlerDeathTest = ::testing::TestWithParam<int>;
-
-// This function runs in a fork()ed process on most systems.
-void InstallHandlerAndRaise(int signo) {
- absl::InstallFailureSignalHandler(absl::FailureSignalHandlerOptions());
- raise(signo);
-}
-
-TEST_P(FailureSignalHandlerDeathTest, AbslFailureSignal) {
- const int signo = GetParam();
- std::string exit_regex = absl::StrCat(
- "\\*\\*\\* ", absl::debugging_internal::FailureSignalToString(signo),
- " received at time=");
-#ifndef _WIN32
- EXPECT_EXIT(InstallHandlerAndRaise(signo), testing::KilledBySignal(signo),
- exit_regex);
-#else
- // Windows doesn't have testing::KilledBySignal().
- EXPECT_DEATH_IF_SUPPORTED(InstallHandlerAndRaise(signo), exit_regex);
-#endif
-}
-
-ABSL_CONST_INIT FILE* error_file = nullptr;
-
-void WriteToErrorFile(const char* msg) {
- if (msg != nullptr) {
- ABSL_RAW_CHECK(fwrite(msg, strlen(msg), 1, error_file) == 1,
- "fwrite() failed");
- }
- ABSL_RAW_CHECK(fflush(error_file) == 0, "fflush() failed");
-}
-
-std::string GetTmpDir() {
- // TEST_TMPDIR is set by Bazel. Try the others when not running under Bazel.
- static const char* const kTmpEnvVars[] = {"TEST_TMPDIR", "TMPDIR", "TEMP",
- "TEMPDIR", "TMP"};
- for (const char* const var : kTmpEnvVars) {
- const char* tmp_dir = std::getenv(var);
- if (tmp_dir != nullptr) {
- return tmp_dir;
- }
- }
-
- // Try something reasonable.
- return "/tmp";
-}
-
-// This function runs in a fork()ed process on most systems.
-void InstallHandlerWithWriteToFileAndRaise(const char* file, int signo) {
- error_file = fopen(file, "w");
- ABSL_RAW_CHECK(error_file != nullptr, "Failed create error_file");
- absl::FailureSignalHandlerOptions options;
- options.writerfn = WriteToErrorFile;
- absl::InstallFailureSignalHandler(options);
- raise(signo);
-}
-
-TEST_P(FailureSignalHandlerDeathTest, AbslFatalSignalsWithWriterFn) {
- const int signo = GetParam();
- std::string tmp_dir = GetTmpDir();
- std::string file = absl::StrCat(tmp_dir, "/signo_", signo);
-
- std::string exit_regex = absl::StrCat(
- "\\*\\*\\* ", absl::debugging_internal::FailureSignalToString(signo),
- " received at time=");
-#ifndef _WIN32
- EXPECT_EXIT(InstallHandlerWithWriteToFileAndRaise(file.c_str(), signo),
- testing::KilledBySignal(signo), exit_regex);
-#else
- // Windows doesn't have testing::KilledBySignal().
- EXPECT_DEATH_IF_SUPPORTED(
- InstallHandlerWithWriteToFileAndRaise(file.c_str(), signo), exit_regex);
-#endif
-
- // Open the file in this process and check its contents.
- std::fstream error_output(file);
- ASSERT_TRUE(error_output.is_open()) << file;
- std::string error_line;
- std::getline(error_output, error_line);
- EXPECT_THAT(
- error_line,
- StartsWith(absl::StrCat(
- "*** ", absl::debugging_internal::FailureSignalToString(signo),
- " received at ")));
-
- // On platforms where it is possible to get the current CPU, the
- // CPU number is also logged. Check that it is present in output.
-#if defined(__linux__)
- EXPECT_THAT(error_line, testing::HasSubstr(" on cpu "));
-#endif
-
- if (absl::debugging_internal::StackTraceWorksForTest()) {
- std::getline(error_output, error_line);
- EXPECT_THAT(error_line, StartsWith("PC: "));
- }
-}
-
-constexpr int kFailureSignals[] = {
- SIGSEGV, SIGILL, SIGFPE, SIGABRT, SIGTERM,
-#ifndef _WIN32
- SIGBUS, SIGTRAP,
-#endif
-};
-
-std::string SignalParamToString(const ::testing::TestParamInfo<int>& info) {
- std::string result =
- absl::debugging_internal::FailureSignalToString(info.param);
- if (result.empty()) {
- result = absl::StrCat(info.param);
- }
- return result;
-}
-
-INSTANTIATE_TEST_SUITE_P(AbslDeathTest, FailureSignalHandlerDeathTest,
- ::testing::ValuesIn(kFailureSignals),
- SignalParamToString);
-
-#endif // GTEST_HAS_DEATH_TEST
-
-} // namespace
-
-int main(int argc, char** argv) {
- absl::InitializeSymbolizer(argv[0]);
- testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/third_party/abseil-cpp/absl/debugging/internal/address_is_readable.cc b/third_party/abseil-cpp/absl/debugging/internal/address_is_readable.cc
deleted file mode 100644
index 91eaa76..0000000
--- a/third_party/abseil-cpp/absl/debugging/internal/address_is_readable.cc
+++ /dev/null
@@ -1,96 +0,0 @@
-// Copyright 2017 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.
-
-// base::AddressIsReadable() probes an address to see whether it is readable,
-// without faulting.
-
-#include "absl/debugging/internal/address_is_readable.h"
-
-#if !defined(__linux__) || defined(__ANDROID__)
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace debugging_internal {
-
-// On platforms other than Linux, just return true.
-bool AddressIsReadable(const void* /* addr */) { return true; }
-
-} // namespace debugging_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#else // __linux__ && !__ANDROID__
-
-#include <stdint.h>
-#include <syscall.h>
-#include <unistd.h>
-
-#include "absl/base/internal/errno_saver.h"
-#include "absl/base/internal/raw_logging.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace debugging_internal {
-
-// NOTE: be extra careful about adding any interposable function calls here
-// (such as open(), read(), etc.). These symbols may be interposed and will get
-// invoked in contexts they don't expect.
-//
-// NOTE: any new system calls here may also require sandbox reconfiguration.
-//
-bool AddressIsReadable(const void *addr) {
- // Align address on 8-byte boundary. On aarch64, checking last
- // byte before inaccessible page returned unexpected EFAULT.
- const uintptr_t u_addr = reinterpret_cast<uintptr_t>(addr) & ~uintptr_t{7};
- addr = reinterpret_cast<const void *>(u_addr);
-
- // rt_sigprocmask below will succeed for this input.
- if (addr == nullptr) return false;
-
- absl::base_internal::ErrnoSaver errno_saver;
-
- // Here we probe with some syscall which
- // - accepts an 8-byte region of user memory as input
- // - tests for EFAULT before other validation
- // - has no problematic side-effects
- //
- // rt_sigprocmask(2) works for this. It copies sizeof(kernel_sigset_t)==8
- // bytes from the address into the kernel memory before any validation.
- //
- // The call can never succeed, since the `how` parameter is not one of
- // SIG_BLOCK, SIG_UNBLOCK, SIG_SETMASK.
- //
- // This strategy depends on Linux implementation details,
- // so we rely on the test to alert us if it stops working.
- //
- // Some discarded past approaches:
- // - msync() doesn't reject PROT_NONE regions
- // - write() on /dev/null doesn't return EFAULT
- // - write() on a pipe requires creating it and draining the writes
- // - connect() works but is problematic for sandboxes and needs a valid
- // file descriptor
- //
- // This can never succeed (invalid first argument to sigprocmask).
- ABSL_RAW_CHECK(syscall(SYS_rt_sigprocmask, ~0, addr, nullptr,
- /*sizeof(kernel_sigset_t)*/ 8) == -1,
- "unexpected success");
- ABSL_RAW_CHECK(errno == EFAULT || errno == EINVAL, "unexpected errno");
- return errno != EFAULT;
-}
-
-} // namespace debugging_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // __linux__ && !__ANDROID__
diff --git a/third_party/abseil-cpp/absl/debugging/internal/address_is_readable.h b/third_party/abseil-cpp/absl/debugging/internal/address_is_readable.h
deleted file mode 100644
index 4bbaf4d..0000000
--- a/third_party/abseil-cpp/absl/debugging/internal/address_is_readable.h
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright 2017 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_DEBUGGING_INTERNAL_ADDRESS_IS_READABLE_H_
-#define ABSL_DEBUGGING_INTERNAL_ADDRESS_IS_READABLE_H_
-
-#include "absl/base/config.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace debugging_internal {
-
-// Return whether the byte at *addr is readable, without faulting.
-// Save and restores errno.
-bool AddressIsReadable(const void *addr);
-
-} // namespace debugging_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_DEBUGGING_INTERNAL_ADDRESS_IS_READABLE_H_
diff --git a/third_party/abseil-cpp/absl/debugging/internal/demangle.cc b/third_party/abseil-cpp/absl/debugging/internal/demangle.cc
deleted file mode 100644
index f283291..0000000
--- a/third_party/abseil-cpp/absl/debugging/internal/demangle.cc
+++ /dev/null
@@ -1,1988 +0,0 @@
-// Copyright 2018 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.
-
-// For reference check out:
-// https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling
-//
-// Note that we only have partial C++11 support yet.
-
-#include "absl/debugging/internal/demangle.h"
-
-#include <cstdint>
-#include <cstdio>
-#include <limits>
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace debugging_internal {
-
-typedef struct {
- const char *abbrev;
- const char *real_name;
- // Number of arguments in <expression> context, or 0 if disallowed.
- int arity;
-} AbbrevPair;
-
-// List of operators from Itanium C++ ABI.
-static const AbbrevPair kOperatorList[] = {
- // New has special syntax (not currently supported).
- {"nw", "new", 0},
- {"na", "new[]", 0},
-
- // Works except that the 'gs' prefix is not supported.
- {"dl", "delete", 1},
- {"da", "delete[]", 1},
-
- {"ps", "+", 1}, // "positive"
- {"ng", "-", 1}, // "negative"
- {"ad", "&", 1}, // "address-of"
- {"de", "*", 1}, // "dereference"
- {"co", "~", 1},
-
- {"pl", "+", 2},
- {"mi", "-", 2},
- {"ml", "*", 2},
- {"dv", "/", 2},
- {"rm", "%", 2},
- {"an", "&", 2},
- {"or", "|", 2},
- {"eo", "^", 2},
- {"aS", "=", 2},
- {"pL", "+=", 2},
- {"mI", "-=", 2},
- {"mL", "*=", 2},
- {"dV", "/=", 2},
- {"rM", "%=", 2},
- {"aN", "&=", 2},
- {"oR", "|=", 2},
- {"eO", "^=", 2},
- {"ls", "<<", 2},
- {"rs", ">>", 2},
- {"lS", "<<=", 2},
- {"rS", ">>=", 2},
- {"eq", "==", 2},
- {"ne", "!=", 2},
- {"lt", "<", 2},
- {"gt", ">", 2},
- {"le", "<=", 2},
- {"ge", ">=", 2},
- {"nt", "!", 1},
- {"aa", "&&", 2},
- {"oo", "||", 2},
- {"pp", "++", 1},
- {"mm", "--", 1},
- {"cm", ",", 2},
- {"pm", "->*", 2},
- {"pt", "->", 0}, // Special syntax
- {"cl", "()", 0}, // Special syntax
- {"ix", "[]", 2},
- {"qu", "?", 3},
- {"st", "sizeof", 0}, // Special syntax
- {"sz", "sizeof", 1}, // Not a real operator name, but used in expressions.
- {nullptr, nullptr, 0},
-};
-
-// List of builtin types from Itanium C++ ABI.
-//
-// Invariant: only one- or two-character type abbreviations here.
-static const AbbrevPair kBuiltinTypeList[] = {
- {"v", "void", 0},
- {"w", "wchar_t", 0},
- {"b", "bool", 0},
- {"c", "char", 0},
- {"a", "signed char", 0},
- {"h", "unsigned char", 0},
- {"s", "short", 0},
- {"t", "unsigned short", 0},
- {"i", "int", 0},
- {"j", "unsigned int", 0},
- {"l", "long", 0},
- {"m", "unsigned long", 0},
- {"x", "long long", 0},
- {"y", "unsigned long long", 0},
- {"n", "__int128", 0},
- {"o", "unsigned __int128", 0},
- {"f", "float", 0},
- {"d", "double", 0},
- {"e", "long double", 0},
- {"g", "__float128", 0},
- {"z", "ellipsis", 0},
-
- {"De", "decimal128", 0}, // IEEE 754r decimal floating point (128 bits)
- {"Dd", "decimal64", 0}, // IEEE 754r decimal floating point (64 bits)
- {"Dc", "decltype(auto)", 0},
- {"Da", "auto", 0},
- {"Dn", "std::nullptr_t", 0}, // i.e., decltype(nullptr)
- {"Df", "decimal32", 0}, // IEEE 754r decimal floating point (32 bits)
- {"Di", "char32_t", 0},
- {"Du", "char8_t", 0},
- {"Ds", "char16_t", 0},
- {"Dh", "float16", 0}, // IEEE 754r half-precision float (16 bits)
- {nullptr, nullptr, 0},
-};
-
-// List of substitutions Itanium C++ ABI.
-static const AbbrevPair kSubstitutionList[] = {
- {"St", "", 0},
- {"Sa", "allocator", 0},
- {"Sb", "basic_string", 0},
- // std::basic_string<char, std::char_traits<char>,std::allocator<char> >
- {"Ss", "string", 0},
- // std::basic_istream<char, std::char_traits<char> >
- {"Si", "istream", 0},
- // std::basic_ostream<char, std::char_traits<char> >
- {"So", "ostream", 0},
- // std::basic_iostream<char, std::char_traits<char> >
- {"Sd", "iostream", 0},
- {nullptr, nullptr, 0},
-};
-
-// State needed for demangling. This struct is copied in almost every stack
-// frame, so every byte counts.
-typedef struct {
- int mangled_idx; // Cursor of mangled name.
- int out_cur_idx; // Cursor of output string.
- int prev_name_idx; // For constructors/destructors.
- unsigned int prev_name_length : 16; // For constructors/destructors.
- signed int nest_level : 15; // For nested names.
- unsigned int append : 1; // Append flag.
- // Note: for some reason MSVC can't pack "bool append : 1" into the same int
- // with the above two fields, so we use an int instead. Amusingly it can pack
- // "signed bool" as expected, but relying on that to continue to be a legal
- // type seems ill-advised (as it's illegal in at least clang).
-} ParseState;
-
-static_assert(sizeof(ParseState) == 4 * sizeof(int),
- "unexpected size of ParseState");
-
-// One-off state for demangling that's not subject to backtracking -- either
-// constant data, data that's intentionally immune to backtracking (steps), or
-// data that would never be changed by backtracking anyway (recursion_depth).
-//
-// Only one copy of this exists for each call to Demangle, so the size of this
-// struct is nearly inconsequential.
-typedef struct {
- const char *mangled_begin; // Beginning of input string.
- char *out; // Beginning of output string.
- int out_end_idx; // One past last allowed output character.
- int recursion_depth; // For stack exhaustion prevention.
- int steps; // Cap how much work we'll do, regardless of depth.
- ParseState parse_state; // Backtrackable state copied for most frames.
-} State;
-
-namespace {
-// Prevent deep recursion / stack exhaustion.
-// Also prevent unbounded handling of complex inputs.
-class ComplexityGuard {
- public:
- explicit ComplexityGuard(State *state) : state_(state) {
- ++state->recursion_depth;
- ++state->steps;
- }
- ~ComplexityGuard() { --state_->recursion_depth; }
-
- // 256 levels of recursion seems like a reasonable upper limit on depth.
- // 128 is not enough to demagle synthetic tests from demangle_unittest.txt:
- // "_ZaaZZZZ..." and "_ZaaZcvZcvZ..."
- static constexpr int kRecursionDepthLimit = 256;
-
- // We're trying to pick a charitable upper-limit on how many parse steps are
- // necessary to handle something that a human could actually make use of.
- // This is mostly in place as a bound on how much work we'll do if we are
- // asked to demangle an mangled name from an untrusted source, so it should be
- // much larger than the largest expected symbol, but much smaller than the
- // amount of work we can do in, e.g., a second.
- //
- // Some real-world symbols from an arbitrary binary started failing between
- // 2^12 and 2^13, so we multiply the latter by an extra factor of 16 to set
- // the limit.
- //
- // Spending one second on 2^17 parse steps would require each step to take
- // 7.6us, or ~30000 clock cycles, so it's safe to say this can be done in
- // under a second.
- static constexpr int kParseStepsLimit = 1 << 17;
-
- bool IsTooComplex() const {
- return state_->recursion_depth > kRecursionDepthLimit ||
- state_->steps > kParseStepsLimit;
- }
-
- private:
- State *state_;
-};
-} // namespace
-
-// We don't use strlen() in libc since it's not guaranteed to be async
-// signal safe.
-static size_t StrLen(const char *str) {
- size_t len = 0;
- while (*str != '\0') {
- ++str;
- ++len;
- }
- return len;
-}
-
-// Returns true if "str" has at least "n" characters remaining.
-static bool AtLeastNumCharsRemaining(const char *str, size_t n) {
- for (size_t i = 0; i < n; ++i) {
- if (str[i] == '\0') {
- return false;
- }
- }
- return true;
-}
-
-// Returns true if "str" has "prefix" as a prefix.
-static bool StrPrefix(const char *str, const char *prefix) {
- size_t i = 0;
- while (str[i] != '\0' && prefix[i] != '\0' && str[i] == prefix[i]) {
- ++i;
- }
- return prefix[i] == '\0'; // Consumed everything in "prefix".
-}
-
-static void InitState(State* state,
- const char* mangled,
- char* out,
- size_t out_size) {
- state->mangled_begin = mangled;
- state->out = out;
- state->out_end_idx = static_cast<int>(out_size);
- state->recursion_depth = 0;
- state->steps = 0;
-
- state->parse_state.mangled_idx = 0;
- state->parse_state.out_cur_idx = 0;
- state->parse_state.prev_name_idx = 0;
- state->parse_state.prev_name_length = 0;
- state->parse_state.nest_level = -1;
- state->parse_state.append = true;
-}
-
-static inline const char *RemainingInput(State *state) {
- return &state->mangled_begin[state->parse_state.mangled_idx];
-}
-
-// Returns true and advances "mangled_idx" if we find "one_char_token"
-// at "mangled_idx" position. It is assumed that "one_char_token" does
-// not contain '\0'.
-static bool ParseOneCharToken(State *state, const char one_char_token) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- if (RemainingInput(state)[0] == one_char_token) {
- ++state->parse_state.mangled_idx;
- return true;
- }
- return false;
-}
-
-// Returns true and advances "mangled_cur" if we find "two_char_token"
-// at "mangled_cur" position. It is assumed that "two_char_token" does
-// not contain '\0'.
-static bool ParseTwoCharToken(State *state, const char *two_char_token) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- if (RemainingInput(state)[0] == two_char_token[0] &&
- RemainingInput(state)[1] == two_char_token[1]) {
- state->parse_state.mangled_idx += 2;
- return true;
- }
- return false;
-}
-
-// Returns true and advances "mangled_cur" if we find any character in
-// "char_class" at "mangled_cur" position.
-static bool ParseCharClass(State *state, const char *char_class) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- if (RemainingInput(state)[0] == '\0') {
- return false;
- }
- const char *p = char_class;
- for (; *p != '\0'; ++p) {
- if (RemainingInput(state)[0] == *p) {
- ++state->parse_state.mangled_idx;
- return true;
- }
- }
- return false;
-}
-
-static bool ParseDigit(State *state, int *digit) {
- char c = RemainingInput(state)[0];
- if (ParseCharClass(state, "0123456789")) {
- if (digit != nullptr) {
- *digit = c - '0';
- }
- return true;
- }
- return false;
-}
-
-// This function is used for handling an optional non-terminal.
-static bool Optional(bool /*status*/) { return true; }
-
-// This function is used for handling <non-terminal>+ syntax.
-typedef bool (*ParseFunc)(State *);
-static bool OneOrMore(ParseFunc parse_func, State *state) {
- if (parse_func(state)) {
- while (parse_func(state)) {
- }
- return true;
- }
- return false;
-}
-
-// This function is used for handling <non-terminal>* syntax. The function
-// always returns true and must be followed by a termination token or a
-// terminating sequence not handled by parse_func (e.g.
-// ParseOneCharToken(state, 'E')).
-static bool ZeroOrMore(ParseFunc parse_func, State *state) {
- while (parse_func(state)) {
- }
- return true;
-}
-
-// Append "str" at "out_cur_idx". If there is an overflow, out_cur_idx is
-// set to out_end_idx+1. The output string is ensured to
-// always terminate with '\0' as long as there is no overflow.
-static void Append(State *state, const char *const str, const size_t length) {
- for (size_t i = 0; i < length; ++i) {
- if (state->parse_state.out_cur_idx + 1 <
- state->out_end_idx) { // +1 for '\0'
- state->out[state->parse_state.out_cur_idx++] = str[i];
- } else {
- // signal overflow
- state->parse_state.out_cur_idx = state->out_end_idx + 1;
- break;
- }
- }
- if (state->parse_state.out_cur_idx < state->out_end_idx) {
- state->out[state->parse_state.out_cur_idx] =
- '\0'; // Terminate it with '\0'
- }
-}
-
-// We don't use equivalents in libc to avoid locale issues.
-static bool IsLower(char c) { return c >= 'a' && c <= 'z'; }
-
-static bool IsAlpha(char c) {
- return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
-}
-
-static bool IsDigit(char c) { return c >= '0' && c <= '9'; }
-
-// Returns true if "str" is a function clone suffix. These suffixes are used
-// by GCC 4.5.x and later versions (and our locally-modified version of GCC
-// 4.4.x) to indicate functions which have been cloned during optimization.
-// We treat any sequence (.<alpha>+.<digit>+)+ as a function clone suffix.
-// Additionally, '_' is allowed along with the alphanumeric sequence.
-static bool IsFunctionCloneSuffix(const char *str) {
- size_t i = 0;
- while (str[i] != '\0') {
- bool parsed = false;
- // Consume a single [.<alpha> | _]*[.<digit>]* sequence.
- if (str[i] == '.' && (IsAlpha(str[i + 1]) || str[i + 1] == '_')) {
- parsed = true;
- i += 2;
- while (IsAlpha(str[i]) || str[i] == '_') {
- ++i;
- }
- }
- if (str[i] == '.' && IsDigit(str[i + 1])) {
- parsed = true;
- i += 2;
- while (IsDigit(str[i])) {
- ++i;
- }
- }
- if (!parsed)
- return false;
- }
- return true; // Consumed everything in "str".
-}
-
-static bool EndsWith(State *state, const char chr) {
- return state->parse_state.out_cur_idx > 0 &&
- state->parse_state.out_cur_idx < state->out_end_idx &&
- chr == state->out[state->parse_state.out_cur_idx - 1];
-}
-
-// Append "str" with some tweaks, iff "append" state is true.
-static void MaybeAppendWithLength(State *state, const char *const str,
- const size_t length) {
- if (state->parse_state.append && length > 0) {
- // Append a space if the output buffer ends with '<' and "str"
- // starts with '<' to avoid <<<.
- if (str[0] == '<' && EndsWith(state, '<')) {
- Append(state, " ", 1);
- }
- // Remember the last identifier name for ctors/dtors,
- // but only if we haven't yet overflown the buffer.
- if (state->parse_state.out_cur_idx < state->out_end_idx &&
- (IsAlpha(str[0]) || str[0] == '_')) {
- state->parse_state.prev_name_idx = state->parse_state.out_cur_idx;
- state->parse_state.prev_name_length = static_cast<unsigned int>(length);
- }
- Append(state, str, length);
- }
-}
-
-// Appends a positive decimal number to the output if appending is enabled.
-static bool MaybeAppendDecimal(State *state, int val) {
- // Max {32-64}-bit unsigned int is 20 digits.
- constexpr size_t kMaxLength = 20;
- char buf[kMaxLength];
-
- // We can't use itoa or sprintf as neither is specified to be
- // async-signal-safe.
- if (state->parse_state.append) {
- // We can't have a one-before-the-beginning pointer, so instead start with
- // one-past-the-end and manipulate one character before the pointer.
- char *p = &buf[kMaxLength];
- do { // val=0 is the only input that should write a leading zero digit.
- *--p = static_cast<char>((val % 10) + '0');
- val /= 10;
- } while (p > buf && val != 0);
-
- // 'p' landed on the last character we set. How convenient.
- Append(state, p, kMaxLength - static_cast<size_t>(p - buf));
- }
-
- return true;
-}
-
-// A convenient wrapper around MaybeAppendWithLength().
-// Returns true so that it can be placed in "if" conditions.
-static bool MaybeAppend(State *state, const char *const str) {
- if (state->parse_state.append) {
- size_t length = StrLen(str);
- MaybeAppendWithLength(state, str, length);
- }
- return true;
-}
-
-// This function is used for handling nested names.
-static bool EnterNestedName(State *state) {
- state->parse_state.nest_level = 0;
- return true;
-}
-
-// This function is used for handling nested names.
-static bool LeaveNestedName(State *state, int16_t prev_value) {
- state->parse_state.nest_level = prev_value;
- return true;
-}
-
-// Disable the append mode not to print function parameters, etc.
-static bool DisableAppend(State *state) {
- state->parse_state.append = false;
- return true;
-}
-
-// Restore the append mode to the previous state.
-static bool RestoreAppend(State *state, bool prev_value) {
- state->parse_state.append = prev_value;
- return true;
-}
-
-// Increase the nest level for nested names.
-static void MaybeIncreaseNestLevel(State *state) {
- if (state->parse_state.nest_level > -1) {
- ++state->parse_state.nest_level;
- }
-}
-
-// Appends :: for nested names if necessary.
-static void MaybeAppendSeparator(State *state) {
- if (state->parse_state.nest_level >= 1) {
- MaybeAppend(state, "::");
- }
-}
-
-// Cancel the last separator if necessary.
-static void MaybeCancelLastSeparator(State *state) {
- if (state->parse_state.nest_level >= 1 && state->parse_state.append &&
- state->parse_state.out_cur_idx >= 2) {
- state->parse_state.out_cur_idx -= 2;
- state->out[state->parse_state.out_cur_idx] = '\0';
- }
-}
-
-// Returns true if the identifier of the given length pointed to by
-// "mangled_cur" is anonymous namespace.
-static bool IdentifierIsAnonymousNamespace(State *state, size_t length) {
- // Returns true if "anon_prefix" is a proper prefix of "mangled_cur".
- static const char anon_prefix[] = "_GLOBAL__N_";
- return (length > (sizeof(anon_prefix) - 1) &&
- StrPrefix(RemainingInput(state), anon_prefix));
-}
-
-// Forward declarations of our parsing functions.
-static bool ParseMangledName(State *state);
-static bool ParseEncoding(State *state);
-static bool ParseName(State *state);
-static bool ParseUnscopedName(State *state);
-static bool ParseNestedName(State *state);
-static bool ParsePrefix(State *state);
-static bool ParseUnqualifiedName(State *state);
-static bool ParseSourceName(State *state);
-static bool ParseLocalSourceName(State *state);
-static bool ParseUnnamedTypeName(State *state);
-static bool ParseNumber(State *state, int *number_out);
-static bool ParseFloatNumber(State *state);
-static bool ParseSeqId(State *state);
-static bool ParseIdentifier(State *state, size_t length);
-static bool ParseOperatorName(State *state, int *arity);
-static bool ParseSpecialName(State *state);
-static bool ParseCallOffset(State *state);
-static bool ParseNVOffset(State *state);
-static bool ParseVOffset(State *state);
-static bool ParseAbiTags(State *state);
-static bool ParseCtorDtorName(State *state);
-static bool ParseDecltype(State *state);
-static bool ParseType(State *state);
-static bool ParseCVQualifiers(State *state);
-static bool ParseBuiltinType(State *state);
-static bool ParseFunctionType(State *state);
-static bool ParseBareFunctionType(State *state);
-static bool ParseClassEnumType(State *state);
-static bool ParseArrayType(State *state);
-static bool ParsePointerToMemberType(State *state);
-static bool ParseTemplateParam(State *state);
-static bool ParseTemplateTemplateParam(State *state);
-static bool ParseTemplateArgs(State *state);
-static bool ParseTemplateArg(State *state);
-static bool ParseBaseUnresolvedName(State *state);
-static bool ParseUnresolvedName(State *state);
-static bool ParseExpression(State *state);
-static bool ParseExprPrimary(State *state);
-static bool ParseExprCastValue(State *state);
-static bool ParseLocalName(State *state);
-static bool ParseLocalNameSuffix(State *state);
-static bool ParseDiscriminator(State *state);
-static bool ParseSubstitution(State *state, bool accept_std);
-
-// Implementation note: the following code is a straightforward
-// translation of the Itanium C++ ABI defined in BNF with a couple of
-// exceptions.
-//
-// - Support GNU extensions not defined in the Itanium C++ ABI
-// - <prefix> and <template-prefix> are combined to avoid infinite loop
-// - Reorder patterns to shorten the code
-// - Reorder patterns to give greedier functions precedence
-// We'll mark "Less greedy than" for these cases in the code
-//
-// Each parsing function changes the parse state and returns true on
-// success, or returns false and doesn't change the parse state (note:
-// the parse-steps counter increases regardless of success or failure).
-// To ensure that the parse state isn't changed in the latter case, we
-// save the original state before we call multiple parsing functions
-// consecutively with &&, and restore it if unsuccessful. See
-// ParseEncoding() as an example of this convention. We follow the
-// convention throughout the code.
-//
-// Originally we tried to do demangling without following the full ABI
-// syntax but it turned out we needed to follow the full syntax to
-// parse complicated cases like nested template arguments. Note that
-// implementing a full-fledged demangler isn't trivial (libiberty's
-// cp-demangle.c has +4300 lines).
-//
-// Note that (foo) in <(foo) ...> is a modifier to be ignored.
-//
-// Reference:
-// - Itanium C++ ABI
-// <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling>
-
-// <mangled-name> ::= _Z <encoding>
-static bool ParseMangledName(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- return ParseTwoCharToken(state, "_Z") && ParseEncoding(state);
-}
-
-// <encoding> ::= <(function) name> <bare-function-type>
-// ::= <(data) name>
-// ::= <special-name>
-static bool ParseEncoding(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- // Implementing the first two productions together as <name>
- // [<bare-function-type>] avoids exponential blowup of backtracking.
- //
- // Since Optional(...) can't fail, there's no need to copy the state for
- // backtracking.
- if (ParseName(state) && Optional(ParseBareFunctionType(state))) {
- return true;
- }
-
- if (ParseSpecialName(state)) {
- return true;
- }
- return false;
-}
-
-// <name> ::= <nested-name>
-// ::= <unscoped-template-name> <template-args>
-// ::= <unscoped-name>
-// ::= <local-name>
-static bool ParseName(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- if (ParseNestedName(state) || ParseLocalName(state)) {
- return true;
- }
-
- // We reorganize the productions to avoid re-parsing unscoped names.
- // - Inline <unscoped-template-name> productions:
- // <name> ::= <substitution> <template-args>
- // ::= <unscoped-name> <template-args>
- // ::= <unscoped-name>
- // - Merge the two productions that start with unscoped-name:
- // <name> ::= <unscoped-name> [<template-args>]
-
- ParseState copy = state->parse_state;
- // "std<...>" isn't a valid name.
- if (ParseSubstitution(state, /*accept_std=*/false) &&
- ParseTemplateArgs(state)) {
- return true;
- }
- state->parse_state = copy;
-
- // Note there's no need to restore state after this since only the first
- // subparser can fail.
- return ParseUnscopedName(state) && Optional(ParseTemplateArgs(state));
-}
-
-// <unscoped-name> ::= <unqualified-name>
-// ::= St <unqualified-name>
-static bool ParseUnscopedName(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- if (ParseUnqualifiedName(state)) {
- return true;
- }
-
- ParseState copy = state->parse_state;
- if (ParseTwoCharToken(state, "St") && MaybeAppend(state, "std::") &&
- ParseUnqualifiedName(state)) {
- return true;
- }
- state->parse_state = copy;
- return false;
-}
-
-// <ref-qualifer> ::= R // lvalue method reference qualifier
-// ::= O // rvalue method reference qualifier
-static inline bool ParseRefQualifier(State *state) {
- return ParseCharClass(state, "OR");
-}
-
-// <nested-name> ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix>
-// <unqualified-name> E
-// ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
-// <template-args> E
-static bool ParseNestedName(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- ParseState copy = state->parse_state;
- if (ParseOneCharToken(state, 'N') && EnterNestedName(state) &&
- Optional(ParseCVQualifiers(state)) &&
- Optional(ParseRefQualifier(state)) && ParsePrefix(state) &&
- LeaveNestedName(state, copy.nest_level) &&
- ParseOneCharToken(state, 'E')) {
- return true;
- }
- state->parse_state = copy;
- return false;
-}
-
-// This part is tricky. If we literally translate them to code, we'll
-// end up infinite loop. Hence we merge them to avoid the case.
-//
-// <prefix> ::= <prefix> <unqualified-name>
-// ::= <template-prefix> <template-args>
-// ::= <template-param>
-// ::= <substitution>
-// ::= # empty
-// <template-prefix> ::= <prefix> <(template) unqualified-name>
-// ::= <template-param>
-// ::= <substitution>
-static bool ParsePrefix(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- bool has_something = false;
- while (true) {
- MaybeAppendSeparator(state);
- if (ParseTemplateParam(state) ||
- ParseSubstitution(state, /*accept_std=*/true) ||
- ParseUnscopedName(state) ||
- (ParseOneCharToken(state, 'M') && ParseUnnamedTypeName(state))) {
- has_something = true;
- MaybeIncreaseNestLevel(state);
- continue;
- }
- MaybeCancelLastSeparator(state);
- if (has_something && ParseTemplateArgs(state)) {
- return ParsePrefix(state);
- } else {
- break;
- }
- }
- return true;
-}
-
-// <unqualified-name> ::= <operator-name> [<abi-tags>]
-// ::= <ctor-dtor-name> [<abi-tags>]
-// ::= <source-name> [<abi-tags>]
-// ::= <local-source-name> [<abi-tags>]
-// ::= <unnamed-type-name> [<abi-tags>]
-//
-// <local-source-name> is a GCC extension; see below.
-static bool ParseUnqualifiedName(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- if (ParseOperatorName(state, nullptr) || ParseCtorDtorName(state) ||
- ParseSourceName(state) || ParseLocalSourceName(state) ||
- ParseUnnamedTypeName(state)) {
- return ParseAbiTags(state);
- }
- return false;
-}
-
-// <abi-tags> ::= <abi-tag> [<abi-tags>]
-// <abi-tag> ::= B <source-name>
-static bool ParseAbiTags(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
-
- while (ParseOneCharToken(state, 'B')) {
- ParseState copy = state->parse_state;
- MaybeAppend(state, "[abi:");
-
- if (!ParseSourceName(state)) {
- state->parse_state = copy;
- return false;
- }
- MaybeAppend(state, "]");
- }
-
- return true;
-}
-
-// <source-name> ::= <positive length number> <identifier>
-static bool ParseSourceName(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- ParseState copy = state->parse_state;
- int length = -1;
- if (ParseNumber(state, &length) &&
- ParseIdentifier(state, static_cast<size_t>(length))) {
- return true;
- }
- state->parse_state = copy;
- return false;
-}
-
-// <local-source-name> ::= L <source-name> [<discriminator>]
-//
-// References:
-// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=31775
-// https://gcc.gnu.org/viewcvs?view=rev&revision=124467
-static bool ParseLocalSourceName(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- ParseState copy = state->parse_state;
- if (ParseOneCharToken(state, 'L') && ParseSourceName(state) &&
- Optional(ParseDiscriminator(state))) {
- return true;
- }
- state->parse_state = copy;
- return false;
-}
-
-// <unnamed-type-name> ::= Ut [<(nonnegative) number>] _
-// ::= <closure-type-name>
-// <closure-type-name> ::= Ul <lambda-sig> E [<(nonnegative) number>] _
-// <lambda-sig> ::= <(parameter) type>+
-static bool ParseUnnamedTypeName(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- ParseState copy = state->parse_state;
- // Type's 1-based index n is encoded as { "", n == 1; itoa(n-2), otherwise }.
- // Optionally parse the encoded value into 'which' and add 2 to get the index.
- int which = -1;
-
- // Unnamed type local to function or class.
- if (ParseTwoCharToken(state, "Ut") && Optional(ParseNumber(state, &which)) &&
- which <= std::numeric_limits<int>::max() - 2 && // Don't overflow.
- ParseOneCharToken(state, '_')) {
- MaybeAppend(state, "{unnamed type#");
- MaybeAppendDecimal(state, 2 + which);
- MaybeAppend(state, "}");
- return true;
- }
- state->parse_state = copy;
-
- // Closure type.
- which = -1;
- if (ParseTwoCharToken(state, "Ul") && DisableAppend(state) &&
- OneOrMore(ParseType, state) && RestoreAppend(state, copy.append) &&
- ParseOneCharToken(state, 'E') && Optional(ParseNumber(state, &which)) &&
- which <= std::numeric_limits<int>::max() - 2 && // Don't overflow.
- ParseOneCharToken(state, '_')) {
- MaybeAppend(state, "{lambda()#");
- MaybeAppendDecimal(state, 2 + which);
- MaybeAppend(state, "}");
- return true;
- }
- state->parse_state = copy;
-
- return false;
-}
-
-// <number> ::= [n] <non-negative decimal integer>
-// If "number_out" is non-null, then *number_out is set to the value of the
-// parsed number on success.
-static bool ParseNumber(State *state, int *number_out) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- bool negative = false;
- if (ParseOneCharToken(state, 'n')) {
- negative = true;
- }
- const char *p = RemainingInput(state);
- uint64_t number = 0;
- for (; *p != '\0'; ++p) {
- if (IsDigit(*p)) {
- number = number * 10 + static_cast<uint64_t>(*p - '0');
- } else {
- break;
- }
- }
- // Apply the sign with uint64_t arithmetic so overflows aren't UB. Gives
- // "incorrect" results for out-of-range inputs, but negative values only
- // appear for literals, which aren't printed.
- if (negative) {
- number = ~number + 1;
- }
- if (p != RemainingInput(state)) { // Conversion succeeded.
- state->parse_state.mangled_idx += p - RemainingInput(state);
- if (number_out != nullptr) {
- // Note: possibly truncate "number".
- *number_out = static_cast<int>(number);
- }
- return true;
- }
- return false;
-}
-
-// Floating-point literals are encoded using a fixed-length lowercase
-// hexadecimal string.
-static bool ParseFloatNumber(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- const char *p = RemainingInput(state);
- for (; *p != '\0'; ++p) {
- if (!IsDigit(*p) && !(*p >= 'a' && *p <= 'f')) {
- break;
- }
- }
- if (p != RemainingInput(state)) { // Conversion succeeded.
- state->parse_state.mangled_idx += p - RemainingInput(state);
- return true;
- }
- return false;
-}
-
-// The <seq-id> is a sequence number in base 36,
-// using digits and upper case letters
-static bool ParseSeqId(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- const char *p = RemainingInput(state);
- for (; *p != '\0'; ++p) {
- if (!IsDigit(*p) && !(*p >= 'A' && *p <= 'Z')) {
- break;
- }
- }
- if (p != RemainingInput(state)) { // Conversion succeeded.
- state->parse_state.mangled_idx += p - RemainingInput(state);
- return true;
- }
- return false;
-}
-
-// <identifier> ::= <unqualified source code identifier> (of given length)
-static bool ParseIdentifier(State *state, size_t length) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- if (!AtLeastNumCharsRemaining(RemainingInput(state), length)) {
- return false;
- }
- if (IdentifierIsAnonymousNamespace(state, length)) {
- MaybeAppend(state, "(anonymous namespace)");
- } else {
- MaybeAppendWithLength(state, RemainingInput(state), length);
- }
- state->parse_state.mangled_idx += length;
- return true;
-}
-
-// <operator-name> ::= nw, and other two letters cases
-// ::= cv <type> # (cast)
-// ::= v <digit> <source-name> # vendor extended operator
-static bool ParseOperatorName(State *state, int *arity) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- if (!AtLeastNumCharsRemaining(RemainingInput(state), 2)) {
- return false;
- }
- // First check with "cv" (cast) case.
- ParseState copy = state->parse_state;
- if (ParseTwoCharToken(state, "cv") && MaybeAppend(state, "operator ") &&
- EnterNestedName(state) && ParseType(state) &&
- LeaveNestedName(state, copy.nest_level)) {
- if (arity != nullptr) {
- *arity = 1;
- }
- return true;
- }
- state->parse_state = copy;
-
- // Then vendor extended operators.
- if (ParseOneCharToken(state, 'v') && ParseDigit(state, arity) &&
- ParseSourceName(state)) {
- return true;
- }
- state->parse_state = copy;
-
- // Other operator names should start with a lower alphabet followed
- // by a lower/upper alphabet.
- if (!(IsLower(RemainingInput(state)[0]) &&
- IsAlpha(RemainingInput(state)[1]))) {
- return false;
- }
- // We may want to perform a binary search if we really need speed.
- const AbbrevPair *p;
- for (p = kOperatorList; p->abbrev != nullptr; ++p) {
- if (RemainingInput(state)[0] == p->abbrev[0] &&
- RemainingInput(state)[1] == p->abbrev[1]) {
- if (arity != nullptr) {
- *arity = p->arity;
- }
- MaybeAppend(state, "operator");
- if (IsLower(*p->real_name)) { // new, delete, etc.
- MaybeAppend(state, " ");
- }
- MaybeAppend(state, p->real_name);
- state->parse_state.mangled_idx += 2;
- return true;
- }
- }
- return false;
-}
-
-// <special-name> ::= TV <type>
-// ::= TT <type>
-// ::= TI <type>
-// ::= TS <type>
-// ::= TH <type> # thread-local
-// ::= Tc <call-offset> <call-offset> <(base) encoding>
-// ::= GV <(object) name>
-// ::= T <call-offset> <(base) encoding>
-// G++ extensions:
-// ::= TC <type> <(offset) number> _ <(base) type>
-// ::= TF <type>
-// ::= TJ <type>
-// ::= GR <name>
-// ::= GA <encoding>
-// ::= Th <call-offset> <(base) encoding>
-// ::= Tv <call-offset> <(base) encoding>
-//
-// Note: we don't care much about them since they don't appear in
-// stack traces. The are special data.
-static bool ParseSpecialName(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- ParseState copy = state->parse_state;
- if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "VTISH") &&
- ParseType(state)) {
- return true;
- }
- state->parse_state = copy;
-
- if (ParseTwoCharToken(state, "Tc") && ParseCallOffset(state) &&
- ParseCallOffset(state) && ParseEncoding(state)) {
- return true;
- }
- state->parse_state = copy;
-
- if (ParseTwoCharToken(state, "GV") && ParseName(state)) {
- return true;
- }
- state->parse_state = copy;
-
- if (ParseOneCharToken(state, 'T') && ParseCallOffset(state) &&
- ParseEncoding(state)) {
- return true;
- }
- state->parse_state = copy;
-
- // G++ extensions
- if (ParseTwoCharToken(state, "TC") && ParseType(state) &&
- ParseNumber(state, nullptr) && ParseOneCharToken(state, '_') &&
- DisableAppend(state) && ParseType(state)) {
- RestoreAppend(state, copy.append);
- return true;
- }
- state->parse_state = copy;
-
- if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "FJ") &&
- ParseType(state)) {
- return true;
- }
- state->parse_state = copy;
-
- if (ParseTwoCharToken(state, "GR") && ParseName(state)) {
- return true;
- }
- state->parse_state = copy;
-
- if (ParseTwoCharToken(state, "GA") && ParseEncoding(state)) {
- return true;
- }
- state->parse_state = copy;
-
- if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "hv") &&
- ParseCallOffset(state) && ParseEncoding(state)) {
- return true;
- }
- state->parse_state = copy;
- return false;
-}
-
-// <call-offset> ::= h <nv-offset> _
-// ::= v <v-offset> _
-static bool ParseCallOffset(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- ParseState copy = state->parse_state;
- if (ParseOneCharToken(state, 'h') && ParseNVOffset(state) &&
- ParseOneCharToken(state, '_')) {
- return true;
- }
- state->parse_state = copy;
-
- if (ParseOneCharToken(state, 'v') && ParseVOffset(state) &&
- ParseOneCharToken(state, '_')) {
- return true;
- }
- state->parse_state = copy;
-
- return false;
-}
-
-// <nv-offset> ::= <(offset) number>
-static bool ParseNVOffset(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- return ParseNumber(state, nullptr);
-}
-
-// <v-offset> ::= <(offset) number> _ <(virtual offset) number>
-static bool ParseVOffset(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- ParseState copy = state->parse_state;
- if (ParseNumber(state, nullptr) && ParseOneCharToken(state, '_') &&
- ParseNumber(state, nullptr)) {
- return true;
- }
- state->parse_state = copy;
- return false;
-}
-
-// <ctor-dtor-name> ::= C1 | C2 | C3 | CI1 <base-class-type> | CI2
-// <base-class-type>
-// ::= D0 | D1 | D2
-// # GCC extensions: "unified" constructor/destructor. See
-// #
-// https://github.com/gcc-mirror/gcc/blob/7ad17b583c3643bd4557f29b8391ca7ef08391f5/gcc/cp/mangle.c#L1847
-// ::= C4 | D4
-static bool ParseCtorDtorName(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- ParseState copy = state->parse_state;
- if (ParseOneCharToken(state, 'C')) {
- if (ParseCharClass(state, "1234")) {
- const char *const prev_name =
- state->out + state->parse_state.prev_name_idx;
- MaybeAppendWithLength(state, prev_name,
- state->parse_state.prev_name_length);
- return true;
- } else if (ParseOneCharToken(state, 'I') && ParseCharClass(state, "12") &&
- ParseClassEnumType(state)) {
- return true;
- }
- }
- state->parse_state = copy;
-
- if (ParseOneCharToken(state, 'D') && ParseCharClass(state, "0124")) {
- const char *const prev_name = state->out + state->parse_state.prev_name_idx;
- MaybeAppend(state, "~");
- MaybeAppendWithLength(state, prev_name,
- state->parse_state.prev_name_length);
- return true;
- }
- state->parse_state = copy;
- return false;
-}
-
-// <decltype> ::= Dt <expression> E # decltype of an id-expression or class
-// # member access (C++0x)
-// ::= DT <expression> E # decltype of an expression (C++0x)
-static bool ParseDecltype(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
-
- ParseState copy = state->parse_state;
- if (ParseOneCharToken(state, 'D') && ParseCharClass(state, "tT") &&
- ParseExpression(state) && ParseOneCharToken(state, 'E')) {
- return true;
- }
- state->parse_state = copy;
-
- return false;
-}
-
-// <type> ::= <CV-qualifiers> <type>
-// ::= P <type> # pointer-to
-// ::= R <type> # reference-to
-// ::= O <type> # rvalue reference-to (C++0x)
-// ::= C <type> # complex pair (C 2000)
-// ::= G <type> # imaginary (C 2000)
-// ::= U <source-name> <type> # vendor extended type qualifier
-// ::= <builtin-type>
-// ::= <function-type>
-// ::= <class-enum-type> # note: just an alias for <name>
-// ::= <array-type>
-// ::= <pointer-to-member-type>
-// ::= <template-template-param> <template-args>
-// ::= <template-param>
-// ::= <decltype>
-// ::= <substitution>
-// ::= Dp <type> # pack expansion of (C++0x)
-// ::= Dv <num-elems> _ # GNU vector extension
-//
-static bool ParseType(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- ParseState copy = state->parse_state;
-
- // We should check CV-qualifers, and PRGC things first.
- //
- // CV-qualifiers overlap with some operator names, but an operator name is not
- // valid as a type. To avoid an ambiguity that can lead to exponential time
- // complexity, refuse to backtrack the CV-qualifiers.
- //
- // _Z4aoeuIrMvvE
- // => _Z 4aoeuI rM v v E
- // aoeu<operator%=, void, void>
- // => _Z 4aoeuI r Mv v E
- // aoeu<void void::* restrict>
- //
- // By consuming the CV-qualifiers first, the former parse is disabled.
- if (ParseCVQualifiers(state)) {
- const bool result = ParseType(state);
- if (!result) state->parse_state = copy;
- return result;
- }
- state->parse_state = copy;
-
- // Similarly, these tag characters can overlap with other <name>s resulting in
- // two different parse prefixes that land on <template-args> in the same
- // place, such as "C3r1xI...". So, disable the "ctor-name = C3" parse by
- // refusing to backtrack the tag characters.
- if (ParseCharClass(state, "OPRCG")) {
- const bool result = ParseType(state);
- if (!result) state->parse_state = copy;
- return result;
- }
- state->parse_state = copy;
-
- if (ParseTwoCharToken(state, "Dp") && ParseType(state)) {
- return true;
- }
- state->parse_state = copy;
-
- if (ParseOneCharToken(state, 'U') && ParseSourceName(state) &&
- ParseType(state)) {
- return true;
- }
- state->parse_state = copy;
-
- if (ParseBuiltinType(state) || ParseFunctionType(state) ||
- ParseClassEnumType(state) || ParseArrayType(state) ||
- ParsePointerToMemberType(state) || ParseDecltype(state) ||
- // "std" on its own isn't a type.
- ParseSubstitution(state, /*accept_std=*/false)) {
- return true;
- }
-
- if (ParseTemplateTemplateParam(state) && ParseTemplateArgs(state)) {
- return true;
- }
- state->parse_state = copy;
-
- // Less greedy than <template-template-param> <template-args>.
- if (ParseTemplateParam(state)) {
- return true;
- }
-
- if (ParseTwoCharToken(state, "Dv") && ParseNumber(state, nullptr) &&
- ParseOneCharToken(state, '_')) {
- return true;
- }
- state->parse_state = copy;
-
- return false;
-}
-
-// <CV-qualifiers> ::= [r] [V] [K]
-// We don't allow empty <CV-qualifiers> to avoid infinite loop in
-// ParseType().
-static bool ParseCVQualifiers(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- int num_cv_qualifiers = 0;
- num_cv_qualifiers += ParseOneCharToken(state, 'r');
- num_cv_qualifiers += ParseOneCharToken(state, 'V');
- num_cv_qualifiers += ParseOneCharToken(state, 'K');
- return num_cv_qualifiers > 0;
-}
-
-// <builtin-type> ::= v, etc. # single-character builtin types
-// ::= u <source-name>
-// ::= Dd, etc. # two-character builtin types
-//
-// Not supported:
-// ::= DF <number> _ # _FloatN (N bits)
-//
-static bool ParseBuiltinType(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- const AbbrevPair *p;
- for (p = kBuiltinTypeList; p->abbrev != nullptr; ++p) {
- // Guaranteed only 1- or 2-character strings in kBuiltinTypeList.
- if (p->abbrev[1] == '\0') {
- if (ParseOneCharToken(state, p->abbrev[0])) {
- MaybeAppend(state, p->real_name);
- return true;
- }
- } else if (p->abbrev[2] == '\0' && ParseTwoCharToken(state, p->abbrev)) {
- MaybeAppend(state, p->real_name);
- return true;
- }
- }
-
- ParseState copy = state->parse_state;
- if (ParseOneCharToken(state, 'u') && ParseSourceName(state)) {
- return true;
- }
- state->parse_state = copy;
- return false;
-}
-
-// <exception-spec> ::= Do # non-throwing
-// exception-specification (e.g.,
-// noexcept, throw())
-// ::= DO <expression> E # computed (instantiation-dependent)
-// noexcept
-// ::= Dw <type>+ E # dynamic exception specification
-// with instantiation-dependent types
-static bool ParseExceptionSpec(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
-
- if (ParseTwoCharToken(state, "Do")) return true;
-
- ParseState copy = state->parse_state;
- if (ParseTwoCharToken(state, "DO") && ParseExpression(state) &&
- ParseOneCharToken(state, 'E')) {
- return true;
- }
- state->parse_state = copy;
- if (ParseTwoCharToken(state, "Dw") && OneOrMore(ParseType, state) &&
- ParseOneCharToken(state, 'E')) {
- return true;
- }
- state->parse_state = copy;
-
- return false;
-}
-
-// <function-type> ::= [exception-spec] F [Y] <bare-function-type> [O] E
-static bool ParseFunctionType(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- ParseState copy = state->parse_state;
- if (Optional(ParseExceptionSpec(state)) && ParseOneCharToken(state, 'F') &&
- Optional(ParseOneCharToken(state, 'Y')) && ParseBareFunctionType(state) &&
- Optional(ParseOneCharToken(state, 'O')) &&
- ParseOneCharToken(state, 'E')) {
- return true;
- }
- state->parse_state = copy;
- return false;
-}
-
-// <bare-function-type> ::= <(signature) type>+
-static bool ParseBareFunctionType(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- ParseState copy = state->parse_state;
- DisableAppend(state);
- if (OneOrMore(ParseType, state)) {
- RestoreAppend(state, copy.append);
- MaybeAppend(state, "()");
- return true;
- }
- state->parse_state = copy;
- return false;
-}
-
-// <class-enum-type> ::= <name>
-static bool ParseClassEnumType(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- return ParseName(state);
-}
-
-// <array-type> ::= A <(positive dimension) number> _ <(element) type>
-// ::= A [<(dimension) expression>] _ <(element) type>
-static bool ParseArrayType(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- ParseState copy = state->parse_state;
- if (ParseOneCharToken(state, 'A') && ParseNumber(state, nullptr) &&
- ParseOneCharToken(state, '_') && ParseType(state)) {
- return true;
- }
- state->parse_state = copy;
-
- if (ParseOneCharToken(state, 'A') && Optional(ParseExpression(state)) &&
- ParseOneCharToken(state, '_') && ParseType(state)) {
- return true;
- }
- state->parse_state = copy;
- return false;
-}
-
-// <pointer-to-member-type> ::= M <(class) type> <(member) type>
-static bool ParsePointerToMemberType(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- ParseState copy = state->parse_state;
- if (ParseOneCharToken(state, 'M') && ParseType(state) && ParseType(state)) {
- return true;
- }
- state->parse_state = copy;
- return false;
-}
-
-// <template-param> ::= T_
-// ::= T <parameter-2 non-negative number> _
-static bool ParseTemplateParam(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- if (ParseTwoCharToken(state, "T_")) {
- MaybeAppend(state, "?"); // We don't support template substitutions.
- return true;
- }
-
- ParseState copy = state->parse_state;
- if (ParseOneCharToken(state, 'T') && ParseNumber(state, nullptr) &&
- ParseOneCharToken(state, '_')) {
- MaybeAppend(state, "?"); // We don't support template substitutions.
- return true;
- }
- state->parse_state = copy;
- return false;
-}
-
-// <template-template-param> ::= <template-param>
-// ::= <substitution>
-static bool ParseTemplateTemplateParam(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- return (ParseTemplateParam(state) ||
- // "std" on its own isn't a template.
- ParseSubstitution(state, /*accept_std=*/false));
-}
-
-// <template-args> ::= I <template-arg>+ E
-static bool ParseTemplateArgs(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- ParseState copy = state->parse_state;
- DisableAppend(state);
- if (ParseOneCharToken(state, 'I') && OneOrMore(ParseTemplateArg, state) &&
- ParseOneCharToken(state, 'E')) {
- RestoreAppend(state, copy.append);
- MaybeAppend(state, "<>");
- return true;
- }
- state->parse_state = copy;
- return false;
-}
-
-// <template-arg> ::= <type>
-// ::= <expr-primary>
-// ::= J <template-arg>* E # argument pack
-// ::= X <expression> E
-static bool ParseTemplateArg(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- ParseState copy = state->parse_state;
- if (ParseOneCharToken(state, 'J') && ZeroOrMore(ParseTemplateArg, state) &&
- ParseOneCharToken(state, 'E')) {
- return true;
- }
- state->parse_state = copy;
-
- // There can be significant overlap between the following leading to
- // exponential backtracking:
- //
- // <expr-primary> ::= L <type> <expr-cast-value> E
- // e.g. L 2xxIvE 1 E
- // <type> ==> <local-source-name> <template-args>
- // e.g. L 2xx IvE
- //
- // This means parsing an entire <type> twice, and <type> can contain
- // <template-arg>, so this can generate exponential backtracking. There is
- // only overlap when the remaining input starts with "L <source-name>", so
- // parse all cases that can start this way jointly to share the common prefix.
- //
- // We have:
- //
- // <template-arg> ::= <type>
- // ::= <expr-primary>
- //
- // First, drop all the productions of <type> that must start with something
- // other than 'L'. All that's left is <class-enum-type>; inline it.
- //
- // <type> ::= <nested-name> # starts with 'N'
- // ::= <unscoped-name>
- // ::= <unscoped-template-name> <template-args>
- // ::= <local-name> # starts with 'Z'
- //
- // Drop and inline again:
- //
- // <type> ::= <unscoped-name>
- // ::= <unscoped-name> <template-args>
- // ::= <substitution> <template-args> # starts with 'S'
- //
- // Merge the first two, inline <unscoped-name>, drop last:
- //
- // <type> ::= <unqualified-name> [<template-args>]
- // ::= St <unqualified-name> [<template-args>] # starts with 'S'
- //
- // Drop and inline:
- //
- // <type> ::= <operator-name> [<template-args>] # starts with lowercase
- // ::= <ctor-dtor-name> [<template-args>] # starts with 'C' or 'D'
- // ::= <source-name> [<template-args>] # starts with digit
- // ::= <local-source-name> [<template-args>]
- // ::= <unnamed-type-name> [<template-args>] # starts with 'U'
- //
- // One more time:
- //
- // <type> ::= L <source-name> [<template-args>]
- //
- // Likewise with <expr-primary>:
- //
- // <expr-primary> ::= L <type> <expr-cast-value> E
- // ::= LZ <encoding> E # cannot overlap; drop
- // ::= L <mangled_name> E # cannot overlap; drop
- //
- // By similar reasoning as shown above, the only <type>s starting with
- // <source-name> are "<source-name> [<template-args>]". Inline this.
- //
- // <expr-primary> ::= L <source-name> [<template-args>] <expr-cast-value> E
- //
- // Now inline both of these into <template-arg>:
- //
- // <template-arg> ::= L <source-name> [<template-args>]
- // ::= L <source-name> [<template-args>] <expr-cast-value> E
- //
- // Merge them and we're done:
- // <template-arg>
- // ::= L <source-name> [<template-args>] [<expr-cast-value> E]
- if (ParseLocalSourceName(state) && Optional(ParseTemplateArgs(state))) {
- copy = state->parse_state;
- if (ParseExprCastValue(state) && ParseOneCharToken(state, 'E')) {
- return true;
- }
- state->parse_state = copy;
- return true;
- }
-
- // Now that the overlapping cases can't reach this code, we can safely call
- // both of these.
- if (ParseType(state) || ParseExprPrimary(state)) {
- return true;
- }
- state->parse_state = copy;
-
- if (ParseOneCharToken(state, 'X') && ParseExpression(state) &&
- ParseOneCharToken(state, 'E')) {
- return true;
- }
- state->parse_state = copy;
- return false;
-}
-
-// <unresolved-type> ::= <template-param> [<template-args>]
-// ::= <decltype>
-// ::= <substitution>
-static inline bool ParseUnresolvedType(State *state) {
- // No ComplexityGuard because we don't copy the state in this stack frame.
- return (ParseTemplateParam(state) && Optional(ParseTemplateArgs(state))) ||
- ParseDecltype(state) || ParseSubstitution(state, /*accept_std=*/false);
-}
-
-// <simple-id> ::= <source-name> [<template-args>]
-static inline bool ParseSimpleId(State *state) {
- // No ComplexityGuard because we don't copy the state in this stack frame.
-
- // Note: <simple-id> cannot be followed by a parameter pack; see comment in
- // ParseUnresolvedType.
- return ParseSourceName(state) && Optional(ParseTemplateArgs(state));
-}
-
-// <base-unresolved-name> ::= <source-name> [<template-args>]
-// ::= on <operator-name> [<template-args>]
-// ::= dn <destructor-name>
-static bool ParseBaseUnresolvedName(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
-
- if (ParseSimpleId(state)) {
- return true;
- }
-
- ParseState copy = state->parse_state;
- if (ParseTwoCharToken(state, "on") && ParseOperatorName(state, nullptr) &&
- Optional(ParseTemplateArgs(state))) {
- return true;
- }
- state->parse_state = copy;
-
- if (ParseTwoCharToken(state, "dn") &&
- (ParseUnresolvedType(state) || ParseSimpleId(state))) {
- return true;
- }
- state->parse_state = copy;
-
- return false;
-}
-
-// <unresolved-name> ::= [gs] <base-unresolved-name>
-// ::= sr <unresolved-type> <base-unresolved-name>
-// ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
-// <base-unresolved-name>
-// ::= [gs] sr <unresolved-qualifier-level>+ E
-// <base-unresolved-name>
-static bool ParseUnresolvedName(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
-
- ParseState copy = state->parse_state;
- if (Optional(ParseTwoCharToken(state, "gs")) &&
- ParseBaseUnresolvedName(state)) {
- return true;
- }
- state->parse_state = copy;
-
- if (ParseTwoCharToken(state, "sr") && ParseUnresolvedType(state) &&
- ParseBaseUnresolvedName(state)) {
- return true;
- }
- state->parse_state = copy;
-
- if (ParseTwoCharToken(state, "sr") && ParseOneCharToken(state, 'N') &&
- ParseUnresolvedType(state) &&
- OneOrMore(/* <unresolved-qualifier-level> ::= */ ParseSimpleId, state) &&
- ParseOneCharToken(state, 'E') && ParseBaseUnresolvedName(state)) {
- return true;
- }
- state->parse_state = copy;
-
- if (Optional(ParseTwoCharToken(state, "gs")) &&
- ParseTwoCharToken(state, "sr") &&
- OneOrMore(/* <unresolved-qualifier-level> ::= */ ParseSimpleId, state) &&
- ParseOneCharToken(state, 'E') && ParseBaseUnresolvedName(state)) {
- return true;
- }
- state->parse_state = copy;
-
- return false;
-}
-
-// <expression> ::= <1-ary operator-name> <expression>
-// ::= <2-ary operator-name> <expression> <expression>
-// ::= <3-ary operator-name> <expression> <expression> <expression>
-// ::= cl <expression>+ E
-// ::= cp <simple-id> <expression>* E # Clang-specific.
-// ::= cv <type> <expression> # type (expression)
-// ::= cv <type> _ <expression>* E # type (expr-list)
-// ::= st <type>
-// ::= <template-param>
-// ::= <function-param>
-// ::= <expr-primary>
-// ::= dt <expression> <unresolved-name> # expr.name
-// ::= pt <expression> <unresolved-name> # expr->name
-// ::= sp <expression> # argument pack expansion
-// ::= sr <type> <unqualified-name> <template-args>
-// ::= sr <type> <unqualified-name>
-// <function-param> ::= fp <(top-level) CV-qualifiers> _
-// ::= fp <(top-level) CV-qualifiers> <number> _
-// ::= fL <number> p <(top-level) CV-qualifiers> _
-// ::= fL <number> p <(top-level) CV-qualifiers> <number> _
-static bool ParseExpression(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- if (ParseTemplateParam(state) || ParseExprPrimary(state)) {
- return true;
- }
-
- ParseState copy = state->parse_state;
-
- // Object/function call expression.
- if (ParseTwoCharToken(state, "cl") && OneOrMore(ParseExpression, state) &&
- ParseOneCharToken(state, 'E')) {
- return true;
- }
- state->parse_state = copy;
-
- // Clang-specific "cp <simple-id> <expression>* E"
- // https://clang.llvm.org/doxygen/ItaniumMangle_8cpp_source.html#l04338
- if (ParseTwoCharToken(state, "cp") && ParseSimpleId(state) &&
- ZeroOrMore(ParseExpression, state) && ParseOneCharToken(state, 'E')) {
- return true;
- }
- state->parse_state = copy;
-
- // Function-param expression (level 0).
- if (ParseTwoCharToken(state, "fp") && Optional(ParseCVQualifiers(state)) &&
- Optional(ParseNumber(state, nullptr)) && ParseOneCharToken(state, '_')) {
- return true;
- }
- state->parse_state = copy;
-
- // Function-param expression (level 1+).
- if (ParseTwoCharToken(state, "fL") && Optional(ParseNumber(state, nullptr)) &&
- ParseOneCharToken(state, 'p') && Optional(ParseCVQualifiers(state)) &&
- Optional(ParseNumber(state, nullptr)) && ParseOneCharToken(state, '_')) {
- return true;
- }
- state->parse_state = copy;
-
- // Parse the conversion expressions jointly to avoid re-parsing the <type> in
- // their common prefix. Parsed as:
- // <expression> ::= cv <type> <conversion-args>
- // <conversion-args> ::= _ <expression>* E
- // ::= <expression>
- //
- // Also don't try ParseOperatorName after seeing "cv", since ParseOperatorName
- // also needs to accept "cv <type>" in other contexts.
- if (ParseTwoCharToken(state, "cv")) {
- if (ParseType(state)) {
- ParseState copy2 = state->parse_state;
- if (ParseOneCharToken(state, '_') && ZeroOrMore(ParseExpression, state) &&
- ParseOneCharToken(state, 'E')) {
- return true;
- }
- state->parse_state = copy2;
- if (ParseExpression(state)) {
- return true;
- }
- }
- } else {
- // Parse unary, binary, and ternary operator expressions jointly, taking
- // care not to re-parse subexpressions repeatedly. Parse like:
- // <expression> ::= <operator-name> <expression>
- // [<one-to-two-expressions>]
- // <one-to-two-expressions> ::= <expression> [<expression>]
- int arity = -1;
- if (ParseOperatorName(state, &arity) &&
- arity > 0 && // 0 arity => disabled.
- (arity < 3 || ParseExpression(state)) &&
- (arity < 2 || ParseExpression(state)) &&
- (arity < 1 || ParseExpression(state))) {
- return true;
- }
- }
- state->parse_state = copy;
-
- // sizeof type
- if (ParseTwoCharToken(state, "st") && ParseType(state)) {
- return true;
- }
- state->parse_state = copy;
-
- // Object and pointer member access expressions.
- if ((ParseTwoCharToken(state, "dt") || ParseTwoCharToken(state, "pt")) &&
- ParseExpression(state) && ParseType(state)) {
- return true;
- }
- state->parse_state = copy;
-
- // Pointer-to-member access expressions. This parses the same as a binary
- // operator, but it's implemented separately because "ds" shouldn't be
- // accepted in other contexts that parse an operator name.
- if (ParseTwoCharToken(state, "ds") && ParseExpression(state) &&
- ParseExpression(state)) {
- return true;
- }
- state->parse_state = copy;
-
- // Parameter pack expansion
- if (ParseTwoCharToken(state, "sp") && ParseExpression(state)) {
- return true;
- }
- state->parse_state = copy;
-
- return ParseUnresolvedName(state);
-}
-
-// <expr-primary> ::= L <type> <(value) number> E
-// ::= L <type> <(value) float> E
-// ::= L <mangled-name> E
-// // A bug in g++'s C++ ABI version 2 (-fabi-version=2).
-// ::= LZ <encoding> E
-//
-// Warning, subtle: the "bug" LZ production above is ambiguous with the first
-// production where <type> starts with <local-name>, which can lead to
-// exponential backtracking in two scenarios:
-//
-// - When whatever follows the E in the <local-name> in the first production is
-// not a name, we backtrack the whole <encoding> and re-parse the whole thing.
-//
-// - When whatever follows the <local-name> in the first production is not a
-// number and this <expr-primary> may be followed by a name, we backtrack the
-// <name> and re-parse it.
-//
-// Moreover this ambiguity isn't always resolved -- for example, the following
-// has two different parses:
-//
-// _ZaaILZ4aoeuE1x1EvE
-// => operator&&<aoeu, x, E, void>
-// => operator&&<(aoeu::x)(1), void>
-//
-// To resolve this, we just do what GCC's demangler does, and refuse to parse
-// casts to <local-name> types.
-static bool ParseExprPrimary(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- ParseState copy = state->parse_state;
-
- // The "LZ" special case: if we see LZ, we commit to accept "LZ <encoding> E"
- // or fail, no backtracking.
- if (ParseTwoCharToken(state, "LZ")) {
- if (ParseEncoding(state) && ParseOneCharToken(state, 'E')) {
- return true;
- }
-
- state->parse_state = copy;
- return false;
- }
-
- // The merged cast production.
- if (ParseOneCharToken(state, 'L') && ParseType(state) &&
- ParseExprCastValue(state)) {
- return true;
- }
- state->parse_state = copy;
-
- if (ParseOneCharToken(state, 'L') && ParseMangledName(state) &&
- ParseOneCharToken(state, 'E')) {
- return true;
- }
- state->parse_state = copy;
-
- return false;
-}
-
-// <number> or <float>, followed by 'E', as described above ParseExprPrimary.
-static bool ParseExprCastValue(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- // We have to be able to backtrack after accepting a number because we could
- // have e.g. "7fffE", which will accept "7" as a number but then fail to find
- // the 'E'.
- ParseState copy = state->parse_state;
- if (ParseNumber(state, nullptr) && ParseOneCharToken(state, 'E')) {
- return true;
- }
- state->parse_state = copy;
-
- if (ParseFloatNumber(state) && ParseOneCharToken(state, 'E')) {
- return true;
- }
- state->parse_state = copy;
-
- return false;
-}
-
-// <local-name> ::= Z <(function) encoding> E <(entity) name> [<discriminator>]
-// ::= Z <(function) encoding> E s [<discriminator>]
-//
-// Parsing a common prefix of these two productions together avoids an
-// exponential blowup of backtracking. Parse like:
-// <local-name> := Z <encoding> E <local-name-suffix>
-// <local-name-suffix> ::= s [<discriminator>]
-// ::= <name> [<discriminator>]
-
-static bool ParseLocalNameSuffix(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
-
- if (MaybeAppend(state, "::") && ParseName(state) &&
- Optional(ParseDiscriminator(state))) {
- return true;
- }
-
- // Since we're not going to overwrite the above "::" by re-parsing the
- // <encoding> (whose trailing '\0' byte was in the byte now holding the
- // first ':'), we have to rollback the "::" if the <name> parse failed.
- if (state->parse_state.append) {
- state->out[state->parse_state.out_cur_idx - 2] = '\0';
- }
-
- return ParseOneCharToken(state, 's') && Optional(ParseDiscriminator(state));
-}
-
-static bool ParseLocalName(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- ParseState copy = state->parse_state;
- if (ParseOneCharToken(state, 'Z') && ParseEncoding(state) &&
- ParseOneCharToken(state, 'E') && ParseLocalNameSuffix(state)) {
- return true;
- }
- state->parse_state = copy;
- return false;
-}
-
-// <discriminator> := _ <(non-negative) number>
-static bool ParseDiscriminator(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- ParseState copy = state->parse_state;
- if (ParseOneCharToken(state, '_') && ParseNumber(state, nullptr)) {
- return true;
- }
- state->parse_state = copy;
- return false;
-}
-
-// <substitution> ::= S_
-// ::= S <seq-id> _
-// ::= St, etc.
-//
-// "St" is special in that it's not valid as a standalone name, and it *is*
-// allowed to precede a name without being wrapped in "N...E". This means that
-// if we accept it on its own, we can accept "St1a" and try to parse
-// template-args, then fail and backtrack, accept "St" on its own, then "1a" as
-// an unqualified name and re-parse the same template-args. To block this
-// exponential backtracking, we disable it with 'accept_std=false' in
-// problematic contexts.
-static bool ParseSubstitution(State *state, bool accept_std) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- if (ParseTwoCharToken(state, "S_")) {
- MaybeAppend(state, "?"); // We don't support substitutions.
- return true;
- }
-
- ParseState copy = state->parse_state;
- if (ParseOneCharToken(state, 'S') && ParseSeqId(state) &&
- ParseOneCharToken(state, '_')) {
- MaybeAppend(state, "?"); // We don't support substitutions.
- return true;
- }
- state->parse_state = copy;
-
- // Expand abbreviations like "St" => "std".
- if (ParseOneCharToken(state, 'S')) {
- const AbbrevPair *p;
- for (p = kSubstitutionList; p->abbrev != nullptr; ++p) {
- if (RemainingInput(state)[0] == p->abbrev[1] &&
- (accept_std || p->abbrev[1] != 't')) {
- MaybeAppend(state, "std");
- if (p->real_name[0] != '\0') {
- MaybeAppend(state, "::");
- MaybeAppend(state, p->real_name);
- }
- ++state->parse_state.mangled_idx;
- return true;
- }
- }
- }
- state->parse_state = copy;
- return false;
-}
-
-// Parse <mangled-name>, optionally followed by either a function-clone suffix
-// or version suffix. Returns true only if all of "mangled_cur" was consumed.
-static bool ParseTopLevelMangledName(State *state) {
- ComplexityGuard guard(state);
- if (guard.IsTooComplex()) return false;
- if (ParseMangledName(state)) {
- if (RemainingInput(state)[0] != '\0') {
- // Drop trailing function clone suffix, if any.
- if (IsFunctionCloneSuffix(RemainingInput(state))) {
- return true;
- }
- // Append trailing version suffix if any.
- // ex. _Z3foo@@GLIBCXX_3.4
- if (RemainingInput(state)[0] == '@') {
- MaybeAppend(state, RemainingInput(state));
- return true;
- }
- return false; // Unconsumed suffix.
- }
- return true;
- }
- return false;
-}
-
-static bool Overflowed(const State *state) {
- return state->parse_state.out_cur_idx >= state->out_end_idx;
-}
-
-// The demangler entry point.
-bool Demangle(const char* mangled, char* out, size_t out_size) {
- State state;
- InitState(&state, mangled, out, out_size);
- return ParseTopLevelMangledName(&state) && !Overflowed(&state) &&
- state.parse_state.out_cur_idx > 0;
-}
-
-} // namespace debugging_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/debugging/internal/demangle.h b/third_party/abseil-cpp/absl/debugging/internal/demangle.h
deleted file mode 100644
index e1f1569..0000000
--- a/third_party/abseil-cpp/absl/debugging/internal/demangle.h
+++ /dev/null
@@ -1,71 +0,0 @@
-// Copyright 2018 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.
-
-// An async-signal-safe and thread-safe demangler for Itanium C++ ABI
-// (aka G++ V3 ABI).
-//
-// The demangler is implemented to be used in async signal handlers to
-// symbolize stack traces. We cannot use libstdc++'s
-// abi::__cxa_demangle() in such signal handlers since it's not async
-// signal safe (it uses malloc() internally).
-//
-// Note that this demangler doesn't support full demangling. More
-// specifically, it doesn't print types of function parameters and
-// types of template arguments. It just skips them. However, it's
-// still very useful to extract basic information such as class,
-// function, constructor, destructor, and operator names.
-//
-// See the implementation note in demangle.cc if you are interested.
-//
-// Example:
-//
-// | Mangled Name | The Demangler | abi::__cxa_demangle()
-// |---------------|---------------|-----------------------
-// | _Z1fv | f() | f()
-// | _Z1fi | f() | f(int)
-// | _Z3foo3bar | foo() | foo(bar)
-// | _Z1fIiEvi | f<>() | void f<int>(int)
-// | _ZN1N1fE | N::f | N::f
-// | _ZN3Foo3BarEv | Foo::Bar() | Foo::Bar()
-// | _Zrm1XS_" | operator%() | operator%(X, X)
-// | _ZN3FooC1Ev | Foo::Foo() | Foo::Foo()
-// | _Z1fSs | f() | f(std::basic_string<char,
-// | | | std::char_traits<char>,
-// | | | std::allocator<char> >)
-//
-// See the unit test for more examples.
-//
-// Note: we might want to write demanglers for ABIs other than Itanium
-// C++ ABI in the future.
-//
-
-#ifndef ABSL_DEBUGGING_INTERNAL_DEMANGLE_H_
-#define ABSL_DEBUGGING_INTERNAL_DEMANGLE_H_
-
-#include "absl/base/config.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace debugging_internal {
-
-// Demangle `mangled`. On success, return true and write the
-// demangled symbol name to `out`. Otherwise, return false.
-// `out` is modified even if demangling is unsuccessful.
-bool Demangle(const char* mangled, char* out, size_t out_size);
-
-} // namespace debugging_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_DEBUGGING_INTERNAL_DEMANGLE_H_
diff --git a/third_party/abseil-cpp/absl/debugging/internal/demangle_test.cc b/third_party/abseil-cpp/absl/debugging/internal/demangle_test.cc
deleted file mode 100644
index 8463a2b..0000000
--- a/third_party/abseil-cpp/absl/debugging/internal/demangle_test.cc
+++ /dev/null
@@ -1,243 +0,0 @@
-// Copyright 2018 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/debugging/internal/demangle.h"
-
-#include <cstdlib>
-#include <string>
-
-#include "gtest/gtest.h"
-#include "absl/base/config.h"
-#include "absl/base/internal/raw_logging.h"
-#include "absl/debugging/internal/stack_consumption.h"
-#include "absl/memory/memory.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace debugging_internal {
-namespace {
-
-// A wrapper function for Demangle() to make the unit test simple.
-static const char *DemangleIt(const char * const mangled) {
- static char demangled[4096];
- if (Demangle(mangled, demangled, sizeof(demangled))) {
- return demangled;
- } else {
- return mangled;
- }
-}
-
-// Test corner cases of bounary conditions.
-TEST(Demangle, CornerCases) {
- char tmp[10];
- EXPECT_TRUE(Demangle("_Z6foobarv", tmp, sizeof(tmp)));
- // sizeof("foobar()") == 9
- EXPECT_STREQ("foobar()", tmp);
- EXPECT_TRUE(Demangle("_Z6foobarv", tmp, 9));
- EXPECT_STREQ("foobar()", tmp);
- EXPECT_FALSE(Demangle("_Z6foobarv", tmp, 8)); // Not enough.
- EXPECT_FALSE(Demangle("_Z6foobarv", tmp, 1));
- EXPECT_FALSE(Demangle("_Z6foobarv", tmp, 0));
- EXPECT_FALSE(Demangle("_Z6foobarv", nullptr, 0)); // Should not cause SEGV.
- EXPECT_FALSE(Demangle("_Z1000000", tmp, 9));
-}
-
-// Test handling of functions suffixed with .clone.N, which is used
-// by GCC 4.5.x (and our locally-modified version of GCC 4.4.x), and
-// .constprop.N and .isra.N, which are used by GCC 4.6.x. These
-// suffixes are used to indicate functions which have been cloned
-// during optimization. We ignore these suffixes.
-TEST(Demangle, Clones) {
- char tmp[20];
- EXPECT_TRUE(Demangle("_ZL3Foov", tmp, sizeof(tmp)));
- EXPECT_STREQ("Foo()", tmp);
- EXPECT_TRUE(Demangle("_ZL3Foov.clone.3", tmp, sizeof(tmp)));
- EXPECT_STREQ("Foo()", tmp);
- EXPECT_TRUE(Demangle("_ZL3Foov.constprop.80", tmp, sizeof(tmp)));
- EXPECT_STREQ("Foo()", tmp);
- EXPECT_TRUE(Demangle("_ZL3Foov.isra.18", tmp, sizeof(tmp)));
- EXPECT_STREQ("Foo()", tmp);
- EXPECT_TRUE(Demangle("_ZL3Foov.isra.2.constprop.18", tmp, sizeof(tmp)));
- EXPECT_STREQ("Foo()", tmp);
- // Demangle suffixes produced by -funique-internal-linkage-names.
- EXPECT_TRUE(Demangle("_ZL3Foov.__uniq.12345", tmp, sizeof(tmp)));
- EXPECT_STREQ("Foo()", tmp);
- EXPECT_TRUE(Demangle("_ZL3Foov.__uniq.12345.isra.2.constprop.18", tmp,
- sizeof(tmp)));
- EXPECT_STREQ("Foo()", tmp);
- // Suffixes without the number should also demangle.
- EXPECT_TRUE(Demangle("_ZL3Foov.clo", tmp, sizeof(tmp)));
- EXPECT_STREQ("Foo()", tmp);
- // Suffixes with just the number should also demangle.
- EXPECT_TRUE(Demangle("_ZL3Foov.123", tmp, sizeof(tmp)));
- EXPECT_STREQ("Foo()", tmp);
- // (.clone. followed by non-number), should also demangle.
- EXPECT_TRUE(Demangle("_ZL3Foov.clone.foo", tmp, sizeof(tmp)));
- EXPECT_STREQ("Foo()", tmp);
- // (.clone. followed by multiple numbers), should also demangle.
- EXPECT_TRUE(Demangle("_ZL3Foov.clone.123.456", tmp, sizeof(tmp)));
- EXPECT_STREQ("Foo()", tmp);
- // (a long valid suffix), should demangle.
- EXPECT_TRUE(Demangle("_ZL3Foov.part.9.165493.constprop.775.31805", tmp,
- sizeof(tmp)));
- EXPECT_STREQ("Foo()", tmp);
- // Invalid (. without anything else), should not demangle.
- EXPECT_FALSE(Demangle("_ZL3Foov.", tmp, sizeof(tmp)));
- // Invalid (. with mix of alpha and digits), should not demangle.
- EXPECT_FALSE(Demangle("_ZL3Foov.abc123", tmp, sizeof(tmp)));
- // Invalid (.clone. not followed by number), should not demangle.
- EXPECT_FALSE(Demangle("_ZL3Foov.clone.", tmp, sizeof(tmp)));
- // Invalid (.constprop. not followed by number), should not demangle.
- EXPECT_FALSE(Demangle("_ZL3Foov.isra.2.constprop.", tmp, sizeof(tmp)));
-}
-
-// Test the GNU abi_tag extension.
-TEST(Demangle, AbiTags) {
- char tmp[80];
-
- // Mangled name generated via:
- // struct [[gnu::abi_tag("abc")]] A{};
- // A a;
- EXPECT_TRUE(Demangle("_Z1aB3abc", tmp, sizeof(tmp)));
- EXPECT_STREQ("a[abi:abc]", tmp);
-
- // Mangled name generated via:
- // struct B {
- // B [[gnu::abi_tag("xyz")]] (){};
- // };
- // B b;
- EXPECT_TRUE(Demangle("_ZN1BC2B3xyzEv", tmp, sizeof(tmp)));
- EXPECT_STREQ("B::B[abi:xyz]()", tmp);
-
- // Mangled name generated via:
- // [[gnu::abi_tag("foo", "bar")]] void C() {}
- EXPECT_TRUE(Demangle("_Z1CB3barB3foov", tmp, sizeof(tmp)));
- EXPECT_STREQ("C[abi:bar][abi:foo]()", tmp);
-}
-
-// Tests that verify that Demangle footprint is within some limit.
-// They are not to be run under sanitizers as the sanitizers increase
-// stack consumption by about 4x.
-#if defined(ABSL_INTERNAL_HAVE_DEBUGGING_STACK_CONSUMPTION) && \
- !defined(ABSL_HAVE_ADDRESS_SANITIZER) && \
- !defined(ABSL_HAVE_MEMORY_SANITIZER) && \
- !defined(ABSL_HAVE_THREAD_SANITIZER)
-
-static const char *g_mangled;
-static char g_demangle_buffer[4096];
-static char *g_demangle_result;
-
-static void DemangleSignalHandler(int signo) {
- if (Demangle(g_mangled, g_demangle_buffer, sizeof(g_demangle_buffer))) {
- g_demangle_result = g_demangle_buffer;
- } else {
- g_demangle_result = nullptr;
- }
-}
-
-// Call Demangle and figure out the stack footprint of this call.
-static const char *DemangleStackConsumption(const char *mangled,
- int *stack_consumed) {
- g_mangled = mangled;
- *stack_consumed = GetSignalHandlerStackConsumption(DemangleSignalHandler);
- ABSL_RAW_LOG(INFO, "Stack consumption of Demangle: %d", *stack_consumed);
- return g_demangle_result;
-}
-
-// Demangle stack consumption should be within 8kB for simple mangled names
-// with some level of nesting. With alternate signal stack we have 64K,
-// but some signal handlers run on thread stack, and could have arbitrarily
-// little space left (so we don't want to make this number too large).
-const int kStackConsumptionUpperLimit = 8192;
-
-// Returns a mangled name nested to the given depth.
-static std::string NestedMangledName(int depth) {
- std::string mangled_name = "_Z1a";
- if (depth > 0) {
- mangled_name += "IXL";
- mangled_name += NestedMangledName(depth - 1);
- mangled_name += "EEE";
- }
- return mangled_name;
-}
-
-TEST(Demangle, DemangleStackConsumption) {
- // Measure stack consumption of Demangle for nested mangled names of varying
- // depth. Since Demangle is implemented as a recursive descent parser,
- // stack consumption will grow as the nesting depth increases. By measuring
- // the stack consumption for increasing depths, we can see the growing
- // impact of any stack-saving changes made to the code for Demangle.
- int stack_consumed = 0;
-
- const char *demangled =
- DemangleStackConsumption("_Z6foobarv", &stack_consumed);
- EXPECT_STREQ("foobar()", demangled);
- EXPECT_GT(stack_consumed, 0);
- EXPECT_LT(stack_consumed, kStackConsumptionUpperLimit);
-
- const std::string nested_mangled_name0 = NestedMangledName(0);
- demangled = DemangleStackConsumption(nested_mangled_name0.c_str(),
- &stack_consumed);
- EXPECT_STREQ("a", demangled);
- EXPECT_GT(stack_consumed, 0);
- EXPECT_LT(stack_consumed, kStackConsumptionUpperLimit);
-
- const std::string nested_mangled_name1 = NestedMangledName(1);
- demangled = DemangleStackConsumption(nested_mangled_name1.c_str(),
- &stack_consumed);
- EXPECT_STREQ("a<>", demangled);
- EXPECT_GT(stack_consumed, 0);
- EXPECT_LT(stack_consumed, kStackConsumptionUpperLimit);
-
- const std::string nested_mangled_name2 = NestedMangledName(2);
- demangled = DemangleStackConsumption(nested_mangled_name2.c_str(),
- &stack_consumed);
- EXPECT_STREQ("a<>", demangled);
- EXPECT_GT(stack_consumed, 0);
- EXPECT_LT(stack_consumed, kStackConsumptionUpperLimit);
-
- const std::string nested_mangled_name3 = NestedMangledName(3);
- demangled = DemangleStackConsumption(nested_mangled_name3.c_str(),
- &stack_consumed);
- EXPECT_STREQ("a<>", demangled);
- EXPECT_GT(stack_consumed, 0);
- EXPECT_LT(stack_consumed, kStackConsumptionUpperLimit);
-}
-
-#endif // Stack consumption tests
-
-static void TestOnInput(const char* input) {
- static const int kOutSize = 1048576;
- auto out = absl::make_unique<char[]>(kOutSize);
- Demangle(input, out.get(), kOutSize);
-}
-
-TEST(DemangleRegression, NegativeLength) {
- TestOnInput("_ZZn4");
-}
-
-TEST(DemangleRegression, DeeplyNestedArrayType) {
- const int depth = 100000;
- std::string data = "_ZStI";
- data.reserve(data.size() + 3 * depth + 1);
- for (int i = 0; i < depth; i++) {
- data += "A1_";
- }
- TestOnInput(data.c_str());
-}
-
-} // namespace
-} // namespace debugging_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/debugging/internal/elf_mem_image.cc b/third_party/abseil-cpp/absl/debugging/internal/elf_mem_image.cc
deleted file mode 100644
index 42dcd3c..0000000
--- a/third_party/abseil-cpp/absl/debugging/internal/elf_mem_image.cc
+++ /dev/null
@@ -1,386 +0,0 @@
-// Copyright 2017 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.
-
-// Allow dynamic symbol lookup in an in-memory Elf image.
-//
-
-#include "absl/debugging/internal/elf_mem_image.h"
-
-#ifdef ABSL_HAVE_ELF_MEM_IMAGE // defined in elf_mem_image.h
-
-#include <string.h>
-#include <cassert>
-#include <cstddef>
-#include "absl/base/config.h"
-#include "absl/base/internal/raw_logging.h"
-
-// From binutils/include/elf/common.h (this doesn't appear to be documented
-// anywhere else).
-//
-// /* This flag appears in a Versym structure. It means that the symbol
-// is hidden, and is only visible with an explicit version number.
-// This is a GNU extension. */
-// #define VERSYM_HIDDEN 0x8000
-//
-// /* This is the mask for the rest of the Versym information. */
-// #define VERSYM_VERSION 0x7fff
-
-#define VERSYM_VERSION 0x7fff
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace debugging_internal {
-
-namespace {
-
-#if __SIZEOF_POINTER__ == 4
-const int kElfClass = ELFCLASS32;
-int ElfBind(const ElfW(Sym) *symbol) { return ELF32_ST_BIND(symbol->st_info); }
-int ElfType(const ElfW(Sym) *symbol) { return ELF32_ST_TYPE(symbol->st_info); }
-#elif __SIZEOF_POINTER__ == 8
-const int kElfClass = ELFCLASS64;
-int ElfBind(const ElfW(Sym) *symbol) { return ELF64_ST_BIND(symbol->st_info); }
-int ElfType(const ElfW(Sym) *symbol) { return ELF64_ST_TYPE(symbol->st_info); }
-#else
-const int kElfClass = -1;
-int ElfBind(const ElfW(Sym) *) {
- ABSL_RAW_LOG(FATAL, "Unexpected word size");
- return 0;
-}
-int ElfType(const ElfW(Sym) *) {
- ABSL_RAW_LOG(FATAL, "Unexpected word size");
- return 0;
-}
-#endif
-
-// Extract an element from one of the ELF tables, cast it to desired type.
-// This is just a simple arithmetic and a glorified cast.
-// Callers are responsible for bounds checking.
-template <typename T>
-const T *GetTableElement(const ElfW(Ehdr) * ehdr, ElfW(Off) table_offset,
- ElfW(Word) element_size, size_t index) {
- return reinterpret_cast<const T*>(reinterpret_cast<const char *>(ehdr)
- + table_offset
- + index * element_size);
-}
-
-} // namespace
-
-// The value of this variable doesn't matter; it's used only for its
-// unique address.
-const int ElfMemImage::kInvalidBaseSentinel = 0;
-
-ElfMemImage::ElfMemImage(const void *base) {
- ABSL_RAW_CHECK(base != kInvalidBase, "bad pointer");
- Init(base);
-}
-
-int ElfMemImage::GetNumSymbols() const {
- if (!hash_) {
- return 0;
- }
- // See http://www.caldera.com/developers/gabi/latest/ch5.dynamic.html#hash
- return static_cast<int>(hash_[1]);
-}
-
-const ElfW(Sym) *ElfMemImage::GetDynsym(int index) const {
- ABSL_RAW_CHECK(index < GetNumSymbols(), "index out of range");
- return dynsym_ + index;
-}
-
-const ElfW(Versym) *ElfMemImage::GetVersym(int index) const {
- ABSL_RAW_CHECK(index < GetNumSymbols(), "index out of range");
- return versym_ + index;
-}
-
-const ElfW(Phdr) *ElfMemImage::GetPhdr(int index) const {
- ABSL_RAW_CHECK(index >= 0 && index < ehdr_->e_phnum, "index out of range");
- return GetTableElement<ElfW(Phdr)>(ehdr_, ehdr_->e_phoff, ehdr_->e_phentsize,
- static_cast<size_t>(index));
-}
-
-const char *ElfMemImage::GetDynstr(ElfW(Word) offset) const {
- ABSL_RAW_CHECK(offset < strsize_, "offset out of range");
- return dynstr_ + offset;
-}
-
-const void *ElfMemImage::GetSymAddr(const ElfW(Sym) *sym) const {
- if (sym->st_shndx == SHN_UNDEF || sym->st_shndx >= SHN_LORESERVE) {
- // Symbol corresponds to "special" (e.g. SHN_ABS) section.
- return reinterpret_cast<const void *>(sym->st_value);
- }
- ABSL_RAW_CHECK(link_base_ < sym->st_value, "symbol out of range");
- return GetTableElement<char>(ehdr_, 0, 1, sym->st_value - link_base_);
-}
-
-const ElfW(Verdef) *ElfMemImage::GetVerdef(int index) const {
- ABSL_RAW_CHECK(0 <= index && static_cast<size_t>(index) <= verdefnum_,
- "index out of range");
- const ElfW(Verdef) *version_definition = verdef_;
- while (version_definition->vd_ndx < index && version_definition->vd_next) {
- const char *const version_definition_as_char =
- reinterpret_cast<const char *>(version_definition);
- version_definition =
- reinterpret_cast<const ElfW(Verdef) *>(version_definition_as_char +
- version_definition->vd_next);
- }
- return version_definition->vd_ndx == index ? version_definition : nullptr;
-}
-
-const ElfW(Verdaux) *ElfMemImage::GetVerdefAux(
- const ElfW(Verdef) *verdef) const {
- return reinterpret_cast<const ElfW(Verdaux) *>(verdef+1);
-}
-
-const char *ElfMemImage::GetVerstr(ElfW(Word) offset) const {
- ABSL_RAW_CHECK(offset < strsize_, "offset out of range");
- return dynstr_ + offset;
-}
-
-void ElfMemImage::Init(const void *base) {
- ehdr_ = nullptr;
- dynsym_ = nullptr;
- dynstr_ = nullptr;
- versym_ = nullptr;
- verdef_ = nullptr;
- hash_ = nullptr;
- strsize_ = 0;
- verdefnum_ = 0;
- // Sentinel: PT_LOAD .p_vaddr can't possibly be this.
- link_base_ = ~ElfW(Addr){0}; // NOLINT(readability/braces)
- if (!base) {
- return;
- }
- const char *const base_as_char = reinterpret_cast<const char *>(base);
- if (base_as_char[EI_MAG0] != ELFMAG0 || base_as_char[EI_MAG1] != ELFMAG1 ||
- base_as_char[EI_MAG2] != ELFMAG2 || base_as_char[EI_MAG3] != ELFMAG3) {
- assert(false);
- return;
- }
- int elf_class = base_as_char[EI_CLASS];
- if (elf_class != kElfClass) {
- assert(false);
- return;
- }
- switch (base_as_char[EI_DATA]) {
- case ELFDATA2LSB: {
-#ifndef ABSL_IS_LITTLE_ENDIAN
- assert(false);
- return;
-#endif
- break;
- }
- case ELFDATA2MSB: {
-#ifndef ABSL_IS_BIG_ENDIAN
- assert(false);
- return;
-#endif
- break;
- }
- default: {
- assert(false);
- return;
- }
- }
-
- ehdr_ = reinterpret_cast<const ElfW(Ehdr) *>(base);
- const ElfW(Phdr) *dynamic_program_header = nullptr;
- for (int i = 0; i < ehdr_->e_phnum; ++i) {
- const ElfW(Phdr) *const program_header = GetPhdr(i);
- switch (program_header->p_type) {
- case PT_LOAD:
- if (!~link_base_) {
- link_base_ = program_header->p_vaddr;
- }
- break;
- case PT_DYNAMIC:
- dynamic_program_header = program_header;
- break;
- }
- }
- if (!~link_base_ || !dynamic_program_header) {
- assert(false);
- // Mark this image as not present. Can not recur infinitely.
- Init(nullptr);
- return;
- }
- ptrdiff_t relocation =
- base_as_char - reinterpret_cast<const char *>(link_base_);
- ElfW(Dyn)* dynamic_entry = reinterpret_cast<ElfW(Dyn)*>(
- static_cast<intptr_t>(dynamic_program_header->p_vaddr) + relocation);
- for (; dynamic_entry->d_tag != DT_NULL; ++dynamic_entry) {
- const auto value =
- static_cast<intptr_t>(dynamic_entry->d_un.d_val) + relocation;
- switch (dynamic_entry->d_tag) {
- case DT_HASH:
- hash_ = reinterpret_cast<ElfW(Word) *>(value);
- break;
- case DT_SYMTAB:
- dynsym_ = reinterpret_cast<ElfW(Sym) *>(value);
- break;
- case DT_STRTAB:
- dynstr_ = reinterpret_cast<const char *>(value);
- break;
- case DT_VERSYM:
- versym_ = reinterpret_cast<ElfW(Versym) *>(value);
- break;
- case DT_VERDEF:
- verdef_ = reinterpret_cast<ElfW(Verdef) *>(value);
- break;
- case DT_VERDEFNUM:
- verdefnum_ = static_cast<size_t>(dynamic_entry->d_un.d_val);
- break;
- case DT_STRSZ:
- strsize_ = static_cast<size_t>(dynamic_entry->d_un.d_val);
- break;
- default:
- // Unrecognized entries explicitly ignored.
- break;
- }
- }
- if (!hash_ || !dynsym_ || !dynstr_ || !versym_ ||
- !verdef_ || !verdefnum_ || !strsize_) {
- assert(false); // invalid VDSO
- // Mark this image as not present. Can not recur infinitely.
- Init(nullptr);
- return;
- }
-}
-
-bool ElfMemImage::LookupSymbol(const char *name,
- const char *version,
- int type,
- SymbolInfo *info_out) const {
- for (const SymbolInfo& info : *this) {
- if (strcmp(info.name, name) == 0 && strcmp(info.version, version) == 0 &&
- ElfType(info.symbol) == type) {
- if (info_out) {
- *info_out = info;
- }
- return true;
- }
- }
- return false;
-}
-
-bool ElfMemImage::LookupSymbolByAddress(const void *address,
- SymbolInfo *info_out) const {
- for (const SymbolInfo& info : *this) {
- const char *const symbol_start =
- reinterpret_cast<const char *>(info.address);
- const char *const symbol_end = symbol_start + info.symbol->st_size;
- if (symbol_start <= address && address < symbol_end) {
- if (info_out) {
- // Client wants to know details for that symbol (the usual case).
- if (ElfBind(info.symbol) == STB_GLOBAL) {
- // Strong symbol; just return it.
- *info_out = info;
- return true;
- } else {
- // Weak or local. Record it, but keep looking for a strong one.
- *info_out = info;
- }
- } else {
- // Client only cares if there is an overlapping symbol.
- return true;
- }
- }
- }
- return false;
-}
-
-ElfMemImage::SymbolIterator::SymbolIterator(const void *const image, int index)
- : index_(index), image_(image) {
-}
-
-const ElfMemImage::SymbolInfo *ElfMemImage::SymbolIterator::operator->() const {
- return &info_;
-}
-
-const ElfMemImage::SymbolInfo& ElfMemImage::SymbolIterator::operator*() const {
- return info_;
-}
-
-bool ElfMemImage::SymbolIterator::operator==(const SymbolIterator &rhs) const {
- return this->image_ == rhs.image_ && this->index_ == rhs.index_;
-}
-
-bool ElfMemImage::SymbolIterator::operator!=(const SymbolIterator &rhs) const {
- return !(*this == rhs);
-}
-
-ElfMemImage::SymbolIterator &ElfMemImage::SymbolIterator::operator++() {
- this->Update(1);
- return *this;
-}
-
-ElfMemImage::SymbolIterator ElfMemImage::begin() const {
- SymbolIterator it(this, 0);
- it.Update(0);
- return it;
-}
-
-ElfMemImage::SymbolIterator ElfMemImage::end() const {
- return SymbolIterator(this, GetNumSymbols());
-}
-
-void ElfMemImage::SymbolIterator::Update(int increment) {
- const ElfMemImage *image = reinterpret_cast<const ElfMemImage *>(image_);
- ABSL_RAW_CHECK(image->IsPresent() || increment == 0, "");
- if (!image->IsPresent()) {
- return;
- }
- index_ += increment;
- if (index_ >= image->GetNumSymbols()) {
- index_ = image->GetNumSymbols();
- return;
- }
- const ElfW(Sym) *symbol = image->GetDynsym(index_);
- const ElfW(Versym) *version_symbol = image->GetVersym(index_);
- ABSL_RAW_CHECK(symbol && version_symbol, "");
- const char *const symbol_name = image->GetDynstr(symbol->st_name);
-#if defined(__NetBSD__)
- const int version_index = version_symbol->vs_vers & VERSYM_VERSION;
-#else
- const ElfW(Versym) version_index = version_symbol[0] & VERSYM_VERSION;
-#endif
- const ElfW(Verdef) *version_definition = nullptr;
- const char *version_name = "";
- if (symbol->st_shndx == SHN_UNDEF) {
- // Undefined symbols reference DT_VERNEED, not DT_VERDEF, and
- // version_index could well be greater than verdefnum_, so calling
- // GetVerdef(version_index) may trigger assertion.
- } else {
- version_definition = image->GetVerdef(version_index);
- }
- if (version_definition) {
- // I am expecting 1 or 2 auxiliary entries: 1 for the version itself,
- // optional 2nd if the version has a parent.
- ABSL_RAW_CHECK(
- version_definition->vd_cnt == 1 || version_definition->vd_cnt == 2,
- "wrong number of entries");
- const ElfW(Verdaux) *version_aux = image->GetVerdefAux(version_definition);
- version_name = image->GetVerstr(version_aux->vda_name);
- }
- info_.name = symbol_name;
- info_.version = version_name;
- info_.address = image->GetSymAddr(symbol);
- info_.symbol = symbol;
-}
-
-} // namespace debugging_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_HAVE_ELF_MEM_IMAGE
diff --git a/third_party/abseil-cpp/absl/debugging/internal/elf_mem_image.h b/third_party/abseil-cpp/absl/debugging/internal/elf_mem_image.h
deleted file mode 100644
index 113071a..0000000
--- a/third_party/abseil-cpp/absl/debugging/internal/elf_mem_image.h
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * Copyright 2017 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.
- */
-
-// Allow dynamic symbol lookup for in-memory Elf images.
-
-#ifndef ABSL_DEBUGGING_INTERNAL_ELF_MEM_IMAGE_H_
-#define ABSL_DEBUGGING_INTERNAL_ELF_MEM_IMAGE_H_
-
-// Including this will define the __GLIBC__ macro if glibc is being
-// used.
-#include <climits>
-
-#include "absl/base/config.h"
-
-// Maybe one day we can rewrite this file not to require the elf
-// symbol extensions in glibc, but for right now we need them.
-#ifdef ABSL_HAVE_ELF_MEM_IMAGE
-#error ABSL_HAVE_ELF_MEM_IMAGE cannot be directly set
-#endif
-
-#if defined(__ELF__) && !defined(__OpenBSD__) && !defined(__QNX__) && \
- !defined(__native_client__) && !defined(__asmjs__) && \
- !defined(__wasm__) && !defined(__HAIKU__)
-#define ABSL_HAVE_ELF_MEM_IMAGE 1
-#endif
-
-#ifdef ABSL_HAVE_ELF_MEM_IMAGE
-
-#include <link.h> // for ElfW
-
-#if defined(__FreeBSD__) && !defined(ElfW)
-#define ElfW(x) __ElfN(x)
-#endif
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace debugging_internal {
-
-// An in-memory ELF image (may not exist on disk).
-class ElfMemImage {
- private:
- // Sentinel: there could never be an elf image at &kInvalidBaseSentinel.
- static const int kInvalidBaseSentinel;
-
- public:
- // Sentinel: there could never be an elf image at this address.
- static constexpr const void *const kInvalidBase =
- static_cast<const void*>(&kInvalidBaseSentinel);
-
- // Information about a single vdso symbol.
- // All pointers are into .dynsym, .dynstr, or .text of the VDSO.
- // Do not free() them or modify through them.
- struct SymbolInfo {
- const char *name; // E.g. "__vdso_getcpu"
- const char *version; // E.g. "LINUX_2.6", could be ""
- // for unversioned symbol.
- const void *address; // Relocated symbol address.
- const ElfW(Sym) *symbol; // Symbol in the dynamic symbol table.
- };
-
- // Supports iteration over all dynamic symbols.
- class SymbolIterator {
- public:
- friend class ElfMemImage;
- const SymbolInfo *operator->() const;
- const SymbolInfo &operator*() const;
- SymbolIterator& operator++();
- bool operator!=(const SymbolIterator &rhs) const;
- bool operator==(const SymbolIterator &rhs) const;
- private:
- SymbolIterator(const void *const image, int index);
- void Update(int incr);
- SymbolInfo info_;
- int index_;
- const void *const image_;
- };
-
-
- explicit ElfMemImage(const void *base);
- void Init(const void *base);
- bool IsPresent() const { return ehdr_ != nullptr; }
- const ElfW(Phdr)* GetPhdr(int index) const;
- const ElfW(Sym)* GetDynsym(int index) const;
- const ElfW(Versym)* GetVersym(int index) const;
- const ElfW(Verdef)* GetVerdef(int index) const;
- const ElfW(Verdaux)* GetVerdefAux(const ElfW(Verdef) *verdef) const;
- const char* GetDynstr(ElfW(Word) offset) const;
- const void* GetSymAddr(const ElfW(Sym) *sym) const;
- const char* GetVerstr(ElfW(Word) offset) const;
- int GetNumSymbols() const;
-
- SymbolIterator begin() const;
- SymbolIterator end() const;
-
- // Look up versioned dynamic symbol in the image.
- // Returns false if image is not present, or doesn't contain given
- // symbol/version/type combination.
- // If info_out is non-null, additional details are filled in.
- bool LookupSymbol(const char *name, const char *version,
- int symbol_type, SymbolInfo *info_out) const;
-
- // Find info about symbol (if any) which overlaps given address.
- // Returns true if symbol was found; false if image isn't present
- // or doesn't have a symbol overlapping given address.
- // If info_out is non-null, additional details are filled in.
- bool LookupSymbolByAddress(const void *address, SymbolInfo *info_out) const;
-
- private:
- const ElfW(Ehdr) *ehdr_;
- const ElfW(Sym) *dynsym_;
- const ElfW(Versym) *versym_;
- const ElfW(Verdef) *verdef_;
- const ElfW(Word) *hash_;
- const char *dynstr_;
- size_t strsize_;
- size_t verdefnum_;
- ElfW(Addr) link_base_; // Link-time base (p_vaddr of first PT_LOAD).
-};
-
-} // namespace debugging_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_HAVE_ELF_MEM_IMAGE
-
-#endif // ABSL_DEBUGGING_INTERNAL_ELF_MEM_IMAGE_H_
diff --git a/third_party/abseil-cpp/absl/debugging/internal/examine_stack.cc b/third_party/abseil-cpp/absl/debugging/internal/examine_stack.cc
deleted file mode 100644
index 5786322..0000000
--- a/third_party/abseil-cpp/absl/debugging/internal/examine_stack.cc
+++ /dev/null
@@ -1,317 +0,0 @@
-//
-// Copyright 2018 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/debugging/internal/examine_stack.h"
-
-#ifndef _WIN32
-#include <unistd.h>
-#endif
-
-#include "absl/base/config.h"
-
-#ifdef ABSL_HAVE_MMAP
-#include <sys/mman.h>
-#endif
-
-#if defined(__linux__) || defined(__APPLE__)
-#include <sys/ucontext.h>
-#endif
-
-#include <csignal>
-#include <cstdio>
-
-#include "absl/base/attributes.h"
-#include "absl/base/internal/raw_logging.h"
-#include "absl/base/macros.h"
-#include "absl/debugging/stacktrace.h"
-#include "absl/debugging/symbolize.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace debugging_internal {
-
-namespace {
-constexpr int kDefaultDumpStackFramesLimit = 64;
-// The %p field width for printf() functions is two characters per byte,
-// and two extra for the leading "0x".
-constexpr int kPrintfPointerFieldWidth = 2 + 2 * sizeof(void*);
-
-ABSL_CONST_INIT SymbolizeUrlEmitter debug_stack_trace_hook = nullptr;
-
-// Async-signal safe mmap allocator.
-void* Allocate(size_t num_bytes) {
-#ifdef ABSL_HAVE_MMAP
- void* p = ::mmap(nullptr, num_bytes, PROT_READ | PROT_WRITE,
- MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
- return p == MAP_FAILED ? nullptr : p;
-#else
- (void)num_bytes;
- return nullptr;
-#endif // ABSL_HAVE_MMAP
-}
-
-void Deallocate(void* p, size_t size) {
-#ifdef ABSL_HAVE_MMAP
- ::munmap(p, size);
-#else
- (void)p;
- (void)size;
-#endif // ABSL_HAVE_MMAP
-}
-
-// Print a program counter only.
-void DumpPC(OutputWriter* writer, void* writer_arg, void* const pc,
- const char* const prefix) {
- char buf[100];
- snprintf(buf, sizeof(buf), "%s@ %*p\n", prefix, kPrintfPointerFieldWidth, pc);
- writer(buf, writer_arg);
-}
-
-// Print a program counter and the corresponding stack frame size.
-void DumpPCAndFrameSize(OutputWriter* writer, void* writer_arg, void* const pc,
- int framesize, const char* const prefix) {
- char buf[100];
- if (framesize <= 0) {
- snprintf(buf, sizeof(buf), "%s@ %*p (unknown)\n", prefix,
- kPrintfPointerFieldWidth, pc);
- } else {
- snprintf(buf, sizeof(buf), "%s@ %*p %9d\n", prefix,
- kPrintfPointerFieldWidth, pc, framesize);
- }
- writer(buf, writer_arg);
-}
-
-// Print a program counter and the corresponding symbol.
-void DumpPCAndSymbol(OutputWriter* writer, void* writer_arg, void* const pc,
- const char* const prefix) {
- char tmp[1024];
- const char* symbol = "(unknown)";
- // Symbolizes the previous address of pc because pc may be in the
- // next function. The overrun happens when the function ends with
- // a call to a function annotated noreturn (e.g. CHECK).
- // If symbolization of pc-1 fails, also try pc on the off-chance
- // that we crashed on the first instruction of a function (that
- // actually happens very often for e.g. __restore_rt).
- const uintptr_t prev_pc = reinterpret_cast<uintptr_t>(pc) - 1;
- if (absl::Symbolize(reinterpret_cast<const char*>(prev_pc), tmp,
- sizeof(tmp)) ||
- absl::Symbolize(pc, tmp, sizeof(tmp))) {
- symbol = tmp;
- }
- char buf[1024];
- snprintf(buf, sizeof(buf), "%s@ %*p %s\n", prefix, kPrintfPointerFieldWidth,
- pc, symbol);
- writer(buf, writer_arg);
-}
-
-// Print a program counter, its stack frame size, and its symbol name.
-// Note that there is a separate symbolize_pc argument. Return addresses may be
-// at the end of the function, and this allows the caller to back up from pc if
-// appropriate.
-void DumpPCAndFrameSizeAndSymbol(OutputWriter* writer, void* writer_arg,
- void* const pc, void* const symbolize_pc,
- int framesize, const char* const prefix) {
- char tmp[1024];
- const char* symbol = "(unknown)";
- if (absl::Symbolize(symbolize_pc, tmp, sizeof(tmp))) {
- symbol = tmp;
- }
- char buf[1024];
- if (framesize <= 0) {
- snprintf(buf, sizeof(buf), "%s@ %*p (unknown) %s\n", prefix,
- kPrintfPointerFieldWidth, pc, symbol);
- } else {
- snprintf(buf, sizeof(buf), "%s@ %*p %9d %s\n", prefix,
- kPrintfPointerFieldWidth, pc, framesize, symbol);
- }
- writer(buf, writer_arg);
-}
-
-} // namespace
-
-void RegisterDebugStackTraceHook(SymbolizeUrlEmitter hook) {
- debug_stack_trace_hook = hook;
-}
-
-SymbolizeUrlEmitter GetDebugStackTraceHook() { return debug_stack_trace_hook; }
-
-// Returns the program counter from signal context, nullptr if
-// unknown. vuc is a ucontext_t*. We use void* to avoid the use of
-// ucontext_t on non-POSIX systems.
-void* GetProgramCounter(void* const vuc) {
-#ifdef __linux__
- if (vuc != nullptr) {
- ucontext_t* context = reinterpret_cast<ucontext_t*>(vuc);
-#if defined(__aarch64__)
- return reinterpret_cast<void*>(context->uc_mcontext.pc);
-#elif defined(__alpha__)
- return reinterpret_cast<void*>(context->uc_mcontext.sc_pc);
-#elif defined(__arm__)
- return reinterpret_cast<void*>(context->uc_mcontext.arm_pc);
-#elif defined(__hppa__)
- return reinterpret_cast<void*>(context->uc_mcontext.sc_iaoq[0]);
-#elif defined(__i386__)
- if (14 < ABSL_ARRAYSIZE(context->uc_mcontext.gregs))
- return reinterpret_cast<void*>(context->uc_mcontext.gregs[14]);
-#elif defined(__ia64__)
- return reinterpret_cast<void*>(context->uc_mcontext.sc_ip);
-#elif defined(__m68k__)
- return reinterpret_cast<void*>(context->uc_mcontext.gregs[16]);
-#elif defined(__mips__)
- return reinterpret_cast<void*>(context->uc_mcontext.pc);
-#elif defined(__powerpc64__)
- return reinterpret_cast<void*>(context->uc_mcontext.gp_regs[32]);
-#elif defined(__powerpc__)
- return reinterpret_cast<void*>(context->uc_mcontext.uc_regs->gregs[32]);
-#elif defined(__riscv)
- return reinterpret_cast<void*>(context->uc_mcontext.__gregs[REG_PC]);
-#elif defined(__s390__) && !defined(__s390x__)
- return reinterpret_cast<void*>(context->uc_mcontext.psw.addr & 0x7fffffff);
-#elif defined(__s390__) && defined(__s390x__)
- return reinterpret_cast<void*>(context->uc_mcontext.psw.addr);
-#elif defined(__sh__)
- return reinterpret_cast<void*>(context->uc_mcontext.pc);
-#elif defined(__sparc__) && !defined(__arch64__)
- return reinterpret_cast<void*>(context->uc_mcontext.gregs[19]);
-#elif defined(__sparc__) && defined(__arch64__)
- return reinterpret_cast<void*>(context->uc_mcontext.mc_gregs[19]);
-#elif defined(__x86_64__)
- if (16 < ABSL_ARRAYSIZE(context->uc_mcontext.gregs))
- return reinterpret_cast<void*>(context->uc_mcontext.gregs[16]);
-#elif defined(__e2k__)
- return reinterpret_cast<void*>(context->uc_mcontext.cr0_hi);
-#elif defined(__loongarch__)
- return reinterpret_cast<void*>(context->uc_mcontext.__pc);
-#else
-#error "Undefined Architecture."
-#endif
- }
-#elif defined(__APPLE__)
- if (vuc != nullptr) {
- ucontext_t* signal_ucontext = reinterpret_cast<ucontext_t*>(vuc);
-#if defined(__aarch64__)
- return reinterpret_cast<void*>(
- __darwin_arm_thread_state64_get_pc(signal_ucontext->uc_mcontext->__ss));
-#elif defined(__arm__)
-#if __DARWIN_UNIX03
- return reinterpret_cast<void*>(signal_ucontext->uc_mcontext->__ss.__pc);
-#else
- return reinterpret_cast<void*>(signal_ucontext->uc_mcontext->ss.pc);
-#endif
-#elif defined(__i386__)
-#if __DARWIN_UNIX03
- return reinterpret_cast<void*>(signal_ucontext->uc_mcontext->__ss.__eip);
-#else
- return reinterpret_cast<void*>(signal_ucontext->uc_mcontext->ss.eip);
-#endif
-#elif defined(__x86_64__)
-#if __DARWIN_UNIX03
- return reinterpret_cast<void*>(signal_ucontext->uc_mcontext->__ss.__rip);
-#else
- return reinterpret_cast<void*>(signal_ucontext->uc_mcontext->ss.rip);
-#endif
-#endif
- }
-#elif defined(__akaros__)
- auto* ctx = reinterpret_cast<struct user_context*>(vuc);
- return reinterpret_cast<void*>(get_user_ctx_pc(ctx));
-#endif
- static_cast<void>(vuc);
- return nullptr;
-}
-
-void DumpPCAndFrameSizesAndStackTrace(void* const pc, void* const stack[],
- int frame_sizes[], int depth,
- int min_dropped_frames,
- bool symbolize_stacktrace,
- OutputWriter* writer, void* writer_arg) {
- if (pc != nullptr) {
- // We don't know the stack frame size for PC, use 0.
- if (symbolize_stacktrace) {
- DumpPCAndFrameSizeAndSymbol(writer, writer_arg, pc, pc, 0, "PC: ");
- } else {
- DumpPCAndFrameSize(writer, writer_arg, pc, 0, "PC: ");
- }
- }
- for (int i = 0; i < depth; i++) {
- if (symbolize_stacktrace) {
- // Pass the previous address of pc as the symbol address because pc is a
- // return address, and an overrun may occur when the function ends with a
- // call to a function annotated noreturn (e.g. CHECK). Note that we don't
- // do this for pc above, as the adjustment is only correct for return
- // addresses.
- DumpPCAndFrameSizeAndSymbol(writer, writer_arg, stack[i],
- reinterpret_cast<char*>(stack[i]) - 1,
- frame_sizes[i], " ");
- } else {
- DumpPCAndFrameSize(writer, writer_arg, stack[i], frame_sizes[i], " ");
- }
- }
- if (min_dropped_frames > 0) {
- char buf[100];
- snprintf(buf, sizeof(buf), " @ ... and at least %d more frames\n",
- min_dropped_frames);
- writer(buf, writer_arg);
- }
-}
-
-// Dump current stack trace as directed by writer.
-// Make sure this function is not inlined to avoid skipping too many top frames.
-ABSL_ATTRIBUTE_NOINLINE
-void DumpStackTrace(int min_dropped_frames, int max_num_frames,
- bool symbolize_stacktrace, OutputWriter* writer,
- void* writer_arg) {
- // Print stack trace
- void* stack_buf[kDefaultDumpStackFramesLimit];
- void** stack = stack_buf;
- int num_stack = kDefaultDumpStackFramesLimit;
- size_t allocated_bytes = 0;
-
- if (num_stack >= max_num_frames) {
- // User requested fewer frames than we already have space for.
- num_stack = max_num_frames;
- } else {
- const size_t needed_bytes =
- static_cast<size_t>(max_num_frames) * sizeof(stack[0]);
- void* p = Allocate(needed_bytes);
- if (p != nullptr) { // We got the space.
- num_stack = max_num_frames;
- stack = reinterpret_cast<void**>(p);
- allocated_bytes = needed_bytes;
- }
- }
-
- int depth = absl::GetStackTrace(stack, num_stack, min_dropped_frames + 1);
- for (int i = 0; i < depth; i++) {
- if (symbolize_stacktrace) {
- DumpPCAndSymbol(writer, writer_arg, stack[static_cast<size_t>(i)],
- " ");
- } else {
- DumpPC(writer, writer_arg, stack[static_cast<size_t>(i)], " ");
- }
- }
-
- auto hook = GetDebugStackTraceHook();
- if (hook != nullptr) {
- (*hook)(stack, depth, writer, writer_arg);
- }
-
- if (allocated_bytes != 0) Deallocate(stack, allocated_bytes);
-}
-
-} // namespace debugging_internal
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/debugging/internal/examine_stack.h b/third_party/abseil-cpp/absl/debugging/internal/examine_stack.h
deleted file mode 100644
index 190af87..0000000
--- a/third_party/abseil-cpp/absl/debugging/internal/examine_stack.h
+++ /dev/null
@@ -1,64 +0,0 @@
-//
-// Copyright 2018 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_DEBUGGING_INTERNAL_EXAMINE_STACK_H_
-#define ABSL_DEBUGGING_INTERNAL_EXAMINE_STACK_H_
-
-#include "absl/base/config.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace debugging_internal {
-
-// Type of function used for printing in stack trace dumping, etc.
-// We avoid closures to keep things simple.
-typedef void OutputWriter(const char*, void*);
-
-// RegisterDebugStackTraceHook() allows to register a single routine
-// `hook` that is called each time DumpStackTrace() is called.
-// `hook` may be called from a signal handler.
-typedef void (*SymbolizeUrlEmitter)(void* const stack[], int depth,
- OutputWriter* writer, void* writer_arg);
-
-// Registration of SymbolizeUrlEmitter for use inside of a signal handler.
-// This is inherently unsafe and must be signal safe code.
-void RegisterDebugStackTraceHook(SymbolizeUrlEmitter hook);
-SymbolizeUrlEmitter GetDebugStackTraceHook();
-
-// Returns the program counter from signal context, or nullptr if
-// unknown. `vuc` is a ucontext_t*. We use void* to avoid the use of
-// ucontext_t on non-POSIX systems.
-void* GetProgramCounter(void* const vuc);
-
-// Uses `writer` to dump the program counter, stack trace, and stack
-// frame sizes.
-void DumpPCAndFrameSizesAndStackTrace(void* const pc, void* const stack[],
- int frame_sizes[], int depth,
- int min_dropped_frames,
- bool symbolize_stacktrace,
- OutputWriter* writer, void* writer_arg);
-
-// Dump current stack trace omitting the topmost `min_dropped_frames` stack
-// frames.
-void DumpStackTrace(int min_dropped_frames, int max_num_frames,
- bool symbolize_stacktrace, OutputWriter* writer,
- void* writer_arg);
-
-} // namespace debugging_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_DEBUGGING_INTERNAL_EXAMINE_STACK_H_
diff --git a/third_party/abseil-cpp/absl/debugging/internal/stack_consumption.cc b/third_party/abseil-cpp/absl/debugging/internal/stack_consumption.cc
deleted file mode 100644
index 5134864..0000000
--- a/third_party/abseil-cpp/absl/debugging/internal/stack_consumption.cc
+++ /dev/null
@@ -1,185 +0,0 @@
-//
-// Copyright 2018 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/debugging/internal/stack_consumption.h"
-
-#ifdef ABSL_INTERNAL_HAVE_DEBUGGING_STACK_CONSUMPTION
-
-#include <signal.h>
-#include <sys/mman.h>
-#include <unistd.h>
-
-#include <string.h>
-
-#include "absl/base/attributes.h"
-#include "absl/base/internal/raw_logging.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace debugging_internal {
-namespace {
-
-// This code requires that we know the direction in which the stack
-// grows. It is commonly believed that this can be detected by putting
-// a variable on the stack and then passing its address to a function
-// that compares the address of this variable to the address of a
-// variable on the function's own stack. However, this is unspecified
-// behavior in C++: If two pointers p and q of the same type point to
-// different objects that are not members of the same object or
-// elements of the same array or to different functions, or if only
-// one of them is null, the results of p<q, p>q, p<=q, and p>=q are
-// unspecified. Therefore, instead we hardcode the direction of the
-// stack on platforms we know about.
-#if defined(__i386__) || defined(__x86_64__) || defined(__ppc__) || \
- defined(__aarch64__) || defined(__riscv)
-constexpr bool kStackGrowsDown = true;
-#else
-#error Need to define kStackGrowsDown
-#endif
-
-// To measure the stack footprint of some code, we create a signal handler
-// (for SIGUSR2 say) that exercises this code on an alternate stack. This
-// alternate stack is initialized to some known pattern (0x55, 0x55, 0x55,
-// ...). We then self-send this signal, and after the signal handler returns,
-// look at the alternate stack buffer to see what portion has been touched.
-//
-// This trick gives us the the stack footprint of the signal handler. But the
-// signal handler, even before the code for it is exercised, consumes some
-// stack already. We however only want the stack usage of the code inside the
-// signal handler. To measure this accurately, we install two signal handlers:
-// one that does nothing and just returns, and the user-provided signal
-// handler. The difference between the stack consumption of these two signals
-// handlers should give us the stack foorprint of interest.
-
-void EmptySignalHandler(int) {}
-
-// This is arbitrary value, and could be increase further, at the cost of
-// memset()ting it all to known sentinel value.
-constexpr int kAlternateStackSize = 64 << 10; // 64KiB
-
-constexpr int kSafetyMargin = 32;
-constexpr char kAlternateStackFillValue = 0x55;
-
-// These helper functions look at the alternate stack buffer, and figure
-// out what portion of this buffer has been touched - this is the stack
-// consumption of the signal handler running on this alternate stack.
-// This function will return -1 if the alternate stack buffer has not been
-// touched. It will abort the program if the buffer has overflowed or is about
-// to overflow.
-int GetStackConsumption(const void* const altstack) {
- const char* begin;
- int increment;
- if (kStackGrowsDown) {
- begin = reinterpret_cast<const char*>(altstack);
- increment = 1;
- } else {
- begin = reinterpret_cast<const char*>(altstack) + kAlternateStackSize - 1;
- increment = -1;
- }
-
- for (int usage_count = kAlternateStackSize; usage_count > 0; --usage_count) {
- if (*begin != kAlternateStackFillValue) {
- ABSL_RAW_CHECK(usage_count <= kAlternateStackSize - kSafetyMargin,
- "Buffer has overflowed or is about to overflow");
- return usage_count;
- }
- begin += increment;
- }
-
- ABSL_RAW_LOG(FATAL, "Unreachable code");
- return -1;
-}
-
-} // namespace
-
-int GetSignalHandlerStackConsumption(void (*signal_handler)(int)) {
- // The alt-signal-stack cannot be heap allocated because there is a
- // bug in glibc-2.2 where some signal handler setup code looks at the
- // current stack pointer to figure out what thread is currently running.
- // Therefore, the alternate stack must be allocated from the main stack
- // itself.
- void* altstack = mmap(nullptr, kAlternateStackSize, PROT_READ | PROT_WRITE,
- MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
- ABSL_RAW_CHECK(altstack != MAP_FAILED, "mmap() failed");
-
- // Set up the alt-signal-stack (and save the older one).
- stack_t sigstk;
- memset(&sigstk, 0, sizeof(sigstk));
- sigstk.ss_sp = altstack;
- sigstk.ss_size = kAlternateStackSize;
- sigstk.ss_flags = 0;
- stack_t old_sigstk;
- memset(&old_sigstk, 0, sizeof(old_sigstk));
- ABSL_RAW_CHECK(sigaltstack(&sigstk, &old_sigstk) == 0,
- "sigaltstack() failed");
-
- // Set up SIGUSR1 and SIGUSR2 signal handlers (and save the older ones).
- struct sigaction sa;
- memset(&sa, 0, sizeof(sa));
- struct sigaction old_sa1, old_sa2;
- sigemptyset(&sa.sa_mask);
- sa.sa_flags = SA_ONSTACK;
-
- // SIGUSR1 maps to EmptySignalHandler.
- sa.sa_handler = EmptySignalHandler;
- ABSL_RAW_CHECK(sigaction(SIGUSR1, &sa, &old_sa1) == 0, "sigaction() failed");
-
- // SIGUSR2 maps to signal_handler.
- sa.sa_handler = signal_handler;
- ABSL_RAW_CHECK(sigaction(SIGUSR2, &sa, &old_sa2) == 0, "sigaction() failed");
-
- // Send SIGUSR1 signal and measure the stack consumption of the empty
- // signal handler.
- // The first signal might use more stack space. Run once and ignore the
- // results to get that out of the way.
- ABSL_RAW_CHECK(kill(getpid(), SIGUSR1) == 0, "kill() failed");
-
- memset(altstack, kAlternateStackFillValue, kAlternateStackSize);
- ABSL_RAW_CHECK(kill(getpid(), SIGUSR1) == 0, "kill() failed");
- int base_stack_consumption = GetStackConsumption(altstack);
-
- // Send SIGUSR2 signal and measure the stack consumption of signal_handler.
- ABSL_RAW_CHECK(kill(getpid(), SIGUSR2) == 0, "kill() failed");
- int signal_handler_stack_consumption = GetStackConsumption(altstack);
-
- // Now restore the old alt-signal-stack and signal handlers.
- if (old_sigstk.ss_sp == nullptr && old_sigstk.ss_size == 0 &&
- (old_sigstk.ss_flags & SS_DISABLE)) {
- // https://git.musl-libc.org/cgit/musl/commit/src/signal/sigaltstack.c?id=7829f42a2c8944555439380498ab8b924d0f2070
- // The original stack has ss_size==0 and ss_flags==SS_DISABLE, but some
- // versions of musl have a bug that rejects ss_size==0. Work around this by
- // setting ss_size to MINSIGSTKSZ, which should be ignored by the kernel
- // when SS_DISABLE is set.
- old_sigstk.ss_size = MINSIGSTKSZ;
- }
- ABSL_RAW_CHECK(sigaltstack(&old_sigstk, nullptr) == 0,
- "sigaltstack() failed");
- ABSL_RAW_CHECK(sigaction(SIGUSR1, &old_sa1, nullptr) == 0,
- "sigaction() failed");
- ABSL_RAW_CHECK(sigaction(SIGUSR2, &old_sa2, nullptr) == 0,
- "sigaction() failed");
-
- ABSL_RAW_CHECK(munmap(altstack, kAlternateStackSize) == 0, "munmap() failed");
- if (signal_handler_stack_consumption != -1 && base_stack_consumption != -1) {
- return signal_handler_stack_consumption - base_stack_consumption;
- }
- return -1;
-}
-
-} // namespace debugging_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_INTERNAL_HAVE_DEBUGGING_STACK_CONSUMPTION
diff --git a/third_party/abseil-cpp/absl/debugging/internal/stack_consumption.h b/third_party/abseil-cpp/absl/debugging/internal/stack_consumption.h
deleted file mode 100644
index f41b64c..0000000
--- a/third_party/abseil-cpp/absl/debugging/internal/stack_consumption.h
+++ /dev/null
@@ -1,50 +0,0 @@
-//
-// Copyright 2018 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.
-
-// Helper function for measuring stack consumption of signal handlers.
-
-#ifndef ABSL_DEBUGGING_INTERNAL_STACK_CONSUMPTION_H_
-#define ABSL_DEBUGGING_INTERNAL_STACK_CONSUMPTION_H_
-
-#include "absl/base/config.h"
-
-// The code in this module is not portable.
-// Use this feature test macro to detect its availability.
-#ifdef ABSL_INTERNAL_HAVE_DEBUGGING_STACK_CONSUMPTION
-#error ABSL_INTERNAL_HAVE_DEBUGGING_STACK_CONSUMPTION cannot be set directly
-#elif !defined(__APPLE__) && !defined(_WIN32) && \
- (defined(__i386__) || defined(__x86_64__) || defined(__ppc__) || \
- defined(__aarch64__) || defined(__riscv))
-#define ABSL_INTERNAL_HAVE_DEBUGGING_STACK_CONSUMPTION 1
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace debugging_internal {
-
-// Returns the stack consumption in bytes for the code exercised by
-// signal_handler. To measure stack consumption, signal_handler is registered
-// as a signal handler, so the code that it exercises must be async-signal
-// safe. The argument of signal_handler is an implementation detail of signal
-// handlers and should ignored by the code for signal_handler. Use global
-// variables to pass information between your test code and signal_handler.
-int GetSignalHandlerStackConsumption(void (*signal_handler)(int));
-
-} // namespace debugging_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_INTERNAL_HAVE_DEBUGGING_STACK_CONSUMPTION
-
-#endif // ABSL_DEBUGGING_INTERNAL_STACK_CONSUMPTION_H_
diff --git a/third_party/abseil-cpp/absl/debugging/internal/stack_consumption_test.cc b/third_party/abseil-cpp/absl/debugging/internal/stack_consumption_test.cc
deleted file mode 100644
index 80445bf..0000000
--- a/third_party/abseil-cpp/absl/debugging/internal/stack_consumption_test.cc
+++ /dev/null
@@ -1,50 +0,0 @@
-//
-// Copyright 2018 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/debugging/internal/stack_consumption.h"
-
-#ifdef ABSL_INTERNAL_HAVE_DEBUGGING_STACK_CONSUMPTION
-
-#include <string.h>
-
-#include "gtest/gtest.h"
-#include "absl/base/internal/raw_logging.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace debugging_internal {
-namespace {
-
-static void SimpleSignalHandler(int signo) {
- char buf[100];
- memset(buf, 'a', sizeof(buf));
-
- // Never true, but prevents compiler from optimizing buf out.
- if (signo == 0) {
- ABSL_RAW_LOG(INFO, "%p", static_cast<void*>(buf));
- }
-}
-
-TEST(SignalHandlerStackConsumptionTest, MeasuresStackConsumption) {
- // Our handler should consume reasonable number of bytes.
- EXPECT_GE(GetSignalHandlerStackConsumption(SimpleSignalHandler), 100);
-}
-
-} // namespace
-} // namespace debugging_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_INTERNAL_HAVE_DEBUGGING_STACK_CONSUMPTION
diff --git a/third_party/abseil-cpp/absl/debugging/internal/stacktrace_aarch64-inl.inc b/third_party/abseil-cpp/absl/debugging/internal/stacktrace_aarch64-inl.inc
deleted file mode 100644
index 71cdaf0..0000000
--- a/third_party/abseil-cpp/absl/debugging/internal/stacktrace_aarch64-inl.inc
+++ /dev/null
@@ -1,206 +0,0 @@
-#ifndef ABSL_DEBUGGING_INTERNAL_STACKTRACE_AARCH64_INL_H_
-#define ABSL_DEBUGGING_INTERNAL_STACKTRACE_AARCH64_INL_H_
-
-// Generate stack tracer for aarch64
-
-#if defined(__linux__)
-#include <sys/mman.h>
-#include <ucontext.h>
-#include <unistd.h>
-#endif
-
-#include <atomic>
-#include <cassert>
-#include <cstdint>
-#include <iostream>
-
-#include "absl/base/attributes.h"
-#include "absl/debugging/internal/address_is_readable.h"
-#include "absl/debugging/internal/vdso_support.h" // a no-op on non-elf or non-glibc systems
-#include "absl/debugging/stacktrace.h"
-
-static const size_t kUnknownFrameSize = 0;
-
-#if defined(__linux__)
-// Returns the address of the VDSO __kernel_rt_sigreturn function, if present.
-static const unsigned char* GetKernelRtSigreturnAddress() {
- constexpr uintptr_t kImpossibleAddress = 1;
- ABSL_CONST_INIT static std::atomic<uintptr_t> memoized{kImpossibleAddress};
- uintptr_t address = memoized.load(std::memory_order_relaxed);
- if (address != kImpossibleAddress) {
- return reinterpret_cast<const unsigned char*>(address);
- }
-
- address = reinterpret_cast<uintptr_t>(nullptr);
-
-#ifdef ABSL_HAVE_VDSO_SUPPORT
- absl::debugging_internal::VDSOSupport vdso;
- if (vdso.IsPresent()) {
- absl::debugging_internal::VDSOSupport::SymbolInfo symbol_info;
- auto lookup = [&](int type) {
- return vdso.LookupSymbol("__kernel_rt_sigreturn", "LINUX_2.6.39", type,
- &symbol_info);
- };
- if ((!lookup(STT_FUNC) && !lookup(STT_NOTYPE)) ||
- symbol_info.address == nullptr) {
- // Unexpected: VDSO is present, yet the expected symbol is missing
- // or null.
- assert(false && "VDSO is present, but doesn't have expected symbol");
- } else {
- if (reinterpret_cast<uintptr_t>(symbol_info.address) !=
- kImpossibleAddress) {
- address = reinterpret_cast<uintptr_t>(symbol_info.address);
- } else {
- assert(false && "VDSO returned invalid address");
- }
- }
- }
-#endif
-
- memoized.store(address, std::memory_order_relaxed);
- return reinterpret_cast<const unsigned char*>(address);
-}
-#endif // __linux__
-
-// Compute the size of a stack frame in [low..high). We assume that
-// low < high. Return size of kUnknownFrameSize.
-template<typename T>
-static inline size_t ComputeStackFrameSize(const T* low,
- const T* high) {
- const char* low_char_ptr = reinterpret_cast<const char *>(low);
- const char* high_char_ptr = reinterpret_cast<const char *>(high);
- return low < high ? static_cast<size_t>(high_char_ptr - low_char_ptr)
- : kUnknownFrameSize;
-}
-
-// Given a pointer to a stack frame, locate and return the calling
-// stackframe, or return null if no stackframe can be found. Perform sanity
-// checks (the strictness of which is controlled by the boolean parameter
-// "STRICT_UNWINDING") to reduce the chance that a bad pointer is returned.
-template<bool STRICT_UNWINDING, bool WITH_CONTEXT>
-ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS // May read random elements from stack.
-ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY // May read random elements from stack.
-static void **NextStackFrame(void **old_frame_pointer, const void *uc) {
- void **new_frame_pointer = reinterpret_cast<void**>(*old_frame_pointer);
- bool check_frame_size = true;
-
-#if defined(__linux__)
- if (WITH_CONTEXT && uc != nullptr) {
- // Check to see if next frame's return address is __kernel_rt_sigreturn.
- if (old_frame_pointer[1] == GetKernelRtSigreturnAddress()) {
- const ucontext_t *ucv = static_cast<const ucontext_t *>(uc);
- // old_frame_pointer[0] is not suitable for unwinding, look at
- // ucontext to discover frame pointer before signal.
- void **const pre_signal_frame_pointer =
- reinterpret_cast<void **>(ucv->uc_mcontext.regs[29]);
-
- // Check that alleged frame pointer is actually readable. This is to
- // prevent "double fault" in case we hit the first fault due to e.g.
- // stack corruption.
- if (!absl::debugging_internal::AddressIsReadable(
- pre_signal_frame_pointer))
- return nullptr;
-
- // Alleged frame pointer is readable, use it for further unwinding.
- new_frame_pointer = pre_signal_frame_pointer;
-
- // Skip frame size check if we return from a signal. We may be using a
- // an alternate stack for signals.
- check_frame_size = false;
- }
- }
-#endif
-
- // The frame pointer should be 8-byte aligned.
- if ((reinterpret_cast<uintptr_t>(new_frame_pointer) & 7) != 0)
- return nullptr;
-
- // Check frame size. In strict mode, we assume frames to be under
- // 100,000 bytes. In non-strict mode, we relax the limit to 1MB.
- if (check_frame_size) {
- const size_t max_size = STRICT_UNWINDING ? 100000 : 1000000;
- const size_t frame_size =
- ComputeStackFrameSize(old_frame_pointer, new_frame_pointer);
- if (frame_size == kUnknownFrameSize || frame_size > max_size)
- return nullptr;
- }
-
- return new_frame_pointer;
-}
-
-template <bool IS_STACK_FRAMES, bool IS_WITH_CONTEXT>
-ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS // May read random elements from stack.
-ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY // May read random elements from stack.
-static int UnwindImpl(void** result, int* sizes, int max_depth, int skip_count,
- const void *ucp, int *min_dropped_frames) {
-#ifdef __GNUC__
- void **frame_pointer = reinterpret_cast<void**>(__builtin_frame_address(0));
-#else
-# error reading stack point not yet supported on this platform.
-#endif
-
- skip_count++; // Skip the frame for this function.
- int n = 0;
-
- // The frame pointer points to low address of a frame. The first 64-bit
- // word of a frame points to the next frame up the call chain, which normally
- // is just after the high address of the current frame. The second word of
- // a frame contains return adress of to the caller. To find a pc value
- // associated with the current frame, we need to go down a level in the call
- // chain. So we remember return the address of the last frame seen. This
- // does not work for the first stack frame, which belongs to UnwindImp() but
- // we skip the frame for UnwindImp() anyway.
- void* prev_return_address = nullptr;
-
- while (frame_pointer && n < max_depth) {
- // The absl::GetStackFrames routine is called when we are in some
- // informational context (the failure signal handler for example).
- // Use the non-strict unwinding rules to produce a stack trace
- // that is as complete as possible (even if it contains a few bogus
- // entries in some rare cases).
- void **next_frame_pointer =
- NextStackFrame<!IS_STACK_FRAMES, IS_WITH_CONTEXT>(frame_pointer, ucp);
-
- if (skip_count > 0) {
- skip_count--;
- } else {
- result[n] = prev_return_address;
- if (IS_STACK_FRAMES) {
- sizes[n] = static_cast<int>(
- ComputeStackFrameSize(frame_pointer, next_frame_pointer));
- }
- n++;
- }
- prev_return_address = frame_pointer[1];
- frame_pointer = next_frame_pointer;
- }
- if (min_dropped_frames != nullptr) {
- // Implementation detail: we clamp the max of frames we are willing to
- // count, so as not to spend too much time in the loop below.
- const int kMaxUnwind = 200;
- int num_dropped_frames = 0;
- for (int j = 0; frame_pointer != nullptr && j < kMaxUnwind; j++) {
- if (skip_count > 0) {
- skip_count--;
- } else {
- num_dropped_frames++;
- }
- frame_pointer =
- NextStackFrame<!IS_STACK_FRAMES, IS_WITH_CONTEXT>(frame_pointer, ucp);
- }
- *min_dropped_frames = num_dropped_frames;
- }
- return n;
-}
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace debugging_internal {
-bool StackTraceWorksForTest() {
- return true;
-}
-} // namespace debugging_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_DEBUGGING_INTERNAL_STACKTRACE_AARCH64_INL_H_
diff --git a/third_party/abseil-cpp/absl/debugging/internal/stacktrace_arm-inl.inc b/third_party/abseil-cpp/absl/debugging/internal/stacktrace_arm-inl.inc
deleted file mode 100644
index 102a2a1..0000000
--- a/third_party/abseil-cpp/absl/debugging/internal/stacktrace_arm-inl.inc
+++ /dev/null
@@ -1,139 +0,0 @@
-// Copyright 2017 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.
-//
-// This is inspired by Craig Silverstein's PowerPC stacktrace code.
-
-#ifndef ABSL_DEBUGGING_INTERNAL_STACKTRACE_ARM_INL_H_
-#define ABSL_DEBUGGING_INTERNAL_STACKTRACE_ARM_INL_H_
-
-#include <cstdint>
-
-#include "absl/debugging/stacktrace.h"
-
-// WARNING:
-// This only works if all your code is in either ARM or THUMB mode. With
-// interworking, the frame pointer of the caller can either be in r11 (ARM
-// mode) or r7 (THUMB mode). A callee only saves the frame pointer of its
-// mode in a fixed location on its stack frame. If the caller is a different
-// mode, there is no easy way to find the frame pointer. It can either be
-// still in the designated register or saved on stack along with other callee
-// saved registers.
-
-// Given a pointer to a stack frame, locate and return the calling
-// stackframe, or return nullptr if no stackframe can be found. Perform sanity
-// checks (the strictness of which is controlled by the boolean parameter
-// "STRICT_UNWINDING") to reduce the chance that a bad pointer is returned.
-template<bool STRICT_UNWINDING>
-static void **NextStackFrame(void **old_sp) {
- void **new_sp = (void**) old_sp[-1];
-
- // Check that the transition from frame pointer old_sp to frame
- // pointer new_sp isn't clearly bogus
- if (STRICT_UNWINDING) {
- // With the stack growing downwards, older stack frame must be
- // at a greater address that the current one.
- if (new_sp <= old_sp) return nullptr;
- // Assume stack frames larger than 100,000 bytes are bogus.
- if ((uintptr_t)new_sp - (uintptr_t)old_sp > 100000) return nullptr;
- } else {
- // In the non-strict mode, allow discontiguous stack frames.
- // (alternate-signal-stacks for example).
- if (new_sp == old_sp) return nullptr;
- // And allow frames upto about 1MB.
- if ((new_sp > old_sp)
- && ((uintptr_t)new_sp - (uintptr_t)old_sp > 1000000)) return nullptr;
- }
- if ((uintptr_t)new_sp & (sizeof(void *) - 1)) return nullptr;
- return new_sp;
-}
-
-// This ensures that absl::GetStackTrace sets up the Link Register properly.
-#ifdef __GNUC__
-void StacktraceArmDummyFunction() __attribute__((noinline));
-void StacktraceArmDummyFunction() { __asm__ volatile(""); }
-#else
-# error StacktraceArmDummyFunction() needs to be ported to this platform.
-#endif
-
-template <bool IS_STACK_FRAMES, bool IS_WITH_CONTEXT>
-static int UnwindImpl(void** result, int* sizes, int max_depth, int skip_count,
- const void * /* ucp */, int *min_dropped_frames) {
-#ifdef __GNUC__
- void **sp = reinterpret_cast<void**>(__builtin_frame_address(0));
-#else
-# error reading stack point not yet supported on this platform.
-#endif
-
- // On ARM, the return address is stored in the link register (r14).
- // This is not saved on the stack frame of a leaf function. To
- // simplify code that reads return addresses, we call a dummy
- // function so that the return address of this function is also
- // stored in the stack frame. This works at least for gcc.
- StacktraceArmDummyFunction();
-
- int n = 0;
- while (sp && n < max_depth) {
- // The absl::GetStackFrames routine is called when we are in some
- // informational context (the failure signal handler for example).
- // Use the non-strict unwinding rules to produce a stack trace
- // that is as complete as possible (even if it contains a few bogus
- // entries in some rare cases).
- void **next_sp = NextStackFrame<!IS_STACK_FRAMES>(sp);
-
- if (skip_count > 0) {
- skip_count--;
- } else {
- result[n] = *sp;
-
- if (IS_STACK_FRAMES) {
- if (next_sp > sp) {
- sizes[n] = (uintptr_t)next_sp - (uintptr_t)sp;
- } else {
- // A frame-size of 0 is used to indicate unknown frame size.
- sizes[n] = 0;
- }
- }
- n++;
- }
- sp = next_sp;
- }
- if (min_dropped_frames != nullptr) {
- // Implementation detail: we clamp the max of frames we are willing to
- // count, so as not to spend too much time in the loop below.
- const int kMaxUnwind = 200;
- int num_dropped_frames = 0;
- for (int j = 0; sp != nullptr && j < kMaxUnwind; j++) {
- if (skip_count > 0) {
- skip_count--;
- } else {
- num_dropped_frames++;
- }
- sp = NextStackFrame<!IS_STACK_FRAMES>(sp);
- }
- *min_dropped_frames = num_dropped_frames;
- }
- return n;
-}
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace debugging_internal {
-bool StackTraceWorksForTest() {
- return false;
-}
-} // namespace debugging_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_DEBUGGING_INTERNAL_STACKTRACE_ARM_INL_H_
diff --git a/third_party/abseil-cpp/absl/debugging/internal/stacktrace_config.h b/third_party/abseil-cpp/absl/debugging/internal/stacktrace_config.h
deleted file mode 100644
index 3929b1b..0000000
--- a/third_party/abseil-cpp/absl/debugging/internal/stacktrace_config.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright 2017 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.
-
- * Defines ABSL_STACKTRACE_INL_HEADER to the *-inl.h containing
- * actual unwinder implementation.
- * This header is "private" to stacktrace.cc.
- * DO NOT include it into any other files.
-*/
-#ifndef ABSL_DEBUGGING_INTERNAL_STACKTRACE_CONFIG_H_
-#define ABSL_DEBUGGING_INTERNAL_STACKTRACE_CONFIG_H_
-
-#include "absl/base/config.h"
-
-#if defined(ABSL_STACKTRACE_INL_HEADER)
-#error ABSL_STACKTRACE_INL_HEADER cannot be directly set
-
-#elif defined(_WIN32)
-#define ABSL_STACKTRACE_INL_HEADER \
- "absl/debugging/internal/stacktrace_win32-inl.inc"
-
-#elif defined(__APPLE__)
-#ifdef ABSL_HAVE_THREAD_LOCAL
-// Thread local support required for UnwindImpl.
-#define ABSL_STACKTRACE_INL_HEADER \
- "absl/debugging/internal/stacktrace_generic-inl.inc"
-#endif // defined(ABSL_HAVE_THREAD_LOCAL)
-
-// Emscripten stacktraces rely on JS. Do not use them in standalone mode.
-#elif defined(__EMSCRIPTEN__) && !defined(STANDALONE_WASM)
-#define ABSL_STACKTRACE_INL_HEADER \
- "absl/debugging/internal/stacktrace_emscripten-inl.inc"
-
-#elif defined(__linux__) && !defined(__ANDROID__)
-
-#if defined(NO_FRAME_POINTER) && \
- (defined(__i386__) || defined(__x86_64__) || defined(__aarch64__))
-// Note: The libunwind-based implementation is not available to open-source
-// users.
-#define ABSL_STACKTRACE_INL_HEADER \
- "absl/debugging/internal/stacktrace_libunwind-inl.inc"
-#define STACKTRACE_USES_LIBUNWIND 1
-#elif defined(NO_FRAME_POINTER) && defined(__has_include)
-#if __has_include(<execinfo.h>)
-// Note: When using glibc this may require -funwind-tables to function properly.
-#define ABSL_STACKTRACE_INL_HEADER \
- "absl/debugging/internal/stacktrace_generic-inl.inc"
-#endif // __has_include(<execinfo.h>)
-#elif defined(__i386__) || defined(__x86_64__)
-#define ABSL_STACKTRACE_INL_HEADER \
- "absl/debugging/internal/stacktrace_x86-inl.inc"
-#elif defined(__ppc__) || defined(__PPC__)
-#define ABSL_STACKTRACE_INL_HEADER \
- "absl/debugging/internal/stacktrace_powerpc-inl.inc"
-#elif defined(__aarch64__)
-#define ABSL_STACKTRACE_INL_HEADER \
- "absl/debugging/internal/stacktrace_aarch64-inl.inc"
-#elif defined(__riscv)
-#define ABSL_STACKTRACE_INL_HEADER \
- "absl/debugging/internal/stacktrace_riscv-inl.inc"
-#elif defined(__has_include)
-#if __has_include(<execinfo.h>)
-// Note: When using glibc this may require -funwind-tables to function properly.
-#define ABSL_STACKTRACE_INL_HEADER \
- "absl/debugging/internal/stacktrace_generic-inl.inc"
-#endif // __has_include(<execinfo.h>)
-#endif // defined(__has_include)
-
-#endif // defined(__linux__) && !defined(__ANDROID__)
-
-// Fallback to the empty implementation.
-#if !defined(ABSL_STACKTRACE_INL_HEADER)
-#define ABSL_STACKTRACE_INL_HEADER \
- "absl/debugging/internal/stacktrace_unimplemented-inl.inc"
-#endif
-
-#endif // ABSL_DEBUGGING_INTERNAL_STACKTRACE_CONFIG_H_
diff --git a/third_party/abseil-cpp/absl/debugging/internal/stacktrace_emscripten-inl.inc b/third_party/abseil-cpp/absl/debugging/internal/stacktrace_emscripten-inl.inc
deleted file mode 100644
index 0f44451..0000000
--- a/third_party/abseil-cpp/absl/debugging/internal/stacktrace_emscripten-inl.inc
+++ /dev/null
@@ -1,110 +0,0 @@
-// Copyright 2017 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.
-//
-// Portable implementation - just use glibc
-//
-// Note: The glibc implementation may cause a call to malloc.
-// This can cause a deadlock in HeapProfiler.
-
-#ifndef ABSL_DEBUGGING_INTERNAL_STACKTRACE_EMSCRIPTEN_INL_H_
-#define ABSL_DEBUGGING_INTERNAL_STACKTRACE_EMSCRIPTEN_INL_H_
-
-#include <emscripten.h>
-
-#include <atomic>
-#include <cstring>
-
-#include "absl/base/attributes.h"
-#include "absl/debugging/stacktrace.h"
-
-extern "C" {
-uintptr_t emscripten_stack_snapshot();
-uint32_t emscripten_stack_unwind_buffer(uintptr_t pc, void *buffer,
- uint32_t depth);
-}
-
-// Sometimes, we can try to get a stack trace from within a stack
-// trace, which can cause a self-deadlock.
-// Protect against such reentrant call by failing to get a stack trace.
-//
-// We use __thread here because the code here is extremely low level -- it is
-// called while collecting stack traces from within malloc and mmap, and thus
-// can not call anything which might call malloc or mmap itself.
-static __thread int recursive = 0;
-
-// The stack trace function might be invoked very early in the program's
-// execution (e.g. from the very first malloc).
-// As such, we suppress usage of backtrace during this early stage of execution.
-static std::atomic<bool> disable_stacktraces(true); // Disabled until healthy.
-// Waiting until static initializers run seems to be late enough.
-// This file is included into stacktrace.cc so this will only run once.
-ABSL_ATTRIBUTE_UNUSED static int stacktraces_enabler = []() {
- // Check if we can even create stacktraces. If not, bail early and leave
- // disable_stacktraces set as-is.
- // clang-format off
- if (!EM_ASM_INT({ return (typeof wasmOffsetConverter !== 'undefined'); })) {
- return 0;
- }
- // clang-format on
- disable_stacktraces.store(false, std::memory_order_relaxed);
- return 0;
-}();
-
-template <bool IS_STACK_FRAMES, bool IS_WITH_CONTEXT>
-static int UnwindImpl(void **result, int *sizes, int max_depth, int skip_count,
- const void *ucp, int *min_dropped_frames) {
- if (recursive || disable_stacktraces.load(std::memory_order_relaxed)) {
- return 0;
- }
- ++recursive;
-
- static_cast<void>(ucp); // Unused.
- constexpr int kStackLength = 64;
- void *stack[kStackLength];
-
- int size;
- uintptr_t pc = emscripten_stack_snapshot();
- size = emscripten_stack_unwind_buffer(pc, stack, kStackLength);
-
- int result_count = size - skip_count;
- if (result_count < 0) result_count = 0;
- if (result_count > max_depth) result_count = max_depth;
- for (int i = 0; i < result_count; i++) result[i] = stack[i + skip_count];
-
- if (IS_STACK_FRAMES) {
- // No implementation for finding out the stack frame sizes yet.
- memset(sizes, 0, sizeof(*sizes) * result_count);
- }
- if (min_dropped_frames != nullptr) {
- if (size - skip_count - max_depth > 0) {
- *min_dropped_frames = size - skip_count - max_depth;
- } else {
- *min_dropped_frames = 0;
- }
- }
-
- --recursive;
-
- return result_count;
-}
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace debugging_internal {
-bool StackTraceWorksForTest() { return true; }
-} // namespace debugging_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_DEBUGGING_INTERNAL_STACKTRACE_EMSCRIPTEN_INL_H_
diff --git a/third_party/abseil-cpp/absl/debugging/internal/stacktrace_generic-inl.inc b/third_party/abseil-cpp/absl/debugging/internal/stacktrace_generic-inl.inc
deleted file mode 100644
index b500aa3..0000000
--- a/third_party/abseil-cpp/absl/debugging/internal/stacktrace_generic-inl.inc
+++ /dev/null
@@ -1,97 +0,0 @@
-// Copyright 2017 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.
-//
-// Portable implementation - just use glibc
-//
-// Note: The glibc implementation may cause a call to malloc.
-// This can cause a deadlock in HeapProfiler.
-
-#ifndef ABSL_DEBUGGING_INTERNAL_STACKTRACE_GENERIC_INL_H_
-#define ABSL_DEBUGGING_INTERNAL_STACKTRACE_GENERIC_INL_H_
-
-#include <execinfo.h>
-#include <atomic>
-#include <cstring>
-
-#include "absl/debugging/stacktrace.h"
-#include "absl/base/attributes.h"
-
-// Sometimes, we can try to get a stack trace from within a stack
-// trace, because we don't block signals inside this code (which would be too
-// expensive: the two extra system calls per stack trace do matter here).
-// That can cause a self-deadlock.
-// Protect against such reentrant call by failing to get a stack trace.
-//
-// We use __thread here because the code here is extremely low level -- it is
-// called while collecting stack traces from within malloc and mmap, and thus
-// can not call anything which might call malloc or mmap itself.
-static __thread int recursive = 0;
-
-// The stack trace function might be invoked very early in the program's
-// execution (e.g. from the very first malloc if using tcmalloc). Also, the
-// glibc implementation itself will trigger malloc the first time it is called.
-// As such, we suppress usage of backtrace during this early stage of execution.
-static std::atomic<bool> disable_stacktraces(true); // Disabled until healthy.
-
-template <bool IS_STACK_FRAMES, bool IS_WITH_CONTEXT>
-static int UnwindImpl(void** result, int* sizes, int max_depth, int skip_count,
- const void *ucp, int *min_dropped_frames) {
- if (recursive || disable_stacktraces.load(std::memory_order_relaxed)) {
- return 0;
- }
- ++recursive;
-
- static_cast<void>(ucp); // Unused.
- static const int kStackLength = 64;
- void * stack[kStackLength];
- int size;
-
- size = backtrace(stack, kStackLength);
- skip_count++; // we want to skip the current frame as well
- int result_count = size - skip_count;
- if (result_count < 0)
- result_count = 0;
- if (result_count > max_depth)
- result_count = max_depth;
- for (int i = 0; i < result_count; i++)
- result[i] = stack[i + skip_count];
-
- if (IS_STACK_FRAMES) {
- // No implementation for finding out the stack frame sizes yet.
- memset(sizes, 0, sizeof(*sizes) * static_cast<size_t>(result_count));
- }
- if (min_dropped_frames != nullptr) {
- if (size - skip_count - max_depth > 0) {
- *min_dropped_frames = size - skip_count - max_depth;
- } else {
- *min_dropped_frames = 0;
- }
- }
-
- --recursive;
-
- return result_count;
-}
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace debugging_internal {
-bool StackTraceWorksForTest() {
- return false;
-}
-} // namespace debugging_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_DEBUGGING_INTERNAL_STACKTRACE_GENERIC_INL_H_
diff --git a/third_party/abseil-cpp/absl/debugging/internal/stacktrace_powerpc-inl.inc b/third_party/abseil-cpp/absl/debugging/internal/stacktrace_powerpc-inl.inc
deleted file mode 100644
index 085cef6..0000000
--- a/third_party/abseil-cpp/absl/debugging/internal/stacktrace_powerpc-inl.inc
+++ /dev/null
@@ -1,258 +0,0 @@
-// Copyright 2017 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.
-//
-// Produce stack trace. I'm guessing (hoping!) the code is much like
-// for x86. For apple machines, at least, it seems to be; see
-// https://developer.apple.com/documentation/mac/runtimehtml/RTArch-59.html
-// https://www.linux-foundation.org/spec/ELF/ppc64/PPC-elf64abi-1.9.html#STACK
-// Linux has similar code: http://patchwork.ozlabs.org/linuxppc/patch?id=8882
-
-#ifndef ABSL_DEBUGGING_INTERNAL_STACKTRACE_POWERPC_INL_H_
-#define ABSL_DEBUGGING_INTERNAL_STACKTRACE_POWERPC_INL_H_
-
-#if defined(__linux__)
-#include <asm/ptrace.h> // for PT_NIP.
-#include <ucontext.h> // for ucontext_t
-#endif
-
-#include <unistd.h>
-#include <cassert>
-#include <cstdint>
-#include <cstdio>
-
-#include "absl/base/attributes.h"
-#include "absl/base/optimization.h"
-#include "absl/base/port.h"
-#include "absl/debugging/stacktrace.h"
-#include "absl/debugging/internal/address_is_readable.h"
-#include "absl/debugging/internal/vdso_support.h" // a no-op on non-elf or non-glibc systems
-
-// Given a stack pointer, return the saved link register value.
-// Note that this is the link register for a callee.
-static inline void *StacktracePowerPCGetLR(void **sp) {
- // PowerPC has 3 main ABIs, which say where in the stack the
- // Link Register is. For DARWIN and AIX (used by apple and
- // linux ppc64), it's in sp[2]. For SYSV (used by linux ppc),
- // it's in sp[1].
-#if defined(_CALL_AIX) || defined(_CALL_DARWIN)
- return *(sp+2);
-#elif defined(_CALL_SYSV)
- return *(sp+1);
-#elif defined(__APPLE__) || defined(__FreeBSD__) || \
- (defined(__linux__) && defined(__PPC64__))
- // This check is in case the compiler doesn't define _CALL_AIX/etc.
- return *(sp+2);
-#elif defined(__linux)
- // This check is in case the compiler doesn't define _CALL_SYSV.
- return *(sp+1);
-#else
-#error Need to specify the PPC ABI for your archiecture.
-#endif
-}
-
-// Given a pointer to a stack frame, locate and return the calling
-// stackframe, or return null if no stackframe can be found. Perform sanity
-// checks (the strictness of which is controlled by the boolean parameter
-// "STRICT_UNWINDING") to reduce the chance that a bad pointer is returned.
-template<bool STRICT_UNWINDING, bool IS_WITH_CONTEXT>
-ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS // May read random elements from stack.
-ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY // May read random elements from stack.
-static void **NextStackFrame(void **old_sp, const void *uc) {
- void **new_sp = (void **) *old_sp;
- enum { kStackAlignment = 16 };
-
- // Check that the transition from frame pointer old_sp to frame
- // pointer new_sp isn't clearly bogus
- if (STRICT_UNWINDING) {
- // With the stack growing downwards, older stack frame must be
- // at a greater address that the current one.
- if (new_sp <= old_sp) return nullptr;
- // Assume stack frames larger than 100,000 bytes are bogus.
- if ((uintptr_t)new_sp - (uintptr_t)old_sp > 100000) return nullptr;
- } else {
- // In the non-strict mode, allow discontiguous stack frames.
- // (alternate-signal-stacks for example).
- if (new_sp == old_sp) return nullptr;
- // And allow frames upto about 1MB.
- if ((new_sp > old_sp)
- && ((uintptr_t)new_sp - (uintptr_t)old_sp > 1000000)) return nullptr;
- }
- if ((uintptr_t)new_sp % kStackAlignment != 0) return nullptr;
-
-#if defined(__linux__)
- enum StackTraceKernelSymbolStatus {
- kNotInitialized = 0, kAddressValid, kAddressInvalid };
-
- if (IS_WITH_CONTEXT && uc != nullptr) {
- static StackTraceKernelSymbolStatus kernel_symbol_status =
- kNotInitialized; // Sentinel: not computed yet.
- // Initialize with sentinel value: __kernel_rt_sigtramp_rt64 can not
- // possibly be there.
- static const unsigned char *kernel_sigtramp_rt64_address = nullptr;
- if (kernel_symbol_status == kNotInitialized) {
- absl::debugging_internal::VDSOSupport vdso;
- if (vdso.IsPresent()) {
- absl::debugging_internal::VDSOSupport::SymbolInfo
- sigtramp_rt64_symbol_info;
- if (!vdso.LookupSymbol(
- "__kernel_sigtramp_rt64", "LINUX_2.6.15",
- absl::debugging_internal::VDSOSupport::kVDSOSymbolType,
- &sigtramp_rt64_symbol_info) ||
- sigtramp_rt64_symbol_info.address == nullptr) {
- // Unexpected: VDSO is present, yet the expected symbol is missing
- // or null.
- assert(false && "VDSO is present, but doesn't have expected symbol");
- kernel_symbol_status = kAddressInvalid;
- } else {
- kernel_sigtramp_rt64_address =
- reinterpret_cast<const unsigned char *>(
- sigtramp_rt64_symbol_info.address);
- kernel_symbol_status = kAddressValid;
- }
- } else {
- kernel_symbol_status = kAddressInvalid;
- }
- }
-
- if (new_sp != nullptr &&
- kernel_symbol_status == kAddressValid &&
- StacktracePowerPCGetLR(new_sp) == kernel_sigtramp_rt64_address) {
- const ucontext_t* signal_context =
- reinterpret_cast<const ucontext_t*>(uc);
- void **const sp_before_signal =
-#if defined(__PPC64__)
- reinterpret_cast<void **>(signal_context->uc_mcontext.gp_regs[PT_R1]);
-#else
- reinterpret_cast<void **>(
- signal_context->uc_mcontext.uc_regs->gregs[PT_R1]);
-#endif
- // Check that alleged sp before signal is nonnull and is reasonably
- // aligned.
- if (sp_before_signal != nullptr &&
- ((uintptr_t)sp_before_signal % kStackAlignment) == 0) {
- // Check that alleged stack pointer is actually readable. This is to
- // prevent a "double fault" in case we hit the first fault due to e.g.
- // a stack corruption.
- if (absl::debugging_internal::AddressIsReadable(sp_before_signal)) {
- // Alleged stack pointer is readable, use it for further unwinding.
- new_sp = sp_before_signal;
- }
- }
- }
- }
-#endif
-
- return new_sp;
-}
-
-// This ensures that absl::GetStackTrace sets up the Link Register properly.
-ABSL_ATTRIBUTE_NOINLINE static void AbslStacktracePowerPCDummyFunction() {
- ABSL_BLOCK_TAIL_CALL_OPTIMIZATION();
-}
-
-template <bool IS_STACK_FRAMES, bool IS_WITH_CONTEXT>
-ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS // May read random elements from stack.
-ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY // May read random elements from stack.
-static int UnwindImpl(void** result, int* sizes, int max_depth, int skip_count,
- const void *ucp, int *min_dropped_frames) {
- void **sp;
- // Apple macOS uses an old version of gnu as -- both Darwin 7.9.0 (Panther)
- // and Darwin 8.8.1 (Tiger) use as 1.38. This means we have to use a
- // different asm syntax. I don't know quite the best way to discriminate
- // systems using the old as from the new one; I've gone with __APPLE__.
-#ifdef __APPLE__
- __asm__ volatile ("mr %0,r1" : "=r" (sp));
-#else
- __asm__ volatile ("mr %0,1" : "=r" (sp));
-#endif
-
- // On PowerPC, the "Link Register" or "Link Record" (LR), is a stack
- // entry that holds the return address of the subroutine call (what
- // instruction we run after our function finishes). This is the
- // same as the stack-pointer of our parent routine, which is what we
- // want here. While the compiler will always(?) set up LR for
- // subroutine calls, it may not for leaf functions (such as this one).
- // This routine forces the compiler (at least gcc) to push it anyway.
- AbslStacktracePowerPCDummyFunction();
-
- // The LR save area is used by the callee, so the top entry is bogus.
- skip_count++;
-
- int n = 0;
-
- // Unlike ABIs of X86 and ARM, PowerPC ABIs say that return address (in
- // the link register) of a function call is stored in the caller's stack
- // frame instead of the callee's. When we look for the return address
- // associated with a stack frame, we need to make sure that there is a
- // caller frame before it. So we call NextStackFrame before entering the
- // loop below and check next_sp instead of sp for loop termination.
- // The outermost frame is set up by runtimes and it does not have a
- // caller frame, so it is skipped.
-
- // The absl::GetStackFrames routine is called when we are in some
- // informational context (the failure signal handler for example).
- // Use the non-strict unwinding rules to produce a stack trace
- // that is as complete as possible (even if it contains a few
- // bogus entries in some rare cases).
- void **next_sp = NextStackFrame<!IS_STACK_FRAMES, IS_WITH_CONTEXT>(sp, ucp);
-
- while (next_sp && n < max_depth) {
- if (skip_count > 0) {
- skip_count--;
- } else {
- result[n] = StacktracePowerPCGetLR(sp);
- if (IS_STACK_FRAMES) {
- if (next_sp > sp) {
- sizes[n] = (uintptr_t)next_sp - (uintptr_t)sp;
- } else {
- // A frame-size of 0 is used to indicate unknown frame size.
- sizes[n] = 0;
- }
- }
- n++;
- }
-
- sp = next_sp;
- next_sp = NextStackFrame<!IS_STACK_FRAMES, IS_WITH_CONTEXT>(sp, ucp);
- }
-
- if (min_dropped_frames != nullptr) {
- // Implementation detail: we clamp the max of frames we are willing to
- // count, so as not to spend too much time in the loop below.
- const int kMaxUnwind = 1000;
- int num_dropped_frames = 0;
- for (int j = 0; next_sp != nullptr && j < kMaxUnwind; j++) {
- if (skip_count > 0) {
- skip_count--;
- } else {
- num_dropped_frames++;
- }
- next_sp = NextStackFrame<!IS_STACK_FRAMES, IS_WITH_CONTEXT>(next_sp, ucp);
- }
- *min_dropped_frames = num_dropped_frames;
- }
- return n;
-}
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace debugging_internal {
-bool StackTraceWorksForTest() {
- return true;
-}
-} // namespace debugging_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_DEBUGGING_INTERNAL_STACKTRACE_POWERPC_INL_H_
diff --git a/third_party/abseil-cpp/absl/debugging/internal/stacktrace_riscv-inl.inc b/third_party/abseil-cpp/absl/debugging/internal/stacktrace_riscv-inl.inc
deleted file mode 100644
index 20183fa..0000000
--- a/third_party/abseil-cpp/absl/debugging/internal/stacktrace_riscv-inl.inc
+++ /dev/null
@@ -1,191 +0,0 @@
-// Copyright 2021 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_DEBUGGING_INTERNAL_STACKTRACE_RISCV_INL_H_
-#define ABSL_DEBUGGING_INTERNAL_STACKTRACE_RISCV_INL_H_
-
-// Generate stack trace for riscv
-
-#include <sys/ucontext.h>
-
-#include "absl/base/config.h"
-#if defined(__linux__)
-#include <sys/mman.h>
-#include <ucontext.h>
-#include <unistd.h>
-#endif
-
-#include <atomic>
-#include <cassert>
-#include <cstdint>
-#include <iostream>
-#include <limits>
-#include <utility>
-
-#include "absl/base/attributes.h"
-#include "absl/debugging/stacktrace.h"
-
-static const uintptr_t kUnknownFrameSize = 0;
-
-// Compute the size of a stack frame in [low..high). We assume that low < high.
-// Return size of kUnknownFrameSize.
-template <typename T>
-static inline uintptr_t ComputeStackFrameSize(const T *low, const T *high) {
- const char *low_char_ptr = reinterpret_cast<const char *>(low);
- const char *high_char_ptr = reinterpret_cast<const char *>(high);
- return low < high ? high_char_ptr - low_char_ptr : kUnknownFrameSize;
-}
-
-// Given a pointer to a stack frame, locate and return the calling stackframe,
-// or return null if no stackframe can be found. Perform sanity checks (the
-// strictness of which is controlled by the boolean parameter
-// "STRICT_UNWINDING") to reduce the chance that a bad pointer is returned.
-template <bool STRICT_UNWINDING, bool WITH_CONTEXT>
-ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS // May read random elements from stack.
-ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY // May read random elements from stack.
-static void ** NextStackFrame(void **old_frame_pointer, const void *uc,
- const std::pair<size_t, size_t> range) {
- // .
- // .
- // .
- // +-> +----------------+
- // | | return address |
- // | | previous fp |
- // | | ... |
- // | +----------------+ <-+
- // | | return address | |
- // +---|- previous fp | |
- // | ... | |
- // $fp ->|----------------+ |
- // | return address | |
- // | previous fp -|---+
- // $sp ->| ... |
- // +----------------+
- void **new_frame_pointer = reinterpret_cast<void **>(old_frame_pointer[-2]);
- uintptr_t frame_pointer = reinterpret_cast<uintptr_t>(new_frame_pointer);
-
- // The RISCV ELF psABI mandates that the stack pointer is always 16-byte
- // aligned.
- // TODO(#1236) this doesn't hold for ILP32E which only mandates a 4-byte
- // alignment.
- if (frame_pointer & 15)
- return nullptr;
-
- // If the new frame pointer matches the signal context, avoid terminating
- // early to deal with alternate signal stacks.
- if (WITH_CONTEXT)
- if (const ucontext_t *ucv = static_cast<const ucontext_t *>(uc))
- // RISCV ELF psABI has the frame pointer at x8/fp/s0.
- // -- RISCV psABI Table 18.2
- if (ucv->uc_mcontext.__gregs[8] == frame_pointer)
- return new_frame_pointer;
-
- // Check frame size. In strict mode, we assume frames to be under 100,000
- // bytes. In non-strict mode, we relax the limit to 1MB.
- const uintptr_t max_size = STRICT_UNWINDING ? 100000 : 1000000;
- const uintptr_t frame_size =
- ComputeStackFrameSize(old_frame_pointer, new_frame_pointer);
- if (frame_size == kUnknownFrameSize) {
- if (STRICT_UNWINDING)
- return nullptr;
-
- // In non-strict mode permit non-contiguous stacks (e.g. alternate signal
- // frame handling).
- if (reinterpret_cast<uintptr_t>(new_frame_pointer) < range.first ||
- reinterpret_cast<uintptr_t>(new_frame_pointer) > range.second)
- return nullptr;
- }
-
- if (frame_size > max_size)
- return nullptr;
-
- return new_frame_pointer;
-}
-
-template <bool IS_STACK_FRAMES, bool IS_WITH_CONTEXT>
-ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS // May read random elements from stack.
-ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY // May read random elements from stack.
-static int UnwindImpl(void **result, int *sizes, int max_depth, int skip_count,
- const void *ucp, int *min_dropped_frames) {
- // The `frame_pointer` that is computed here points to the top of the frame.
- // The two words preceding the address are the return address and the previous
- // frame pointer.
-#if defined(__GNUC__)
- void **frame_pointer = reinterpret_cast<void **>(__builtin_frame_address(0));
-#else
-#error reading stack pointer not yet supported on this platform
-#endif
-
- std::pair<size_t, size_t> stack = {
- // assume that the first page is not the stack.
- static_cast<size_t>(sysconf(_SC_PAGESIZE)),
- std::numeric_limits<size_t>::max() - sizeof(void *)
- };
-
- int n = 0;
- void *return_address = nullptr;
- while (frame_pointer && n < max_depth) {
- return_address = frame_pointer[-1];
-
- // The absl::GetStackFrames routine is called when we are in some
- // informational context (the failure signal handler for example). Use the
- // non-strict unwinding rules to produce a stack trace that is as complete
- // as possible (even if it contains a few bogus entries in some rare cases).
- void **next_frame_pointer =
- NextStackFrame<!IS_STACK_FRAMES, IS_WITH_CONTEXT>(frame_pointer, ucp,
- stack);
-
- if (skip_count > 0) {
- skip_count--;
- } else {
- result[n] = return_address;
- if (IS_STACK_FRAMES) {
- sizes[n] = ComputeStackFrameSize(frame_pointer, next_frame_pointer);
- }
- n++;
- }
-
- frame_pointer = next_frame_pointer;
- }
-
- if (min_dropped_frames != nullptr) {
- // Implementation detail: we clamp the max of frames we are willing to
- // count, so as not to spend too much time in the loop below.
- const int kMaxUnwind = 200;
- int num_dropped_frames = 0;
- for (int j = 0; frame_pointer != nullptr && j < kMaxUnwind; j++) {
- if (skip_count > 0) {
- skip_count--;
- } else {
- num_dropped_frames++;
- }
- frame_pointer =
- NextStackFrame<!IS_STACK_FRAMES, IS_WITH_CONTEXT>(frame_pointer, ucp,
- stack);
- }
- *min_dropped_frames = num_dropped_frames;
- }
-
- return n;
-}
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace debugging_internal {
-bool StackTraceWorksForTest() { return true; }
-} // namespace debugging_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif
diff --git a/third_party/abseil-cpp/absl/debugging/internal/stacktrace_unimplemented-inl.inc b/third_party/abseil-cpp/absl/debugging/internal/stacktrace_unimplemented-inl.inc
deleted file mode 100644
index 5b8fb19..0000000
--- a/third_party/abseil-cpp/absl/debugging/internal/stacktrace_unimplemented-inl.inc
+++ /dev/null
@@ -1,24 +0,0 @@
-#ifndef ABSL_DEBUGGING_INTERNAL_STACKTRACE_UNIMPLEMENTED_INL_H_
-#define ABSL_DEBUGGING_INTERNAL_STACKTRACE_UNIMPLEMENTED_INL_H_
-
-template <bool IS_STACK_FRAMES, bool IS_WITH_CONTEXT>
-static int UnwindImpl(void** /* result */, int* /* sizes */,
- int /* max_depth */, int /* skip_count */,
- const void* /* ucp */, int *min_dropped_frames) {
- if (min_dropped_frames != nullptr) {
- *min_dropped_frames = 0;
- }
- return 0;
-}
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace debugging_internal {
-bool StackTraceWorksForTest() {
- return false;
-}
-} // namespace debugging_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_DEBUGGING_INTERNAL_STACKTRACE_UNIMPLEMENTED_INL_H_
diff --git a/third_party/abseil-cpp/absl/debugging/internal/stacktrace_win32-inl.inc b/third_party/abseil-cpp/absl/debugging/internal/stacktrace_win32-inl.inc
deleted file mode 100644
index ef2b973..0000000
--- a/third_party/abseil-cpp/absl/debugging/internal/stacktrace_win32-inl.inc
+++ /dev/null
@@ -1,94 +0,0 @@
-// Copyright 2017 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.
-//
-// Produces a stack trace for Windows. Normally, one could use
-// stacktrace_x86-inl.h or stacktrace_x86_64-inl.h -- and indeed, that
-// should work for binaries compiled using MSVC in "debug" mode.
-// However, in "release" mode, Windows uses frame-pointer
-// optimization, which makes getting a stack trace very difficult.
-//
-// There are several approaches one can take. One is to use Windows
-// intrinsics like StackWalk64. These can work, but have restrictions
-// on how successful they can be. Another attempt is to write a
-// version of stacktrace_x86-inl.h that has heuristic support for
-// dealing with FPO, similar to what WinDbg does (see
-// http://www.nynaeve.net/?p=97). There are (non-working) examples of
-// these approaches, complete with TODOs, in stacktrace_win32-inl.h#1
-//
-// The solution we've ended up doing is to call the undocumented
-// windows function RtlCaptureStackBackTrace, which probably doesn't
-// work with FPO but at least is fast, and doesn't require a symbol
-// server.
-//
-// This code is inspired by a patch from David Vitek:
-// https://code.google.com/p/google-perftools/issues/detail?id=83
-
-#ifndef ABSL_DEBUGGING_INTERNAL_STACKTRACE_WIN32_INL_H_
-#define ABSL_DEBUGGING_INTERNAL_STACKTRACE_WIN32_INL_H_
-
-#include <windows.h> // for GetProcAddress and GetModuleHandle
-#include <cassert>
-
-typedef USHORT NTAPI RtlCaptureStackBackTrace_Function(
- IN ULONG frames_to_skip,
- IN ULONG frames_to_capture,
- OUT PVOID *backtrace,
- OUT PULONG backtrace_hash);
-
-// It is not possible to load RtlCaptureStackBackTrace at static init time in
-// UWP. CaptureStackBackTrace is the public version of RtlCaptureStackBackTrace
-#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) && \
- !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
-static RtlCaptureStackBackTrace_Function* const RtlCaptureStackBackTrace_fn =
- &::CaptureStackBackTrace;
-#else
-// Load the function we need at static init time, where we don't have
-// to worry about someone else holding the loader's lock.
-static RtlCaptureStackBackTrace_Function* const RtlCaptureStackBackTrace_fn =
- (RtlCaptureStackBackTrace_Function*)GetProcAddress(
- GetModuleHandleA("ntdll.dll"), "RtlCaptureStackBackTrace");
-#endif // WINAPI_PARTITION_APP && !WINAPI_PARTITION_DESKTOP
-
-template <bool IS_STACK_FRAMES, bool IS_WITH_CONTEXT>
-static int UnwindImpl(void** result, int* sizes, int max_depth, int skip_count,
- const void*, int* min_dropped_frames) {
- USHORT n = 0;
- if (!RtlCaptureStackBackTrace_fn || skip_count < 0 || max_depth < 0) {
- // can't get a stacktrace with no function/invalid args
- } else {
- n = RtlCaptureStackBackTrace_fn(static_cast<ULONG>(skip_count) + 2,
- static_cast<ULONG>(max_depth), result, 0);
- }
- if (IS_STACK_FRAMES) {
- // No implementation for finding out the stack frame sizes yet.
- memset(sizes, 0, sizeof(*sizes) * n);
- }
- if (min_dropped_frames != nullptr) {
- // Not implemented.
- *min_dropped_frames = 0;
- }
- return n;
-}
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace debugging_internal {
-bool StackTraceWorksForTest() {
- return false;
-}
-} // namespace debugging_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_DEBUGGING_INTERNAL_STACKTRACE_WIN32_INL_H_
diff --git a/third_party/abseil-cpp/absl/debugging/internal/stacktrace_x86-inl.inc b/third_party/abseil-cpp/absl/debugging/internal/stacktrace_x86-inl.inc
deleted file mode 100644
index 9fbfcf7..0000000
--- a/third_party/abseil-cpp/absl/debugging/internal/stacktrace_x86-inl.inc
+++ /dev/null
@@ -1,371 +0,0 @@
-// Copyright 2017 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.
-//
-// Produce stack trace
-
-#ifndef ABSL_DEBUGGING_INTERNAL_STACKTRACE_X86_INL_INC_
-#define ABSL_DEBUGGING_INTERNAL_STACKTRACE_X86_INL_INC_
-
-#if defined(__linux__) && (defined(__i386__) || defined(__x86_64__))
-#include <ucontext.h> // for ucontext_t
-#endif
-
-#if !defined(_WIN32)
-#include <unistd.h>
-#endif
-
-#include <cassert>
-#include <cstdint>
-#include <limits>
-
-#include "absl/base/macros.h"
-#include "absl/base/port.h"
-#include "absl/debugging/internal/address_is_readable.h"
-#include "absl/debugging/internal/vdso_support.h" // a no-op on non-elf or non-glibc systems
-#include "absl/debugging/stacktrace.h"
-
-using absl::debugging_internal::AddressIsReadable;
-
-#if defined(__linux__) && defined(__i386__)
-// Count "push %reg" instructions in VDSO __kernel_vsyscall(),
-// preceeding "syscall" or "sysenter".
-// If __kernel_vsyscall uses frame pointer, answer 0.
-//
-// kMaxBytes tells how many instruction bytes of __kernel_vsyscall
-// to analyze before giving up. Up to kMaxBytes+1 bytes of
-// instructions could be accessed.
-//
-// Here are known __kernel_vsyscall instruction sequences:
-//
-// SYSENTER (linux-2.6.26/arch/x86/vdso/vdso32/sysenter.S).
-// Used on Intel.
-// 0xffffe400 <__kernel_vsyscall+0>: push %ecx
-// 0xffffe401 <__kernel_vsyscall+1>: push %edx
-// 0xffffe402 <__kernel_vsyscall+2>: push %ebp
-// 0xffffe403 <__kernel_vsyscall+3>: mov %esp,%ebp
-// 0xffffe405 <__kernel_vsyscall+5>: sysenter
-//
-// SYSCALL (see linux-2.6.26/arch/x86/vdso/vdso32/syscall.S).
-// Used on AMD.
-// 0xffffe400 <__kernel_vsyscall+0>: push %ebp
-// 0xffffe401 <__kernel_vsyscall+1>: mov %ecx,%ebp
-// 0xffffe403 <__kernel_vsyscall+3>: syscall
-//
-
-// The sequence below isn't actually expected in Google fleet,
-// here only for completeness. Remove this comment from OSS release.
-
-// i386 (see linux-2.6.26/arch/x86/vdso/vdso32/int80.S)
-// 0xffffe400 <__kernel_vsyscall+0>: int $0x80
-// 0xffffe401 <__kernel_vsyscall+1>: ret
-//
-static const int kMaxBytes = 10;
-
-// We use assert()s instead of DCHECK()s -- this is too low level
-// for DCHECK().
-
-static int CountPushInstructions(const unsigned char *const addr) {
- int result = 0;
- for (int i = 0; i < kMaxBytes; ++i) {
- if (addr[i] == 0x89) {
- // "mov reg,reg"
- if (addr[i + 1] == 0xE5) {
- // Found "mov %esp,%ebp".
- return 0;
- }
- ++i; // Skip register encoding byte.
- } else if (addr[i] == 0x0F &&
- (addr[i + 1] == 0x34 || addr[i + 1] == 0x05)) {
- // Found "sysenter" or "syscall".
- return result;
- } else if ((addr[i] & 0xF0) == 0x50) {
- // Found "push %reg".
- ++result;
- } else if (addr[i] == 0xCD && addr[i + 1] == 0x80) {
- // Found "int $0x80"
- assert(result == 0);
- return 0;
- } else {
- // Unexpected instruction.
- assert(false && "unexpected instruction in __kernel_vsyscall");
- return 0;
- }
- }
- // Unexpected: didn't find SYSENTER or SYSCALL in
- // [__kernel_vsyscall, __kernel_vsyscall + kMaxBytes) interval.
- assert(false && "did not find SYSENTER or SYSCALL in __kernel_vsyscall");
- return 0;
-}
-#endif
-
-// Assume stack frames larger than 100,000 bytes are bogus.
-static const int kMaxFrameBytes = 100000;
-
-// Returns the stack frame pointer from signal context, 0 if unknown.
-// vuc is a ucontext_t *. We use void* to avoid the use
-// of ucontext_t on non-POSIX systems.
-static uintptr_t GetFP(const void *vuc) {
-#if !defined(__linux__)
- static_cast<void>(vuc); // Avoid an unused argument compiler warning.
-#else
- if (vuc != nullptr) {
- auto *uc = reinterpret_cast<const ucontext_t *>(vuc);
-#if defined(__i386__)
- const auto bp = uc->uc_mcontext.gregs[REG_EBP];
- const auto sp = uc->uc_mcontext.gregs[REG_ESP];
-#elif defined(__x86_64__)
- const auto bp = uc->uc_mcontext.gregs[REG_RBP];
- const auto sp = uc->uc_mcontext.gregs[REG_RSP];
-#else
- const uintptr_t bp = 0;
- const uintptr_t sp = 0;
-#endif
- // Sanity-check that the base pointer is valid. It's possible that some
- // code in the process is compiled with --copt=-fomit-frame-pointer or
- // --copt=-momit-leaf-frame-pointer.
- //
- // TODO(bcmills): -momit-leaf-frame-pointer is currently the default
- // behavior when building with clang. Talk to the C++ toolchain team about
- // fixing that.
- if (bp >= sp && bp - sp <= kMaxFrameBytes)
- return static_cast<uintptr_t>(bp);
-
- // If bp isn't a plausible frame pointer, return the stack pointer instead.
- // If we're lucky, it points to the start of a stack frame; otherwise, we'll
- // get one frame of garbage in the stack trace and fail the sanity check on
- // the next iteration.
- return static_cast<uintptr_t>(sp);
- }
-#endif
- return 0;
-}
-
-// Given a pointer to a stack frame, locate and return the calling
-// stackframe, or return null if no stackframe can be found. Perform sanity
-// checks (the strictness of which is controlled by the boolean parameter
-// "STRICT_UNWINDING") to reduce the chance that a bad pointer is returned.
-template <bool STRICT_UNWINDING, bool WITH_CONTEXT>
-ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS // May read random elements from stack.
-ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY // May read random elements from stack.
-static void **NextStackFrame(void **old_fp, const void *uc,
- size_t stack_low, size_t stack_high) {
- void **new_fp = (void **)*old_fp;
-
-#if defined(__linux__) && defined(__i386__)
- if (WITH_CONTEXT && uc != nullptr) {
- // How many "push %reg" instructions are there at __kernel_vsyscall?
- // This is constant for a given kernel and processor, so compute
- // it only once.
- static int num_push_instructions = -1; // Sentinel: not computed yet.
- // Initialize with sentinel value: __kernel_rt_sigreturn can not possibly
- // be there.
- static const unsigned char *kernel_rt_sigreturn_address = nullptr;
- static const unsigned char *kernel_vsyscall_address = nullptr;
- if (num_push_instructions == -1) {
-#ifdef ABSL_HAVE_VDSO_SUPPORT
- absl::debugging_internal::VDSOSupport vdso;
- if (vdso.IsPresent()) {
- absl::debugging_internal::VDSOSupport::SymbolInfo
- rt_sigreturn_symbol_info;
- absl::debugging_internal::VDSOSupport::SymbolInfo vsyscall_symbol_info;
- if (!vdso.LookupSymbol("__kernel_rt_sigreturn", "LINUX_2.5", STT_FUNC,
- &rt_sigreturn_symbol_info) ||
- !vdso.LookupSymbol("__kernel_vsyscall", "LINUX_2.5", STT_FUNC,
- &vsyscall_symbol_info) ||
- rt_sigreturn_symbol_info.address == nullptr ||
- vsyscall_symbol_info.address == nullptr) {
- // Unexpected: 32-bit VDSO is present, yet one of the expected
- // symbols is missing or null.
- assert(false && "VDSO is present, but doesn't have expected symbols");
- num_push_instructions = 0;
- } else {
- kernel_rt_sigreturn_address =
- reinterpret_cast<const unsigned char *>(
- rt_sigreturn_symbol_info.address);
- kernel_vsyscall_address =
- reinterpret_cast<const unsigned char *>(
- vsyscall_symbol_info.address);
- num_push_instructions =
- CountPushInstructions(kernel_vsyscall_address);
- }
- } else {
- num_push_instructions = 0;
- }
-#else // ABSL_HAVE_VDSO_SUPPORT
- num_push_instructions = 0;
-#endif // ABSL_HAVE_VDSO_SUPPORT
- }
- if (num_push_instructions != 0 && kernel_rt_sigreturn_address != nullptr &&
- old_fp[1] == kernel_rt_sigreturn_address) {
- const ucontext_t *ucv = static_cast<const ucontext_t *>(uc);
- // This kernel does not use frame pointer in its VDSO code,
- // and so %ebp is not suitable for unwinding.
- void **const reg_ebp =
- reinterpret_cast<void **>(ucv->uc_mcontext.gregs[REG_EBP]);
- const unsigned char *const reg_eip =
- reinterpret_cast<unsigned char *>(ucv->uc_mcontext.gregs[REG_EIP]);
- if (new_fp == reg_ebp && kernel_vsyscall_address <= reg_eip &&
- reg_eip - kernel_vsyscall_address < kMaxBytes) {
- // We "stepped up" to __kernel_vsyscall, but %ebp is not usable.
- // Restore from 'ucv' instead.
- void **const reg_esp =
- reinterpret_cast<void **>(ucv->uc_mcontext.gregs[REG_ESP]);
- // Check that alleged %esp is not null and is reasonably aligned.
- if (reg_esp &&
- ((uintptr_t)reg_esp & (sizeof(reg_esp) - 1)) == 0) {
- // Check that alleged %esp is actually readable. This is to prevent
- // "double fault" in case we hit the first fault due to e.g. stack
- // corruption.
- void *const reg_esp2 = reg_esp[num_push_instructions - 1];
- if (AddressIsReadable(reg_esp2)) {
- // Alleged %esp is readable, use it for further unwinding.
- new_fp = reinterpret_cast<void **>(reg_esp2);
- }
- }
- }
- }
- }
-#endif
-
- const uintptr_t old_fp_u = reinterpret_cast<uintptr_t>(old_fp);
- const uintptr_t new_fp_u = reinterpret_cast<uintptr_t>(new_fp);
-
- // Check that the transition from frame pointer old_fp to frame
- // pointer new_fp isn't clearly bogus. Skip the checks if new_fp
- // matches the signal context, so that we don't skip out early when
- // using an alternate signal stack.
- //
- // TODO(bcmills): The GetFP call should be completely unnecessary when
- // ENABLE_COMBINED_UNWINDER is set (because we should be back in the thread's
- // stack by this point), but it is empirically still needed (e.g. when the
- // stack includes a call to abort). unw_get_reg returns UNW_EBADREG for some
- // frames. Figure out why GetValidFrameAddr and/or libunwind isn't doing what
- // it's supposed to.
- if (STRICT_UNWINDING &&
- (!WITH_CONTEXT || uc == nullptr || new_fp_u != GetFP(uc))) {
- // With the stack growing downwards, older stack frame must be
- // at a greater address that the current one.
- if (new_fp_u <= old_fp_u) return nullptr;
- if (new_fp_u - old_fp_u > kMaxFrameBytes) return nullptr;
-
- if (stack_low < old_fp_u && old_fp_u <= stack_high) {
- // Old BP was in the expected stack region...
- if (!(stack_low < new_fp_u && new_fp_u <= stack_high)) {
- // ... but new BP is outside of expected stack region.
- // It is most likely bogus.
- return nullptr;
- }
- } else {
- // We may be here if we are executing in a co-routine with a
- // separate stack. We can't do safety checks in this case.
- }
- } else {
- if (new_fp == nullptr) return nullptr; // skip AddressIsReadable() below
- // In the non-strict mode, allow discontiguous stack frames.
- // (alternate-signal-stacks for example).
- if (new_fp == old_fp) return nullptr;
- }
-
- if (new_fp_u & (sizeof(void *) - 1)) return nullptr;
-#ifdef __i386__
- // On 32-bit machines, the stack pointer can be very close to
- // 0xffffffff, so we explicitly check for a pointer into the
- // last two pages in the address space
- if (new_fp_u >= 0xffffe000) return nullptr;
-#endif
-#if !defined(_WIN32)
- if (!STRICT_UNWINDING) {
- // Lax sanity checks cause a crash in 32-bit tcmalloc/crash_reason_test
- // on AMD-based machines with VDSO-enabled kernels.
- // Make an extra sanity check to insure new_fp is readable.
- // Note: NextStackFrame<false>() is only called while the program
- // is already on its last leg, so it's ok to be slow here.
-
- if (!AddressIsReadable(new_fp)) {
- return nullptr;
- }
- }
-#endif
- return new_fp;
-}
-
-template <bool IS_STACK_FRAMES, bool IS_WITH_CONTEXT>
-ABSL_ATTRIBUTE_NO_SANITIZE_ADDRESS // May read random elements from stack.
-ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY // May read random elements from stack.
-ABSL_ATTRIBUTE_NOINLINE
-static int UnwindImpl(void **result, int *sizes, int max_depth, int skip_count,
- const void *ucp, int *min_dropped_frames) {
- int n = 0;
- void **fp = reinterpret_cast<void **>(__builtin_frame_address(0));
-
- // Assume that the first page is not stack.
- size_t stack_low = static_cast<size_t>(getpagesize());
- size_t stack_high = std::numeric_limits<size_t>::max() - sizeof(void *);
-
- while (fp && n < max_depth) {
- if (*(fp + 1) == reinterpret_cast<void *>(0)) {
- // In 64-bit code, we often see a frame that
- // points to itself and has a return address of 0.
- break;
- }
- void **next_fp = NextStackFrame<!IS_STACK_FRAMES, IS_WITH_CONTEXT>(
- fp, ucp, stack_low, stack_high);
- if (skip_count > 0) {
- skip_count--;
- } else {
- result[n] = *(fp + 1);
- if (IS_STACK_FRAMES) {
- if (next_fp > fp) {
- sizes[n] = static_cast<int>(
- reinterpret_cast<uintptr_t>(next_fp) -
- reinterpret_cast<uintptr_t>(fp));
- } else {
- // A frame-size of 0 is used to indicate unknown frame size.
- sizes[n] = 0;
- }
- }
- n++;
- }
- fp = next_fp;
- }
- if (min_dropped_frames != nullptr) {
- // Implementation detail: we clamp the max of frames we are willing to
- // count, so as not to spend too much time in the loop below.
- const int kMaxUnwind = 1000;
- int num_dropped_frames = 0;
- for (int j = 0; fp != nullptr && j < kMaxUnwind; j++) {
- if (skip_count > 0) {
- skip_count--;
- } else {
- num_dropped_frames++;
- }
- fp = NextStackFrame<!IS_STACK_FRAMES, IS_WITH_CONTEXT>(fp, ucp, stack_low,
- stack_high);
- }
- *min_dropped_frames = num_dropped_frames;
- }
- return n;
-}
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace debugging_internal {
-bool StackTraceWorksForTest() {
- return true;
-}
-} // namespace debugging_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_DEBUGGING_INTERNAL_STACKTRACE_X86_INL_INC_
diff --git a/third_party/abseil-cpp/absl/debugging/internal/symbolize.h b/third_party/abseil-cpp/absl/debugging/internal/symbolize.h
deleted file mode 100644
index 27d5e65..0000000
--- a/third_party/abseil-cpp/absl/debugging/internal/symbolize.h
+++ /dev/null
@@ -1,153 +0,0 @@
-// Copyright 2018 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.
-
-// This file contains internal parts of the Abseil symbolizer.
-// Do not depend on the anything in this file, it may change at anytime.
-
-#ifndef ABSL_DEBUGGING_INTERNAL_SYMBOLIZE_H_
-#define ABSL_DEBUGGING_INTERNAL_SYMBOLIZE_H_
-
-#ifdef __cplusplus
-
-#include <cstddef>
-#include <cstdint>
-
-#include "absl/base/config.h"
-#include "absl/strings/string_view.h"
-
-#ifdef ABSL_INTERNAL_HAVE_ELF_SYMBOLIZE
-#error ABSL_INTERNAL_HAVE_ELF_SYMBOLIZE cannot be directly set
-#elif defined(__ELF__) && defined(__GLIBC__) && !defined(__native_client__) \
- && !defined(__asmjs__) && !defined(__wasm__)
-#define ABSL_INTERNAL_HAVE_ELF_SYMBOLIZE 1
-
-#include <elf.h>
-#include <link.h> // For ElfW() macro.
-#include <functional>
-#include <string>
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace debugging_internal {
-
-// Iterates over all sections, invoking callback on each with the section name
-// and the section header.
-//
-// Returns true on success; otherwise returns false in case of errors.
-//
-// This is not async-signal-safe.
-bool ForEachSection(int fd,
- const std::function<bool(absl::string_view name,
- const ElfW(Shdr) &)>& callback);
-
-// Gets the section header for the given name, if it exists. Returns true on
-// success. Otherwise, returns false.
-bool GetSectionHeaderByName(int fd, const char *name, size_t name_len,
- ElfW(Shdr) *out);
-
-} // namespace debugging_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_INTERNAL_HAVE_ELF_SYMBOLIZE
-
-#ifdef ABSL_INTERNAL_HAVE_DARWIN_SYMBOLIZE
-#error ABSL_INTERNAL_HAVE_DARWIN_SYMBOLIZE cannot be directly set
-#elif defined(__APPLE__)
-#define ABSL_INTERNAL_HAVE_DARWIN_SYMBOLIZE 1
-#endif
-
-#ifdef ABSL_INTERNAL_HAVE_EMSCRIPTEN_SYMBOLIZE
-#error ABSL_INTERNAL_HAVE_EMSCRIPTEN_SYMBOLIZE cannot be directly set
-#elif defined(__EMSCRIPTEN__)
-#define ABSL_INTERNAL_HAVE_EMSCRIPTEN_SYMBOLIZE 1
-#endif
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace debugging_internal {
-
-struct SymbolDecoratorArgs {
- // The program counter we are getting symbolic name for.
- const void *pc;
- // 0 for main executable, load address for shared libraries.
- ptrdiff_t relocation;
- // Read-only file descriptor for ELF image covering "pc",
- // or -1 if no such ELF image exists in /proc/self/maps.
- int fd;
- // Output buffer, size.
- // Note: the buffer may not be empty -- default symbolizer may have already
- // produced some output, and earlier decorators may have adorned it in
- // some way. You are free to replace or augment the contents (within the
- // symbol_buf_size limit).
- char *const symbol_buf;
- size_t symbol_buf_size;
- // Temporary scratch space, size.
- // Use that space in preference to allocating your own stack buffer to
- // conserve stack.
- char *const tmp_buf;
- size_t tmp_buf_size;
- // User-provided argument
- void* arg;
-};
-using SymbolDecorator = void (*)(const SymbolDecoratorArgs *);
-
-// Installs a function-pointer as a decorator. Returns a value less than zero
-// if the system cannot install the decorator. Otherwise, returns a unique
-// identifier corresponding to the decorator. This identifier can be used to
-// uninstall the decorator - See RemoveSymbolDecorator() below.
-int InstallSymbolDecorator(SymbolDecorator decorator, void* arg);
-
-// Removes a previously installed function-pointer decorator. Parameter "ticket"
-// is the return-value from calling InstallSymbolDecorator().
-bool RemoveSymbolDecorator(int ticket);
-
-// Remove all installed decorators. Returns true if successful, false if
-// symbolization is currently in progress.
-bool RemoveAllSymbolDecorators(void);
-
-// Registers an address range to a file mapping.
-//
-// Preconditions:
-// start <= end
-// filename != nullptr
-//
-// Returns true if the file was successfully registered.
-bool RegisterFileMappingHint(const void* start, const void* end,
- uint64_t offset, const char* filename);
-
-// Looks up the file mapping registered by RegisterFileMappingHint for an
-// address range. If there is one, the file name is stored in *filename and
-// *start and *end are modified to reflect the registered mapping. Returns
-// whether any hint was found.
-bool GetFileMappingHint(const void** start, const void** end, uint64_t* offset,
- const char** filename);
-
-} // namespace debugging_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // __cplusplus
-
-#include <stdbool.h>
-
-#ifdef __cplusplus
-extern "C"
-#endif // __cplusplus
-
- bool
- AbslInternalGetFileMappingHint(const void** start, const void** end,
- uint64_t* offset, const char** filename);
-
-#endif // ABSL_DEBUGGING_INTERNAL_SYMBOLIZE_H_
diff --git a/third_party/abseil-cpp/absl/debugging/internal/vdso_support.cc b/third_party/abseil-cpp/absl/debugging/internal/vdso_support.cc
deleted file mode 100644
index 8a588ea..0000000
--- a/third_party/abseil-cpp/absl/debugging/internal/vdso_support.cc
+++ /dev/null
@@ -1,205 +0,0 @@
-// Copyright 2017 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.
-
-// Allow dynamic symbol lookup in the kernel VDSO page.
-//
-// VDSOSupport -- a class representing kernel VDSO (if present).
-
-#include "absl/debugging/internal/vdso_support.h"
-
-#ifdef ABSL_HAVE_VDSO_SUPPORT // defined in vdso_support.h
-
-#if !defined(__has_include)
-#define __has_include(header) 0
-#endif
-
-#include <errno.h>
-#include <fcntl.h>
-#if __has_include(<syscall.h>)
-#include <syscall.h>
-#elif __has_include(<sys/syscall.h>)
-#include <sys/syscall.h>
-#endif
-#include <unistd.h>
-
-#if !defined(__UCLIBC__) && defined(__GLIBC__) && \
- (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
-#define ABSL_HAVE_GETAUXVAL
-#endif
-
-#ifdef ABSL_HAVE_GETAUXVAL
-#include <sys/auxv.h>
-#endif
-
-#include "absl/base/dynamic_annotations.h"
-#include "absl/base/internal/raw_logging.h"
-#include "absl/base/port.h"
-
-#ifndef AT_SYSINFO_EHDR
-#define AT_SYSINFO_EHDR 33 // for crosstoolv10
-#endif
-
-#if defined(__NetBSD__)
-using Elf32_auxv_t = Aux32Info;
-using Elf64_auxv_t = Aux64Info;
-#endif
-#if defined(__FreeBSD__)
-#if defined(__ELF_WORD_SIZE) && __ELF_WORD_SIZE == 64
-using Elf64_auxv_t = Elf64_Auxinfo;
-#endif
-using Elf32_auxv_t = Elf32_Auxinfo;
-#endif
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace debugging_internal {
-
-ABSL_CONST_INIT
-std::atomic<const void *> VDSOSupport::vdso_base_(
- debugging_internal::ElfMemImage::kInvalidBase);
-
-ABSL_CONST_INIT std::atomic<VDSOSupport::GetCpuFn> VDSOSupport::getcpu_fn_(
- &InitAndGetCPU);
-
-VDSOSupport::VDSOSupport()
- // If vdso_base_ is still set to kInvalidBase, we got here
- // before VDSOSupport::Init has been called. Call it now.
- : image_(vdso_base_.load(std::memory_order_relaxed) ==
- debugging_internal::ElfMemImage::kInvalidBase
- ? Init()
- : vdso_base_.load(std::memory_order_relaxed)) {}
-
-// NOTE: we can't use GoogleOnceInit() below, because we can be
-// called by tcmalloc, and none of the *once* stuff may be functional yet.
-//
-// In addition, we hope that the VDSOSupportHelper constructor
-// causes this code to run before there are any threads, and before
-// InitGoogle() has executed any chroot or setuid calls.
-//
-// Finally, even if there is a race here, it is harmless, because
-// the operation should be idempotent.
-const void *VDSOSupport::Init() {
- const auto kInvalidBase = debugging_internal::ElfMemImage::kInvalidBase;
-#ifdef ABSL_HAVE_GETAUXVAL
- if (vdso_base_.load(std::memory_order_relaxed) == kInvalidBase) {
- errno = 0;
- const void *const sysinfo_ehdr =
- reinterpret_cast<const void *>(getauxval(AT_SYSINFO_EHDR));
- if (errno == 0) {
- vdso_base_.store(sysinfo_ehdr, std::memory_order_relaxed);
- }
- }
-#endif // ABSL_HAVE_GETAUXVAL
- if (vdso_base_.load(std::memory_order_relaxed) == kInvalidBase) {
- int fd = open("/proc/self/auxv", O_RDONLY);
- if (fd == -1) {
- // Kernel too old to have a VDSO.
- vdso_base_.store(nullptr, std::memory_order_relaxed);
- getcpu_fn_.store(&GetCPUViaSyscall, std::memory_order_relaxed);
- return nullptr;
- }
- ElfW(auxv_t) aux;
- while (read(fd, &aux, sizeof(aux)) == sizeof(aux)) {
- if (aux.a_type == AT_SYSINFO_EHDR) {
-#if defined(__NetBSD__)
- vdso_base_.store(reinterpret_cast<void *>(aux.a_v),
- std::memory_order_relaxed);
-#else
- vdso_base_.store(reinterpret_cast<void *>(aux.a_un.a_val),
- std::memory_order_relaxed);
-#endif
- break;
- }
- }
- close(fd);
- if (vdso_base_.load(std::memory_order_relaxed) == kInvalidBase) {
- // Didn't find AT_SYSINFO_EHDR in auxv[].
- vdso_base_.store(nullptr, std::memory_order_relaxed);
- }
- }
- GetCpuFn fn = &GetCPUViaSyscall; // default if VDSO not present.
- if (vdso_base_.load(std::memory_order_relaxed)) {
- VDSOSupport vdso;
- SymbolInfo info;
- if (vdso.LookupSymbol("__vdso_getcpu", "LINUX_2.6", STT_FUNC, &info)) {
- fn = reinterpret_cast<GetCpuFn>(const_cast<void *>(info.address));
- }
- }
- // Subtle: this code runs outside of any locks; prevent compiler
- // from assigning to getcpu_fn_ more than once.
- getcpu_fn_.store(fn, std::memory_order_relaxed);
- return vdso_base_.load(std::memory_order_relaxed);
-}
-
-const void *VDSOSupport::SetBase(const void *base) {
- ABSL_RAW_CHECK(base != debugging_internal::ElfMemImage::kInvalidBase,
- "internal error");
- const void *old_base = vdso_base_.load(std::memory_order_relaxed);
- vdso_base_.store(base, std::memory_order_relaxed);
- image_.Init(base);
- // Also reset getcpu_fn_, so GetCPU could be tested with simulated VDSO.
- getcpu_fn_.store(&InitAndGetCPU, std::memory_order_relaxed);
- return old_base;
-}
-
-bool VDSOSupport::LookupSymbol(const char *name,
- const char *version,
- int type,
- SymbolInfo *info) const {
- return image_.LookupSymbol(name, version, type, info);
-}
-
-bool VDSOSupport::LookupSymbolByAddress(const void *address,
- SymbolInfo *info_out) const {
- return image_.LookupSymbolByAddress(address, info_out);
-}
-
-// NOLINT on 'long' because this routine mimics kernel api.
-long VDSOSupport::GetCPUViaSyscall(unsigned *cpu, // NOLINT(runtime/int)
- void *, void *) {
-#ifdef SYS_getcpu
- return syscall(SYS_getcpu, cpu, nullptr, nullptr);
-#else
- // x86_64 never implemented sys_getcpu(), except as a VDSO call.
- static_cast<void>(cpu); // Avoid an unused argument compiler warning.
- errno = ENOSYS;
- return -1;
-#endif
-}
-
-// Use fast __vdso_getcpu if available.
-long VDSOSupport::InitAndGetCPU(unsigned *cpu, // NOLINT(runtime/int)
- void *x, void *y) {
- Init();
- GetCpuFn fn = getcpu_fn_.load(std::memory_order_relaxed);
- ABSL_RAW_CHECK(fn != &InitAndGetCPU, "Init() did not set getcpu_fn_");
- return (*fn)(cpu, x, y);
-}
-
-// This function must be very fast, and may be called from very
-// low level (e.g. tcmalloc). Hence I avoid things like
-// GoogleOnceInit() and ::operator new.
-ABSL_ATTRIBUTE_NO_SANITIZE_MEMORY
-int GetCPU() {
- unsigned cpu;
- long ret_code = // NOLINT(runtime/int)
- (*VDSOSupport::getcpu_fn_)(&cpu, nullptr, nullptr);
- return ret_code == 0 ? static_cast<int>(cpu) : static_cast<int>(ret_code);
-}
-
-} // namespace debugging_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_HAVE_VDSO_SUPPORT
diff --git a/third_party/abseil-cpp/absl/debugging/internal/vdso_support.h b/third_party/abseil-cpp/absl/debugging/internal/vdso_support.h
deleted file mode 100644
index 6562c6c..0000000
--- a/third_party/abseil-cpp/absl/debugging/internal/vdso_support.h
+++ /dev/null
@@ -1,158 +0,0 @@
-//
-// Copyright 2017 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.
-//
-
-// Allow dynamic symbol lookup in the kernel VDSO page.
-//
-// VDSO stands for "Virtual Dynamic Shared Object" -- a page of
-// executable code, which looks like a shared library, but doesn't
-// necessarily exist anywhere on disk, and which gets mmap()ed into
-// every process by kernels which support VDSO, such as 2.6.x for 32-bit
-// executables, and 2.6.24 and above for 64-bit executables.
-//
-// More details could be found here:
-// http://www.trilithium.com/johan/2005/08/linux-gate/
-//
-// VDSOSupport -- a class representing kernel VDSO (if present).
-//
-// Example usage:
-// VDSOSupport vdso;
-// VDSOSupport::SymbolInfo info;
-// typedef (*FN)(unsigned *, void *, void *);
-// FN fn = nullptr;
-// if (vdso.LookupSymbol("__vdso_getcpu", "LINUX_2.6", STT_FUNC, &info)) {
-// fn = reinterpret_cast<FN>(info.address);
-// }
-
-#ifndef ABSL_DEBUGGING_INTERNAL_VDSO_SUPPORT_H_
-#define ABSL_DEBUGGING_INTERNAL_VDSO_SUPPORT_H_
-
-#include <atomic>
-
-#include "absl/base/attributes.h"
-#include "absl/debugging/internal/elf_mem_image.h"
-
-#ifdef ABSL_HAVE_ELF_MEM_IMAGE
-
-#ifdef ABSL_HAVE_VDSO_SUPPORT
-#error ABSL_HAVE_VDSO_SUPPORT cannot be directly set
-#else
-#define ABSL_HAVE_VDSO_SUPPORT 1
-#endif
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace debugging_internal {
-
-// NOTE: this class may be used from within tcmalloc, and can not
-// use any memory allocation routines.
-class VDSOSupport {
- public:
- VDSOSupport();
-
- typedef ElfMemImage::SymbolInfo SymbolInfo;
- typedef ElfMemImage::SymbolIterator SymbolIterator;
-
- // On PowerPC64 VDSO symbols can either be of type STT_FUNC or STT_NOTYPE
- // depending on how the kernel is built. The kernel is normally built with
- // STT_NOTYPE type VDSO symbols. Let's make things simpler first by using a
- // compile-time constant.
-#ifdef __powerpc64__
- enum { kVDSOSymbolType = STT_NOTYPE };
-#else
- enum { kVDSOSymbolType = STT_FUNC };
-#endif
-
- // Answers whether we have a vdso at all.
- bool IsPresent() const { return image_.IsPresent(); }
-
- // Allow to iterate over all VDSO symbols.
- SymbolIterator begin() const { return image_.begin(); }
- SymbolIterator end() const { return image_.end(); }
-
- // Look up versioned dynamic symbol in the kernel VDSO.
- // Returns false if VDSO is not present, or doesn't contain given
- // symbol/version/type combination.
- // If info_out != nullptr, additional details are filled in.
- bool LookupSymbol(const char *name, const char *version,
- int symbol_type, SymbolInfo *info_out) const;
-
- // Find info about symbol (if any) which overlaps given address.
- // Returns true if symbol was found; false if VDSO isn't present
- // or doesn't have a symbol overlapping given address.
- // If info_out != nullptr, additional details are filled in.
- bool LookupSymbolByAddress(const void *address, SymbolInfo *info_out) const;
-
- // Used only for testing. Replace real VDSO base with a mock.
- // Returns previous value of vdso_base_. After you are done testing,
- // you are expected to call SetBase() with previous value, in order to
- // reset state to the way it was.
- const void *SetBase(const void *s);
-
- // Computes vdso_base_ and returns it. Should be called as early as
- // possible; before any thread creation, chroot or setuid.
- static const void *Init();
-
- private:
- // image_ represents VDSO ELF image in memory.
- // image_.ehdr_ == nullptr implies there is no VDSO.
- ElfMemImage image_;
-
- // Cached value of auxv AT_SYSINFO_EHDR, computed once.
- // This is a tri-state:
- // kInvalidBase => value hasn't been determined yet.
- // 0 => there is no VDSO.
- // else => vma of VDSO Elf{32,64}_Ehdr.
- //
- // When testing with mock VDSO, low bit is set.
- // The low bit is always available because vdso_base_ is
- // page-aligned.
- static std::atomic<const void *> vdso_base_;
-
- // NOLINT on 'long' because these routines mimic kernel api.
- // The 'cache' parameter may be used by some versions of the kernel,
- // and should be nullptr or point to a static buffer containing at
- // least two 'long's.
- static long InitAndGetCPU(unsigned *cpu, void *cache, // NOLINT 'long'.
- void *unused);
- static long GetCPUViaSyscall(unsigned *cpu, void *cache, // NOLINT 'long'.
- void *unused);
- typedef long (*GetCpuFn)(unsigned *cpu, void *cache, // NOLINT 'long'.
- void *unused);
-
- // This function pointer may point to InitAndGetCPU,
- // GetCPUViaSyscall, or __vdso_getcpu at different stages of initialization.
- ABSL_CONST_INIT static std::atomic<GetCpuFn> getcpu_fn_;
-
- friend int GetCPU(void); // Needs access to getcpu_fn_.
-
- VDSOSupport(const VDSOSupport&) = delete;
- VDSOSupport& operator=(const VDSOSupport&) = delete;
-};
-
-// Same as sched_getcpu() on later glibc versions.
-// Return current CPU, using (fast) __vdso_getcpu@LINUX_2.6 if present,
-// otherwise use syscall(SYS_getcpu,...).
-// May return -1 with errno == ENOSYS if the kernel doesn't
-// support SYS_getcpu.
-int GetCPU();
-
-} // namespace debugging_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_HAVE_ELF_MEM_IMAGE
-
-#endif // ABSL_DEBUGGING_INTERNAL_VDSO_SUPPORT_H_
diff --git a/third_party/abseil-cpp/absl/debugging/leak_check.cc b/third_party/abseil-cpp/absl/debugging/leak_check.cc
deleted file mode 100644
index 195e82b..0000000
--- a/third_party/abseil-cpp/absl/debugging/leak_check.cc
+++ /dev/null
@@ -1,73 +0,0 @@
-// Copyright 2017 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.
-//
-// Wrappers around lsan_interface functions.
-//
-// These are always-available run-time functions manipulating the LeakSanitizer,
-// even when the lsan_interface (and LeakSanitizer) is not available. When
-// LeakSanitizer is not linked in, these functions become no-op stubs.
-
-#include "absl/debugging/leak_check.h"
-
-#include "absl/base/attributes.h"
-#include "absl/base/config.h"
-
-#if defined(ABSL_HAVE_LEAK_SANITIZER)
-
-#include <sanitizer/lsan_interface.h>
-
-#if ABSL_HAVE_ATTRIBUTE_WEAK
-extern "C" ABSL_ATTRIBUTE_WEAK int __lsan_is_turned_off();
-#endif
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-bool HaveLeakSanitizer() { return true; }
-
-#if ABSL_HAVE_ATTRIBUTE_WEAK
-bool LeakCheckerIsActive() {
- return !(&__lsan_is_turned_off && __lsan_is_turned_off());
-}
-#else
-bool LeakCheckerIsActive() { return true; }
-#endif
-
-bool FindAndReportLeaks() { return __lsan_do_recoverable_leak_check(); }
-void DoIgnoreLeak(const void* ptr) { __lsan_ignore_object(ptr); }
-void RegisterLivePointers(const void* ptr, size_t size) {
- __lsan_register_root_region(ptr, size);
-}
-void UnRegisterLivePointers(const void* ptr, size_t size) {
- __lsan_unregister_root_region(ptr, size);
-}
-LeakCheckDisabler::LeakCheckDisabler() { __lsan_disable(); }
-LeakCheckDisabler::~LeakCheckDisabler() { __lsan_enable(); }
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#else // defined(ABSL_HAVE_LEAK_SANITIZER)
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-bool HaveLeakSanitizer() { return false; }
-bool LeakCheckerIsActive() { return false; }
-void DoIgnoreLeak(const void*) { }
-void RegisterLivePointers(const void*, size_t) { }
-void UnRegisterLivePointers(const void*, size_t) { }
-LeakCheckDisabler::LeakCheckDisabler() { }
-LeakCheckDisabler::~LeakCheckDisabler() { }
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // defined(ABSL_HAVE_LEAK_SANITIZER)
diff --git a/third_party/abseil-cpp/absl/debugging/leak_check.h b/third_party/abseil-cpp/absl/debugging/leak_check.h
deleted file mode 100644
index eff162f..0000000
--- a/third_party/abseil-cpp/absl/debugging/leak_check.h
+++ /dev/null
@@ -1,150 +0,0 @@
-// Copyright 2018 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.
-//
-// -----------------------------------------------------------------------------
-// File: leak_check.h
-// -----------------------------------------------------------------------------
-//
-// This file contains functions that affect leak checking behavior within
-// targets built with the LeakSanitizer (LSan), a memory leak detector that is
-// integrated within the AddressSanitizer (ASan) as an additional component, or
-// which can be used standalone. LSan and ASan are included (or can be provided)
-// as additional components for most compilers such as Clang, gcc and MSVC.
-// Note: this leak checking API is not yet supported in MSVC.
-// Leak checking is enabled by default in all ASan builds.
-//
-// https://clang.llvm.org/docs/LeakSanitizer.html
-// https://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer
-//
-// GCC and Clang both automatically enable LeakSanitizer when AddressSanitizer
-// is enabled. To use the mode, simply pass `-fsanitize=address` to both the
-// compiler and linker. An example Bazel command could be
-//
-// $ bazel test --copt=-fsanitize=address --linkopt=-fsanitize=address ...
-//
-// GCC and Clang auto support a standalone LeakSanitizer mode (a mode which does
-// not also use AddressSanitizer). To use the mode, simply pass
-// `-fsanitize=leak` to both the compiler and linker. Since GCC does not
-// currently provide a way of detecting this mode at compile-time, GCC users
-// must also pass -DLEAK_SANIITIZER to the compiler. An example Bazel command
-// could be
-//
-// $ bazel test --copt=-DLEAK_SANITIZER --copt=-fsanitize=leak
-// --linkopt=-fsanitize=leak ...
-//
-// -----------------------------------------------------------------------------
-#ifndef ABSL_DEBUGGING_LEAK_CHECK_H_
-#define ABSL_DEBUGGING_LEAK_CHECK_H_
-
-#include <cstddef>
-
-#include "absl/base/config.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-
-// HaveLeakSanitizer()
-//
-// Returns true if a leak-checking sanitizer (either ASan or standalone LSan) is
-// currently built into this target.
-bool HaveLeakSanitizer();
-
-// LeakCheckerIsActive()
-//
-// Returns true if a leak-checking sanitizer (either ASan or standalone LSan) is
-// currently built into this target and is turned on.
-bool LeakCheckerIsActive();
-
-// DoIgnoreLeak()
-//
-// Implements `IgnoreLeak()` below. This function should usually
-// not be called directly; calling `IgnoreLeak()` is preferred.
-void DoIgnoreLeak(const void* ptr);
-
-// IgnoreLeak()
-//
-// Instruct the leak sanitizer to ignore leak warnings on the object referenced
-// by the passed pointer, as well as all heap objects transitively referenced
-// by it. The passed object pointer can point to either the beginning of the
-// object or anywhere within it.
-//
-// Example:
-//
-// static T* obj = IgnoreLeak(new T(...));
-//
-// If the passed `ptr` does not point to an actively allocated object at the
-// time `IgnoreLeak()` is called, the call is a no-op; if it is actively
-// allocated, leak sanitizer will assume this object is referenced even if
-// there is no actual reference in user memory.
-//
-template <typename T>
-T* IgnoreLeak(T* ptr) {
- DoIgnoreLeak(ptr);
- return ptr;
-}
-
-// FindAndReportLeaks()
-//
-// If any leaks are detected, prints a leak report and returns true. This
-// function may be called repeatedly, and does not affect end-of-process leak
-// checking.
-//
-// Example:
-// if (FindAndReportLeaks()) {
-// ... diagnostic already printed. Exit with failure code.
-// exit(1)
-// }
-bool FindAndReportLeaks();
-
-// LeakCheckDisabler
-//
-// This helper class indicates that any heap allocations done in the code block
-// covered by the scoped object, which should be allocated on the stack, will
-// not be reported as leaks. Leak check disabling will occur within the code
-// block and any nested function calls within the code block.
-//
-// Example:
-//
-// void Foo() {
-// LeakCheckDisabler disabler;
-// ... code that allocates objects whose leaks should be ignored ...
-// }
-//
-// REQUIRES: Destructor runs in same thread as constructor
-class LeakCheckDisabler {
- public:
- LeakCheckDisabler();
- LeakCheckDisabler(const LeakCheckDisabler&) = delete;
- LeakCheckDisabler& operator=(const LeakCheckDisabler&) = delete;
- ~LeakCheckDisabler();
-};
-
-// RegisterLivePointers()
-//
-// Registers `ptr[0,size-1]` as pointers to memory that is still actively being
-// referenced and for which leak checking should be ignored. This function is
-// useful if you store pointers in mapped memory, for memory ranges that we know
-// are correct but for which normal analysis would flag as leaked code.
-void RegisterLivePointers(const void* ptr, size_t size);
-
-// UnRegisterLivePointers()
-//
-// Deregisters the pointers previously marked as active in
-// `RegisterLivePointers()`, enabling leak checking of those pointers.
-void UnRegisterLivePointers(const void* ptr, size_t size);
-
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_DEBUGGING_LEAK_CHECK_H_
diff --git a/third_party/abseil-cpp/absl/debugging/leak_check_fail_test.cc b/third_party/abseil-cpp/absl/debugging/leak_check_fail_test.cc
deleted file mode 100644
index c49b81a..0000000
--- a/third_party/abseil-cpp/absl/debugging/leak_check_fail_test.cc
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright 2017 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 <memory>
-#include "gtest/gtest.h"
-#include "absl/base/internal/raw_logging.h"
-#include "absl/debugging/leak_check.h"
-
-namespace {
-
-TEST(LeakCheckTest, LeakMemory) {
- // This test is expected to cause lsan failures on program exit. Therefore the
- // test will be run only by leak_check_test.sh, which will verify a
- // failed exit code.
-
- char* foo = strdup("lsan should complain about this leaked string");
- ABSL_RAW_LOG(INFO, "Should detect leaked string %s", foo);
-}
-
-TEST(LeakCheckTest, LeakMemoryAfterDisablerScope) {
- // This test is expected to cause lsan failures on program exit. Therefore the
- // test will be run only by external_leak_check_test.sh, which will verify a
- // failed exit code.
- { absl::LeakCheckDisabler disabler; }
- char* foo = strdup("lsan should also complain about this leaked string");
- ABSL_RAW_LOG(INFO, "Re-enabled leak detection.Should detect leaked string %s",
- foo);
-}
-
-} // namespace
diff --git a/third_party/abseil-cpp/absl/debugging/leak_check_test.cc b/third_party/abseil-cpp/absl/debugging/leak_check_test.cc
deleted file mode 100644
index 6a42e31..0000000
--- a/third_party/abseil-cpp/absl/debugging/leak_check_test.cc
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright 2017 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 <string>
-
-#include "gtest/gtest.h"
-#include "absl/base/config.h"
-#include "absl/base/internal/raw_logging.h"
-#include "absl/debugging/leak_check.h"
-
-namespace {
-
-TEST(LeakCheckTest, IgnoreLeakSuppressesLeakedMemoryErrors) {
- if (!absl::LeakCheckerIsActive()) {
- GTEST_SKIP() << "LeakChecker is not active";
- }
- auto foo = absl::IgnoreLeak(new std::string("some ignored leaked string"));
- ABSL_RAW_LOG(INFO, "Ignoring leaked string %s", foo->c_str());
-}
-
-TEST(LeakCheckTest, LeakCheckDisablerIgnoresLeak) {
- if (!absl::LeakCheckerIsActive()) {
- GTEST_SKIP() << "LeakChecker is not active";
- }
- absl::LeakCheckDisabler disabler;
- auto foo = new std::string("some string leaked while checks are disabled");
- ABSL_RAW_LOG(INFO, "Ignoring leaked string %s", foo->c_str());
-}
-
-} // namespace
diff --git a/third_party/abseil-cpp/absl/debugging/stacktrace.cc b/third_party/abseil-cpp/absl/debugging/stacktrace.cc
deleted file mode 100644
index ff8069f..0000000
--- a/third_party/abseil-cpp/absl/debugging/stacktrace.cc
+++ /dev/null
@@ -1,142 +0,0 @@
-// Copyright 2017 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.
-
-// Produce stack trace.
-//
-// There are three different ways we can try to get the stack trace:
-//
-// 1) Our hand-coded stack-unwinder. This depends on a certain stack
-// layout, which is used by gcc (and those systems using a
-// gcc-compatible ABI) on x86 systems, at least since gcc 2.95.
-// It uses the frame pointer to do its work.
-//
-// 2) The libunwind library. This is still in development, and as a
-// separate library adds a new dependency, but doesn't need a frame
-// pointer. It also doesn't call malloc.
-//
-// 3) The gdb unwinder -- also the one used by the c++ exception code.
-// It's obviously well-tested, but has a fatal flaw: it can call
-// malloc() from the unwinder. This is a problem because we're
-// trying to use the unwinder to instrument malloc().
-//
-// Note: if you add a new implementation here, make sure it works
-// correctly when absl::GetStackTrace() is called with max_depth == 0.
-// Some code may do that.
-
-#include "absl/debugging/stacktrace.h"
-
-#include <atomic>
-
-#include "absl/base/attributes.h"
-#include "absl/base/port.h"
-#include "absl/debugging/internal/stacktrace_config.h"
-
-#if defined(ABSL_STACKTRACE_INL_HEADER)
-#include ABSL_STACKTRACE_INL_HEADER
-#else
-# error Cannot calculate stack trace: will need to write for your environment
-
-# include "absl/debugging/internal/stacktrace_aarch64-inl.inc"
-# include "absl/debugging/internal/stacktrace_arm-inl.inc"
-# include "absl/debugging/internal/stacktrace_emscripten-inl.inc"
-# include "absl/debugging/internal/stacktrace_generic-inl.inc"
-# include "absl/debugging/internal/stacktrace_powerpc-inl.inc"
-# include "absl/debugging/internal/stacktrace_riscv-inl.inc"
-# include "absl/debugging/internal/stacktrace_unimplemented-inl.inc"
-# include "absl/debugging/internal/stacktrace_win32-inl.inc"
-# include "absl/debugging/internal/stacktrace_x86-inl.inc"
-#endif
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace {
-
-typedef int (*Unwinder)(void**, int*, int, int, const void*, int*);
-std::atomic<Unwinder> custom;
-
-template <bool IS_STACK_FRAMES, bool IS_WITH_CONTEXT>
-ABSL_ATTRIBUTE_ALWAYS_INLINE inline int Unwind(void** result, int* sizes,
- int max_depth, int skip_count,
- const void* uc,
- int* min_dropped_frames) {
- Unwinder f = &UnwindImpl<IS_STACK_FRAMES, IS_WITH_CONTEXT>;
- Unwinder g = custom.load(std::memory_order_acquire);
- if (g != nullptr) f = g;
-
- // Add 1 to skip count for the unwinder function itself
- int size = (*f)(result, sizes, max_depth, skip_count + 1, uc,
- min_dropped_frames);
- // To disable tail call to (*f)(...)
- ABSL_BLOCK_TAIL_CALL_OPTIMIZATION();
- return size;
-}
-
-} // anonymous namespace
-
-ABSL_ATTRIBUTE_NOINLINE ABSL_ATTRIBUTE_NO_TAIL_CALL int GetStackFrames(
- void** result, int* sizes, int max_depth, int skip_count) {
- return Unwind<true, false>(result, sizes, max_depth, skip_count, nullptr,
- nullptr);
-}
-
-ABSL_ATTRIBUTE_NOINLINE ABSL_ATTRIBUTE_NO_TAIL_CALL int
-GetStackFramesWithContext(void** result, int* sizes, int max_depth,
- int skip_count, const void* uc,
- int* min_dropped_frames) {
- return Unwind<true, true>(result, sizes, max_depth, skip_count, uc,
- min_dropped_frames);
-}
-
-ABSL_ATTRIBUTE_NOINLINE ABSL_ATTRIBUTE_NO_TAIL_CALL int GetStackTrace(
- void** result, int max_depth, int skip_count) {
- return Unwind<false, false>(result, nullptr, max_depth, skip_count, nullptr,
- nullptr);
-}
-
-ABSL_ATTRIBUTE_NOINLINE ABSL_ATTRIBUTE_NO_TAIL_CALL int
-GetStackTraceWithContext(void** result, int max_depth, int skip_count,
- const void* uc, int* min_dropped_frames) {
- return Unwind<false, true>(result, nullptr, max_depth, skip_count, uc,
- min_dropped_frames);
-}
-
-void SetStackUnwinder(Unwinder w) {
- custom.store(w, std::memory_order_release);
-}
-
-int DefaultStackUnwinder(void** pcs, int* sizes, int depth, int skip,
- const void* uc, int* min_dropped_frames) {
- skip++; // For this function
- Unwinder f = nullptr;
- if (sizes == nullptr) {
- if (uc == nullptr) {
- f = &UnwindImpl<false, false>;
- } else {
- f = &UnwindImpl<false, true>;
- }
- } else {
- if (uc == nullptr) {
- f = &UnwindImpl<true, false>;
- } else {
- f = &UnwindImpl<true, true>;
- }
- }
- volatile int x = 0;
- int n = (*f)(pcs, sizes, depth, skip, uc, min_dropped_frames);
- x = 1; (void) x; // To disable tail call to (*f)(...)
- return n;
-}
-
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/debugging/stacktrace.h b/third_party/abseil-cpp/absl/debugging/stacktrace.h
deleted file mode 100644
index 0ec0ffd..0000000
--- a/third_party/abseil-cpp/absl/debugging/stacktrace.h
+++ /dev/null
@@ -1,231 +0,0 @@
-// Copyright 2018 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.
-//
-// -----------------------------------------------------------------------------
-// File: stacktrace.h
-// -----------------------------------------------------------------------------
-//
-// This file contains routines to extract the current stack trace and associated
-// stack frames. These functions are thread-safe and async-signal-safe.
-//
-// Note that stack trace functionality is platform dependent and requires
-// additional support from the compiler/build system in most cases. (That is,
-// this functionality generally only works on platforms/builds that have been
-// specifically configured to support it.)
-//
-// Note: stack traces in Abseil that do not utilize a symbolizer will result in
-// frames consisting of function addresses rather than human-readable function
-// names. (See symbolize.h for information on symbolizing these values.)
-
-#ifndef ABSL_DEBUGGING_STACKTRACE_H_
-#define ABSL_DEBUGGING_STACKTRACE_H_
-
-#include "absl/base/config.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-
-// GetStackFrames()
-//
-// Records program counter values for up to `max_depth` frames, skipping the
-// most recent `skip_count` stack frames, stores their corresponding values
-// and sizes in `results` and `sizes` buffers, and returns the number of frames
-// stored. (Note that the frame generated for the `absl::GetStackFrames()`
-// routine itself is also skipped.)
-//
-// Example:
-//
-// main() { foo(); }
-// foo() { bar(); }
-// bar() {
-// void* result[10];
-// int sizes[10];
-// int depth = absl::GetStackFrames(result, sizes, 10, 1);
-// }
-//
-// The current stack frame would consist of three function calls: `bar()`,
-// `foo()`, and then `main()`; however, since the `GetStackFrames()` call sets
-// `skip_count` to `1`, it will skip the frame for `bar()`, the most recently
-// invoked function call. It will therefore return 2 and fill `result` with
-// program counters within the following functions:
-//
-// result[0] foo()
-// result[1] main()
-//
-// (Note: in practice, a few more entries after `main()` may be added to account
-// for startup processes.)
-//
-// Corresponding stack frame sizes will also be recorded:
-//
-// sizes[0] 16
-// sizes[1] 16
-//
-// (Stack frame sizes of `16` above are just for illustration purposes.)
-//
-// Stack frame sizes of 0 or less indicate that those frame sizes couldn't
-// be identified.
-//
-// This routine may return fewer stack frame entries than are
-// available. Also note that `result` and `sizes` must both be non-null.
-extern int GetStackFrames(void** result, int* sizes, int max_depth,
- int skip_count);
-
-// GetStackFramesWithContext()
-//
-// Records program counter values obtained from a signal handler. Records
-// program counter values for up to `max_depth` frames, skipping the most recent
-// `skip_count` stack frames, stores their corresponding values and sizes in
-// `results` and `sizes` buffers, and returns the number of frames stored. (Note
-// that the frame generated for the `absl::GetStackFramesWithContext()` routine
-// itself is also skipped.)
-//
-// The `uc` parameter, if non-null, should be a pointer to a `ucontext_t` value
-// passed to a signal handler registered via the `sa_sigaction` field of a
-// `sigaction` struct. (See
-// http://man7.org/linux/man-pages/man2/sigaction.2.html.) The `uc` value may
-// help a stack unwinder to provide a better stack trace under certain
-// conditions. `uc` may safely be null.
-//
-// The `min_dropped_frames` output parameter, if non-null, points to the
-// location to note any dropped stack frames, if any, due to buffer limitations
-// or other reasons. (This value will be set to `0` if no frames were dropped.)
-// The number of total stack frames is guaranteed to be >= skip_count +
-// max_depth + *min_dropped_frames.
-extern int GetStackFramesWithContext(void** result, int* sizes, int max_depth,
- int skip_count, const void* uc,
- int* min_dropped_frames);
-
-// GetStackTrace()
-//
-// Records program counter values for up to `max_depth` frames, skipping the
-// most recent `skip_count` stack frames, stores their corresponding values
-// in `results`, and returns the number of frames
-// stored. Note that this function is similar to `absl::GetStackFrames()`
-// except that it returns the stack trace only, and not stack frame sizes.
-//
-// Example:
-//
-// main() { foo(); }
-// foo() { bar(); }
-// bar() {
-// void* result[10];
-// int depth = absl::GetStackTrace(result, 10, 1);
-// }
-//
-// This produces:
-//
-// result[0] foo
-// result[1] main
-// .... ...
-//
-// `result` must not be null.
-extern int GetStackTrace(void** result, int max_depth, int skip_count);
-
-// GetStackTraceWithContext()
-//
-// Records program counter values obtained from a signal handler. Records
-// program counter values for up to `max_depth` frames, skipping the most recent
-// `skip_count` stack frames, stores their corresponding values in `results`,
-// and returns the number of frames stored. (Note that the frame generated for
-// the `absl::GetStackFramesWithContext()` routine itself is also skipped.)
-//
-// The `uc` parameter, if non-null, should be a pointer to a `ucontext_t` value
-// passed to a signal handler registered via the `sa_sigaction` field of a
-// `sigaction` struct. (See
-// http://man7.org/linux/man-pages/man2/sigaction.2.html.) The `uc` value may
-// help a stack unwinder to provide a better stack trace under certain
-// conditions. `uc` may safely be null.
-//
-// The `min_dropped_frames` output parameter, if non-null, points to the
-// location to note any dropped stack frames, if any, due to buffer limitations
-// or other reasons. (This value will be set to `0` if no frames were dropped.)
-// The number of total stack frames is guaranteed to be >= skip_count +
-// max_depth + *min_dropped_frames.
-extern int GetStackTraceWithContext(void** result, int max_depth,
- int skip_count, const void* uc,
- int* min_dropped_frames);
-
-// SetStackUnwinder()
-//
-// Provides a custom function for unwinding stack frames that will be used in
-// place of the default stack unwinder when invoking the static
-// GetStack{Frames,Trace}{,WithContext}() functions above.
-//
-// The arguments passed to the unwinder function will match the
-// arguments passed to `absl::GetStackFramesWithContext()` except that sizes
-// will be non-null iff the caller is interested in frame sizes.
-//
-// If unwinder is set to null, we revert to the default stack-tracing behavior.
-//
-// *****************************************************************************
-// WARNING
-// *****************************************************************************
-//
-// absl::SetStackUnwinder is not suitable for general purpose use. It is
-// provided for custom runtimes.
-// Some things to watch out for when calling `absl::SetStackUnwinder()`:
-//
-// (a) The unwinder may be called from within signal handlers and
-// therefore must be async-signal-safe.
-//
-// (b) Even after a custom stack unwinder has been unregistered, other
-// threads may still be in the process of using that unwinder.
-// Therefore do not clean up any state that may be needed by an old
-// unwinder.
-// *****************************************************************************
-extern void SetStackUnwinder(int (*unwinder)(void** pcs, int* sizes,
- int max_depth, int skip_count,
- const void* uc,
- int* min_dropped_frames));
-
-// DefaultStackUnwinder()
-//
-// Records program counter values of up to `max_depth` frames, skipping the most
-// recent `skip_count` stack frames, and stores their corresponding values in
-// `pcs`. (Note that the frame generated for this call itself is also skipped.)
-// This function acts as a generic stack-unwinder; prefer usage of the more
-// specific `GetStack{Trace,Frames}{,WithContext}()` functions above.
-//
-// If you have set your own stack unwinder (with the `SetStackUnwinder()`
-// function above, you can still get the default stack unwinder by calling
-// `DefaultStackUnwinder()`, which will ignore any previously set stack unwinder
-// and use the default one instead.
-//
-// Because this function is generic, only `pcs` is guaranteed to be non-null
-// upon return. It is legal for `sizes`, `uc`, and `min_dropped_frames` to all
-// be null when called.
-//
-// The semantics are the same as the corresponding `GetStack*()` function in the
-// case where `absl::SetStackUnwinder()` was never called. Equivalents are:
-//
-// null sizes | non-nullptr sizes
-// |==========================================================|
-// null uc | GetStackTrace() | GetStackFrames() |
-// non-null uc | GetStackTraceWithContext() | GetStackFramesWithContext() |
-// |==========================================================|
-extern int DefaultStackUnwinder(void** pcs, int* sizes, int max_depth,
- int skip_count, const void* uc,
- int* min_dropped_frames);
-
-namespace debugging_internal {
-// Returns true for platforms which are expected to have functioning stack trace
-// implementations. Intended to be used for tests which want to exclude
-// verification of logic known to be broken because stack traces are not
-// working.
-extern bool StackTraceWorksForTest();
-} // namespace debugging_internal
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_DEBUGGING_STACKTRACE_H_
diff --git a/third_party/abseil-cpp/absl/debugging/stacktrace_benchmark.cc b/third_party/abseil-cpp/absl/debugging/stacktrace_benchmark.cc
deleted file mode 100644
index 9360baf..0000000
--- a/third_party/abseil-cpp/absl/debugging/stacktrace_benchmark.cc
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright 2022 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/attributes.h"
-#include "absl/base/config.h"
-#include "absl/base/optimization.h"
-#include "absl/debugging/stacktrace.h"
-#include "benchmark/benchmark.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-namespace {
-
-static constexpr int kMaxStackDepth = 100;
-static constexpr int kCacheSize = (1 << 16);
-void* pcs[kMaxStackDepth];
-
-ABSL_ATTRIBUTE_NOINLINE void func(benchmark::State& state, int x, int depth) {
- if (x <= 0) {
- // Touch a significant amount of memory so that the stack is likely to be
- // not cached in the L1 cache.
- state.PauseTiming();
- int* arr = new int[kCacheSize];
- for (int i = 0; i < kCacheSize; ++i) benchmark::DoNotOptimize(arr[i] = 100);
- delete[] arr;
- state.ResumeTiming();
- benchmark::DoNotOptimize(absl::GetStackTrace(pcs, depth, 0));
- return;
- }
- ABSL_BLOCK_TAIL_CALL_OPTIMIZATION();
- func(state, --x, depth);
-}
-
-void BM_GetStackTrace(benchmark::State& state) {
- int depth = state.range(0);
- for (auto s : state) {
- func(state, depth, depth);
- }
-}
-
-BENCHMARK(BM_GetStackTrace)->DenseRange(10, kMaxStackDepth, 10);
-} // namespace
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/debugging/symbolize.cc b/third_party/abseil-cpp/absl/debugging/symbolize.cc
deleted file mode 100644
index 638d395..0000000
--- a/third_party/abseil-cpp/absl/debugging/symbolize.cc
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright 2018 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/debugging/symbolize.h"
-
-#ifdef _WIN32
-#include <winapifamily.h>
-#if !(WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)) || \
- WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
-// UWP doesn't have access to win32 APIs.
-#define ABSL_INTERNAL_HAVE_SYMBOLIZE_WIN32
-#endif
-#endif
-
-// Emscripten symbolization relies on JS. Do not use them in standalone mode.
-#if defined(__EMSCRIPTEN__) && !defined(STANDALONE_WASM)
-#define ABSL_INTERNAL_HAVE_SYMBOLIZE_WASM
-#endif
-
-#if defined(ABSL_INTERNAL_HAVE_ELF_SYMBOLIZE)
-#include "absl/debugging/symbolize_elf.inc"
-#elif defined(ABSL_INTERNAL_HAVE_SYMBOLIZE_WIN32)
-// The Windows Symbolizer only works if PDB files containing the debug info
-// are available to the program at runtime.
-#include "absl/debugging/symbolize_win32.inc"
-#elif defined(__APPLE__)
-#include "absl/debugging/symbolize_darwin.inc"
-#elif defined(ABSL_INTERNAL_HAVE_SYMBOLIZE_WASM)
-#include "absl/debugging/symbolize_emscripten.inc"
-#else
-#include "absl/debugging/symbolize_unimplemented.inc"
-#endif
diff --git a/third_party/abseil-cpp/absl/debugging/symbolize.h b/third_party/abseil-cpp/absl/debugging/symbolize.h
deleted file mode 100644
index 43d93a8..0000000
--- a/third_party/abseil-cpp/absl/debugging/symbolize.h
+++ /dev/null
@@ -1,99 +0,0 @@
-// Copyright 2018 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.
-//
-// -----------------------------------------------------------------------------
-// File: symbolize.h
-// -----------------------------------------------------------------------------
-//
-// This file configures the Abseil symbolizer for use in converting instruction
-// pointer addresses (program counters) into human-readable names (function
-// calls, etc.) within Abseil code.
-//
-// The symbolizer may be invoked from several sources:
-//
-// * Implicitly, through the installation of an Abseil failure signal handler.
-// (See failure_signal_handler.h for more information.)
-// * By calling `Symbolize()` directly on a program counter you obtain through
-// `absl::GetStackTrace()` or `absl::GetStackFrames()`. (See stacktrace.h
-// for more information.
-// * By calling `Symbolize()` directly on a program counter you obtain through
-// other means (which would be platform-dependent).
-//
-// In all of the above cases, the symbolizer must first be initialized before
-// any program counter values can be symbolized. If you are installing a failure
-// signal handler, initialize the symbolizer before you do so.
-//
-// Example:
-//
-// int main(int argc, char** argv) {
-// // Initialize the Symbolizer before installing the failure signal handler
-// absl::InitializeSymbolizer(argv[0]);
-//
-// // Now you may install the failure signal handler
-// absl::FailureSignalHandlerOptions options;
-// absl::InstallFailureSignalHandler(options);
-//
-// // Start running your main program
-// ...
-// return 0;
-// }
-//
-#ifndef ABSL_DEBUGGING_SYMBOLIZE_H_
-#define ABSL_DEBUGGING_SYMBOLIZE_H_
-
-#include "absl/debugging/internal/symbolize.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-
-// InitializeSymbolizer()
-//
-// Initializes the program counter symbolizer, given the path of the program
-// (typically obtained through `main()`s `argv[0]`). The Abseil symbolizer
-// allows you to read program counters (instruction pointer values) using their
-// human-readable names within output such as stack traces.
-//
-// Example:
-//
-// int main(int argc, char *argv[]) {
-// absl::InitializeSymbolizer(argv[0]);
-// // Now you can use the symbolizer
-// }
-void InitializeSymbolizer(const char* argv0);
-//
-// Symbolize()
-//
-// Symbolizes a program counter (instruction pointer value) `pc` and, on
-// success, writes the name to `out`. The symbol name is demangled, if possible.
-// Note that the symbolized name may be truncated and will be NUL-terminated.
-// Demangling is supported for symbols generated by GCC 3.x or newer). Returns
-// `false` on failure.
-//
-// Example:
-//
-// // Print a program counter and its symbol name.
-// static void DumpPCAndSymbol(void *pc) {
-// char tmp[1024];
-// const char *symbol = "(unknown)";
-// if (absl::Symbolize(pc, tmp, sizeof(tmp))) {
-// symbol = tmp;
-// }
-// absl::PrintF("%p %s\n", pc, symbol);
-// }
-bool Symbolize(const void *pc, char *out, int out_size);
-
-ABSL_NAMESPACE_END
-} // namespace absl
-
-#endif // ABSL_DEBUGGING_SYMBOLIZE_H_
diff --git a/third_party/abseil-cpp/absl/debugging/symbolize_darwin.inc b/third_party/abseil-cpp/absl/debugging/symbolize_darwin.inc
deleted file mode 100644
index cf63d19..0000000
--- a/third_party/abseil-cpp/absl/debugging/symbolize_darwin.inc
+++ /dev/null
@@ -1,102 +0,0 @@
-// 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 <cxxabi.h>
-#include <execinfo.h>
-
-#include <algorithm>
-#include <cstring>
-
-#include "absl/base/internal/raw_logging.h"
-#include "absl/debugging/internal/demangle.h"
-#include "absl/strings/numbers.h"
-#include "absl/strings/str_cat.h"
-#include "absl/strings/string_view.h"
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-
-void InitializeSymbolizer(const char*) {}
-
-namespace debugging_internal {
-namespace {
-
-static std::string GetSymbolString(absl::string_view backtrace_line) {
- // Example Backtrace lines:
- // 0 libimaging_shared.dylib 0x018c152a
- // _ZNSt11_Deque_baseIN3nik7mediadb4PageESaIS2_EE17_M_initialize_mapEm + 3478
- //
- // or
- // 0 libimaging_shared.dylib 0x0000000001895c39
- // _ZN3nik4util19register_shared_ptrINS_3gpu7TextureEEEvPKvS5_ + 39
- //
- // or
- // 0 mysterious_app 0x0124000120120009 main + 17
- auto address_pos = backtrace_line.find(" 0x");
- if (address_pos == absl::string_view::npos) return std::string();
- absl::string_view symbol_view = backtrace_line.substr(address_pos + 1);
-
- auto space_pos = symbol_view.find(" ");
- if (space_pos == absl::string_view::npos) return std::string();
- symbol_view = symbol_view.substr(space_pos + 1); // to mangled symbol
-
- auto plus_pos = symbol_view.find(" + ");
- if (plus_pos == absl::string_view::npos) return std::string();
- symbol_view = symbol_view.substr(0, plus_pos); // strip remainng
-
- return std::string(symbol_view);
-}
-
-} // namespace
-} // namespace debugging_internal
-
-bool Symbolize(const void* pc, char* out, int out_size) {
- if (out_size <= 0 || pc == nullptr) {
- out = nullptr;
- return false;
- }
-
- // This allocates a char* array.
- char** frame_strings = backtrace_symbols(const_cast<void**>(&pc), 1);
-
- if (frame_strings == nullptr) return false;
-
- std::string symbol = debugging_internal::GetSymbolString(frame_strings[0]);
- free(frame_strings);
-
- char tmp_buf[1024];
- if (debugging_internal::Demangle(symbol.c_str(), tmp_buf, sizeof(tmp_buf))) {
- size_t len = strlen(tmp_buf);
- if (len + 1 <= static_cast<size_t>(out_size)) { // +1 for '\0'
- assert(len < sizeof(tmp_buf));
- memmove(out, tmp_buf, len + 1);
- }
- } else {
- strncpy(out, symbol.c_str(), static_cast<size_t>(out_size));
- }
-
- if (out[out_size - 1] != '\0') {
- // strncpy() does not '\0' terminate when it truncates.
- static constexpr char kEllipsis[] = "...";
- size_t ellipsis_size =
- std::min(sizeof(kEllipsis) - 1, static_cast<size_t>(out_size) - 1);
- memcpy(out + out_size - ellipsis_size - 1, kEllipsis, ellipsis_size);
- out[out_size - 1] = '\0';
- }
-
- return true;
-}
-
-ABSL_NAMESPACE_END
-} // namespace absl
diff --git a/third_party/abseil-cpp/absl/debugging/symbolize_elf.inc b/third_party/abseil-cpp/absl/debugging/symbolize_elf.inc
deleted file mode 100644
index ffb4eec..0000000
--- a/third_party/abseil-cpp/absl/debugging/symbolize_elf.inc
+++ /dev/null
@@ -1,1637 +0,0 @@
-// Copyright 2018 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.
-
-// This library provides Symbolize() function that symbolizes program
-// counters to their corresponding symbol names on linux platforms.
-// This library has a minimal implementation of an ELF symbol table
-// reader (i.e. it doesn't depend on libelf, etc.).
-//
-// The algorithm used in Symbolize() is as follows.
-//
-// 1. Go through a list of maps in /proc/self/maps and find the map
-// containing the program counter.
-//
-// 2. Open the mapped file and find a regular symbol table inside.
-// Iterate over symbols in the symbol table and look for the symbol
-// containing the program counter. If such a symbol is found,
-// obtain the symbol name, and demangle the symbol if possible.
-// If the symbol isn't found in the regular symbol table (binary is
-// stripped), try the same thing with a dynamic symbol table.
-//
-// Note that Symbolize() is originally implemented to be used in
-// signal handlers, hence it doesn't use malloc() and other unsafe
-// operations. It should be both thread-safe and async-signal-safe.
-//
-// Implementation note:
-//
-// We don't use heaps but only use stacks. We want to reduce the
-// stack consumption so that the symbolizer can run on small stacks.
-//
-// Here are some numbers collected with GCC 4.1.0 on x86:
-// - sizeof(Elf32_Sym) = 16
-// - sizeof(Elf32_Shdr) = 40
-// - sizeof(Elf64_Sym) = 24
-// - sizeof(Elf64_Shdr) = 64
-//
-// This implementation is intended to be async-signal-safe but uses some
-// functions which are not guaranteed to be so, such as memchr() and
-// memmove(). We assume they are async-signal-safe.
-
-#include <dlfcn.h>
-#include <elf.h>
-#include <fcntl.h>
-#include <link.h> // For ElfW() macro.
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include <algorithm>
-#include <array>
-#include <atomic>
-#include <cerrno>
-#include <cinttypes>
-#include <climits>
-#include <cstdint>
-#include <cstdio>
-#include <cstdlib>
-#include <cstring>
-
-#include "absl/base/casts.h"
-#include "absl/base/dynamic_annotations.h"
-#include "absl/base/internal/low_level_alloc.h"
-#include "absl/base/internal/raw_logging.h"
-#include "absl/base/internal/spinlock.h"
-#include "absl/base/port.h"
-#include "absl/debugging/internal/demangle.h"
-#include "absl/debugging/internal/vdso_support.h"
-#include "absl/strings/string_view.h"
-
-#if defined(__FreeBSD__) && !defined(ElfW)
-#define ElfW(x) __ElfN(x)
-#endif
-
-namespace absl {
-ABSL_NAMESPACE_BEGIN
-
-// Value of argv[0]. Used by MaybeInitializeObjFile().
-static char *argv0_value = nullptr;
-
-void InitializeSymbolizer(const char *argv0) {
-#ifdef ABSL_HAVE_VDSO_SUPPORT
- // We need to make sure VDSOSupport::Init() is called before any setuid or
- // chroot calls, so InitializeSymbolizer() should be called very early in the
- // life of a program.
- absl::debugging_internal::VDSOSupport::Init();
-#endif
- if (argv0_value != nullptr) {
- free(argv0_value);
- argv0_value = nullptr;
- }
- if (argv0 != nullptr && argv0[0] != '\0') {
- argv0_value = strdup(argv0);
- }
-}
-
-namespace debugging_internal {
-namespace {
-
-// Re-runs fn until it doesn't cause EINTR.
-#define NO_INTR(fn) \
- do { \
- } while ((fn) < 0 && errno == EINTR)
-
-// On Linux, ELF_ST_* are defined in <linux/elf.h>. To make this portable
-// we define our own ELF_ST_BIND and ELF_ST_TYPE if not available.
-#ifndef ELF_ST_BIND
-#define ELF_ST_BIND(info) (((unsigned char)(info)) >> 4)
-#endif
-
-#ifndef ELF_ST_TYPE
-#define ELF_ST_TYPE(info) (((unsigned char)(info)) & 0xF)
-#endif
-
-// Some platforms use a special .opd section to store function pointers.
-const char kOpdSectionName[] = ".opd";
-
-#if (defined(__powerpc__) && !(_CALL_ELF > 1)) || defined(__ia64)
-// Use opd section for function descriptors on these platforms, the function
-// address is the first word of the descriptor.
-enum { kPlatformUsesOPDSections = 1 };
-#else // not PPC or IA64
-enum { kPlatformUsesOPDSections = 0 };
-#endif
-
-// This works for PowerPC & IA64 only. A function descriptor consist of two
-// pointers and the first one is the function's entry.
-const size_t kFunctionDescriptorSize = sizeof(void *) * 2;
-
-const int kMaxDecorators = 10; // Seems like a reasonable upper limit.
-
-struct InstalledSymbolDecorator {
- SymbolDecorator fn;
- void *arg;
- int ticket;
-};
-
-int g_num_decorators;
-InstalledSymbolDecorator g_decorators[kMaxDecorators];
-
-struct FileMappingHint {
- const void *start;
- const void *end;
- uint64_t offset;
- const char *filename;
-};
-
-// Protects g_decorators.
-// We are using SpinLock and not a Mutex here, because we may be called
-// from inside Mutex::Lock itself, and it prohibits recursive calls.
-// This happens in e.g. base/stacktrace_syscall_unittest.
-// Moreover, we are using only TryLock(), if the decorator list
-// is being modified (is busy), we skip all decorators, and possibly
-// loose some info. Sorry, that's the best we could do.
-ABSL_CONST_INIT absl::base_internal::SpinLock g_decorators_mu(
- absl::kConstInit, absl::base_internal::SCHEDULE_KERNEL_ONLY);
-
-const int kMaxFileMappingHints = 8;
-int g_num_file_mapping_hints;
-FileMappingHint g_file_mapping_hints[kMaxFileMappingHints];
-// Protects g_file_mapping_hints.
-ABSL_CONST_INIT absl::base_internal::SpinLock g_file_mapping_mu(
- absl::kConstInit, absl::base_internal::SCHEDULE_KERNEL_ONLY);
-
-// Async-signal-safe function to zero a buffer.
-// memset() is not guaranteed to be async-signal-safe.
-static void SafeMemZero(void* p, size_t size) {
- unsigned char *c = static_cast<unsigned char *>(p);
- while (size--) {
- *c++ = 0;
- }
-}
-
-struct ObjFile {
- ObjFile()
- : filename(nullptr),
- start_addr(nullptr),
- end_addr(nullptr),
- offset(0),
- fd(-1),
- elf_type(-1) {
- SafeMemZero(&elf_header, sizeof(elf_header));
- SafeMemZero(&phdr[0], sizeof(phdr));
- }
-
- char *filename;
- const void *start_addr;
- const void *end_addr;
- uint64_t offset;
-
- // The following fields are initialized on the first access to the
- // object file.
- int fd;
- int elf_type;
- ElfW(Ehdr) elf_header;
-
- // PT_LOAD program header describing executable code.
- // Normally we expect just one, but SWIFT binaries have two.
- // CUDA binaries have 3 (see cr/473913254 description).
- std::array<ElfW(Phdr), 4> phdr;
-};
-
-// Build 4-way associative cache for symbols. Within each cache line, symbols
-// are replaced in LRU order.
-enum {
- ASSOCIATIVITY = 4,
-};
-struct SymbolCacheLine {
- const void *pc[ASSOCIATIVITY];
- char *name[ASSOCIATIVITY];
-
- // age[i] is incremented when a line is accessed. it's reset to zero if the
- // i'th entry is read.
- uint32_t age[ASSOCIATIVITY];
-};
-
-// ---------------------------------------------------------------
-// An async-signal-safe arena for LowLevelAlloc
-static std::atomic<base_internal::LowLevelAlloc::Arena *> g_sig_safe_arena;
-
-static base_internal::LowLevelAlloc::Arena *SigSafeArena() {
- return g_sig_safe_arena.load(std::memory_order_acquire);
-}
-
-static void InitSigSafeArena() {
- if (SigSafeArena() == nullptr) {
- base_internal::LowLevelAlloc::Arena *new_arena =
- base_internal::LowLevelAlloc::NewArena(
- base_internal::LowLevelAlloc::kAsyncSignalSafe);
- base_internal::LowLevelAlloc::Arena *old_value = nullptr;
- if (!g_sig_safe_arena.compare_exchange_strong(old_value, new_arena,
- std::memory_order_release,
- std::memory_order_relaxed)) {
- // We lost a race to allocate an arena; deallocate.
- base_internal::LowLevelAlloc::DeleteArena(new_arena);
- }
- }
-}
-
-// ---------------------------------------------------------------
-// An AddrMap is a vector of ObjFile, using SigSafeArena() for allocation.
-
-class AddrMap {
- public:
- AddrMap() : size_(0), allocated_(0), obj_(nullptr) {}
- ~AddrMap() { base_internal::LowLevelAlloc::Free(obj_); }
- size_t Size() const { return size_; }
- ObjFile *At(size_t i) { return &obj_[i]; }
- ObjFile *Add();
- void Clear();
-
- private:
- size_t size_; // count of valid elements (<= allocated_)
- size_t allocated_; // count of allocated elements
- ObjFile *obj_; // array of allocated_ elements
- AddrMap(const AddrMap &) = delete;
- AddrMap &operator=(const AddrMap &) = delete;
-};
-
-void AddrMap::Clear() {
- for (size_t i = 0; i != size_; i++) {
- At(i)->~ObjFile();
- }
- size_ = 0;
-}
-
-ObjFile *AddrMap::Add() {
- if (size_ == allocated_) {
- size_t new_allocated = allocated_ * 2 + 50;
- ObjFile *new_obj_ =
- static_cast<ObjFile *>(base_internal::LowLevelAlloc::AllocWithArena(
- new_allocated * sizeof(*new_obj_), SigSafeArena()));
- if (obj_) {
- memcpy(new_obj_, obj_, allocated_ * sizeof(*new_obj_));
- base_internal::LowLevelAlloc::Free(obj_);
- }
- obj_ = new_obj_;
- allocated_ = new_allocated;
- }
- return new (&obj_[size_++]) ObjFile;
-}
-
-// ---------------------------------------------------------------
-
-enum FindSymbolResult { SYMBOL_NOT_FOUND = 1, SYMBOL_TRUNCATED, SYMBOL_FOUND };
-
-class Symbolizer {
- public:
- Symbolizer();
- ~Symbolizer();
- const char *GetSymbol(const void *const pc);
-
- private:
- char *CopyString(const char *s) {
- size_t len = strlen(s);
- char *dst = static_cast<char *>(
- base_internal::LowLevelAlloc::AllocWithArena(len + 1, SigSafeArena()));
- ABSL_RAW_CHECK(dst != nullptr, "out of memory");
- memcpy(dst, s, len + 1);
- return dst;
- }
- ObjFile *FindObjFile(const void *const start,
- size_t size) ABSL_ATTRIBUTE_NOINLINE;
- static bool RegisterObjFile(const char *filename,
- const void *const start_addr,
- const void *const end_addr, uint64_t offset,
- void *arg);
- SymbolCacheLine *GetCacheLine(const void *const pc);
- const char *FindSymbolInCache(const void *const pc);
- const char *InsertSymbolInCache(const void *const pc, const char *name);
- void AgeSymbols(SymbolCacheLine *line);
- void ClearAddrMap();
- FindSymbolResult GetSymbolFromObjectFile(const ObjFile &obj,
- const void *const pc,
- const ptrdiff_t relocation,
- char *out, size_t out_size,
- char *tmp_buf, size_t tmp_buf_size);
- const char *GetUncachedSymbol(const void *pc);
-
- enum {
- SYMBOL_BUF_SIZE = 3072,
- TMP_BUF_SIZE = 1024,
- SYMBOL_CACHE_LINES = 128,
- };
-
- AddrMap addr_map_;
-
- bool ok_;
- bool addr_map_read_;
-
- char symbol_buf_[SYMBOL_BUF_SIZE];
-
- // tmp_buf_ will be used to store arrays of ElfW(Shdr) and ElfW(Sym)
- // so we ensure that tmp_buf_ is properly aligned to store either.
- alignas(16) char tmp_buf_[TMP_BUF_SIZE];
- static_assert(alignof(ElfW(Shdr)) <= 16,
- "alignment of tmp buf too small for Shdr");
- static_assert(alignof(ElfW(Sym)) <= 16,
- "alignment of tmp buf too small for Sym");
-
- SymbolCacheLine symbol_cache_[SYMBOL_CACHE_LINES];
-};
-
-static std::atomic<Symbolizer *> g_cached_symbolizer;
-
-} // namespace
-
-static size_t SymbolizerSize() {
-#if defined(__wasm__) || defined(__asmjs__)
- auto pagesize = static_cast<size_t>(getpagesize());
-#else
- auto pagesize = static_cast<size_t>(sysconf(_SC_PAGESIZE));
-#endif
- return ((sizeof(Symbolizer) - 1) / pagesize + 1) * pagesize;
-}
-
-// Return (and set null) g_cached_symbolized_state if it is not null.
-// Otherwise return a new symbolizer.
-static Symbolizer *AllocateSymbolizer() {
- InitSigSafeArena();
- Symbolizer *symbolizer =
- g_cached_symbolizer.exchange(nullptr, std::memory_order_acquire);
- if (symbolizer != nullptr) {
- return symbolizer;
- }
- return new (base_internal::LowLevelAlloc::AllocWithArena(
- SymbolizerSize(), SigSafeArena())) Symbolizer();
-}
-
-// Set g_cached_symbolize_state to s if it is null, otherwise
-// delete s.
-static void FreeSymbolizer(Symbolizer *s) {
- Symbolizer *old_cached_symbolizer = nullptr;
- if (!g_cached_symbolizer.compare_exchange_strong(old_cached_symbolizer, s,
- std::memory_order_release,
- std::memory_order_relaxed)) {
- s->~Symbolizer();
- base_internal::LowLevelAlloc::Free(s);
- }
-}
-
-Symbolizer::Symbolizer() : ok_(true), addr_map_read_(false) {
- for (SymbolCacheLine &symbol_cache_line : symbol_cache_) {
- for (size_t j = 0; j < ABSL_ARRAYSIZE(symbol_cache_line.name); ++j) {
- symbol_cache_line.pc[j] = nullptr;
- symbol_cache_line.name[j] = nullptr;
- symbol_cache_line.age[j] = 0;
- }
- }
-}
-
-Symbolizer::~Symbolizer() {
- for (SymbolCacheLine &symbol_cache_line : symbol_cache_) {
- for (char *s : symbol_cache_line.name) {
- base_internal::LowLevelAlloc::Free(s);
- }
- }
- ClearAddrMap();
-}
-
-// We don't use assert() since it's not guaranteed to be
-// async-signal-safe. Instead we define a minimal assertion
-// macro. So far, we don't need pretty printing for __FILE__, etc.
-#define SAFE_ASSERT(expr) ((expr) ? static_cast<void>(0) : abort())
-
-// Read up to "count" bytes from file descriptor "fd" into the buffer
-// starting at "buf" while handling short reads and EINTR. On
-// success, return the number of bytes read. Otherwise, return -1.
-static ssize_t ReadPersistent(int fd, void *buf, size_t count) {
- SAFE_ASSERT(fd >= 0);
- SAFE_ASSERT(count <= SSIZE_MAX);
- char *buf0 = reinterpret_cast<char *>(buf);
- size_t num_bytes = 0;
- while (num_bytes < count) {
- ssize_t len;
- NO_INTR(len = read(fd, buf0 + num_bytes, count - num_bytes));
- if (len < 0) { // There was an error other than EINTR.
- ABSL_RAW_LOG(WARNING, "read failed: errno=%d", errno);
- return -1;
- }
- if (len == 0) { // Reached EOF.
- break;
- }
- num_bytes += static_cast<size_t>(len);
- }
- SAFE_ASSERT(num_bytes <= count);
- return static_cast<ssize_t>(num_bytes);
-}
-
-// Read up to "count" bytes from "offset" in the file pointed by file
-// descriptor "fd" into the buffer starting at "buf". On success,
-// return the number of bytes read. Otherwise, return -1.
-static ssize_t ReadFromOffset(const int fd, void *buf, const size_t count,
- const off_t offset) {
- off_t off = lseek(fd, offset