about summary refs log tree commit diff
path: root/absl/container
diff options
context:
space:
mode:
Diffstat (limited to 'absl/container')
-rw-r--r--absl/container/BUILD.bazel69
-rw-r--r--absl/container/CMakeLists.txt62
-rw-r--r--absl/container/btree_map.h705
-rw-r--r--absl/container/btree_set.h653
-rw-r--r--absl/container/btree_test.cc2243
-rw-r--r--absl/container/btree_test.h153
-rw-r--r--absl/container/internal/btree.h2610
-rw-r--r--absl/container/internal/btree_container.h609
8 files changed, 7104 insertions, 0 deletions
diff --git a/absl/container/BUILD.bazel b/absl/container/BUILD.bazel
index 9e2a5b1eacb9..1859d9e9c75c 100644
--- a/absl/container/BUILD.bazel
+++ b/absl/container/BUILD.bazel
@@ -825,3 +825,72 @@ cc_test(
         "@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",
+        ":compressed_tuple",
+        ":container_memory",
+        ":layout",
+        "//absl/base:core_headers",
+        "//absl/base:throw_delegate",
+        "//absl/memory",
+        "//absl/meta:type_traits",
+        "//absl/strings",
+        "//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/time",
+    ],
+)
+
+cc_test(
+    name = "btree_test",
+    size = "large",
+    srcs = [
+        "btree_test.cc",
+    ],
+    copts = ABSL_TEST_COPTS + ["-fexceptions"],
+    linkopts = ABSL_DEFAULT_LINKOPTS,
+    shard_count = 10,
+    visibility = ["//visibility:private"],
+    deps = [
+        ":btree",
+        ":btree_test_common",
+        ":counting_allocator",
+        ":test_instance_tracker",
+        "//absl/base",
+        "//absl/flags:flag",
+        "//absl/hash:hash_testing",
+        "//absl/memory",
+        "//absl/meta:type_traits",
+        "//absl/strings",
+        "//absl/types:compare",
+        "@com_google_googletest//:gtest_main",
+    ],
+)
diff --git a/absl/container/CMakeLists.txt b/absl/container/CMakeLists.txt
index 7988b12fe3b8..6cabe0c9309a 100644
--- a/absl/container/CMakeLists.txt
+++ b/absl/container/CMakeLists.txt
@@ -25,6 +25,68 @@ absl_cc_library(
 
 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::compare
+    absl::compressed_tuple
+    absl::container_memory
+    absl::core_headers
+    absl::layout
+    absl::memory
+    absl::strings
+    absl::throw_delegate
+    absl::type_traits
+    absl::utility
+)
+
+absl_cc_library(
+  NAME
+    btree_test_common
+  hdrs
+    "btree_test.h"
+  COPTS
+    ${ABSL_TEST_COPTS}
+  LINKOPTS
+    ${ABSL_DEFAULT_LINKOPTS}
+  DEPS
+    absl::btree
+    absl::flat_hash_set
+    absl::strings
+    absl::time
+  TESTONLY
+)
+
+absl_cc_test(
+  NAME
+    btree_test
+  SRCS
+    "btree_test.cc"
+  DEPS
+    absl::base
+    absl::btree
+    absl::btree_test_common
+    absl::compare
+    absl::counting_allocator
+    absl::flags
+    absl::hash_testing
+    absl::strings
+    absl::test_instance_tracker
+    absl::type_traits
+    gmock_main
+)
+
+absl_cc_library(
+  NAME
     compressed_tuple
   HDRS
     "internal/compressed_tuple.h"
diff --git a/absl/container/btree_map.h b/absl/container/btree_map.h
new file mode 100644
index 000000000000..9f35f63949df
--- /dev/null
+++ b/absl/container/btree_map.h
@@ -0,0 +1,705 @@
+// 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.
+//
+// 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.
+
+#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::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,
+              /*Multi=*/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.
+  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::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. 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& x):
+  //
+  //   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: 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 is provided 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 is provided a
+  // compatible heterogeneous comparator.
+  using Base::count;
+
+  // btree_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
+  // `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 is provided a
+  // compatible heterogeneous comparator.
+  using Base::find;
+
+  // 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::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,
+              /*Multi=*/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& x):
+  //
+  //   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: 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 elements from a given `source` btree_multimap into this
+  // `btree_multimap`. If the destination `btree_multimap` already contains an
+  // element with an equivalent key, that element is not extracted.
+  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 is provided 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 is provided a
+  // compatible heterogeneous comparator.
+  using Base::count;
+
+  // btree_multimap::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_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 is provided a
+  // compatible heterogeneous comparator.
+  using Base::find;
+
+  // 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);
+}
+
+}  // namespace absl
+
+#endif  // ABSL_CONTAINER_BTREE_MAP_H_
diff --git a/absl/container/btree_set.h b/absl/container/btree_set.h
new file mode 100644
index 000000000000..6e47b4aae652
--- /dev/null
+++ b/absl/container/btree_set.h
@@ -0,0 +1,653 @@
+// 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.
+//
+// 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.
+
+#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::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,
+              /*Multi=*/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.
+  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. 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& x):
+  //
+  //   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 is provided 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 is provided 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 is provided a
+  // compatible heterogeneous comparator.
+  using Base::find;
+
+  // 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::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,
+              /*Multi=*/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& x):
+  //
+  //   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 elements from a given `source` btree_multiset into this
+  // `btree_multiset`. If the destination `btree_multiset` already contains an
+  // element with an equivalent key, that element is not extracted.
+  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 is provided 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 is provided 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 is provided a
+  // compatible heterogeneous comparator.
+  using Base::find;
+
+  // 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);
+}
+
+}  // namespace absl
+
+#endif  // ABSL_CONTAINER_BTREE_SET_H_
diff --git a/absl/container/btree_test.cc b/absl/container/btree_test.cc
new file mode 100644
index 000000000000..a330cca32b90
--- /dev/null
+++ b/absl/container/btree_test.cc
@@ -0,0 +1,2243 @@
+// 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 <cstdint>
+#include <map>
+#include <memory>
+#include <stdexcept>
+#include <string>
+#include <type_traits>
+#include <utility>
+
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include "absl/base/internal/raw_logging.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/meta/type_traits.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 {
+namespace container_internal {
+namespace {
+
+using ::absl::test_internal::InstanceTracker;
+using ::absl::test_internal::MovableOnlyInstance;
+using ::testing::ElementsAre;
+using ::testing::ElementsAreArray;
+using ::testing::IsEmpty;
+using ::testing::Pair;
+
+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 &x)
+      : tree_(x.tree_), const_tree_(tree_), checker_(x.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 &x) {
+    typename KeyOfValue<typename TreeType::key_type,
+                        typename TreeType::value_type>::type key_of_value;
+    const key_type &key = key_of_value(x);
+    CheckPairEquals(*find(key), x);
+    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 &x) {
+    tree_ = x.tree_;
+    checker_ = x.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;
+      }
+    }
+    checker_.erase(checker_begin, checker_end);
+    tree_.erase(begin, end);
+    EXPECT_EQ(tree_.size(), checker_.size());
+    EXPECT_EQ(tree_.size(), size - count);
+  }
+
+  void clear() {
+    tree_.clear();
+    checker_.clear();
+  }
+  void swap(base_checker &x) {
+    tree_.swap(x.tree_);
+    checker_.swap(x.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 &x) : super_type(x) {}
+  template <class InputIterator>
+  unique_checker(InputIterator b, InputIterator e) : super_type(b, e) {}
+
+  // Insertion routines.
+  std::pair<iterator, bool> insert(const value_type &x) {
+    int size = this->tree_.size();
+    std::pair<typename CheckerType::iterator, bool> checker_res =
+        this->checker_.insert(x);
+    std::pair<iterator, bool> tree_res = this->tree_.insert(x);
+    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 &x) {
+    int size = this->tree_.size();
+    std::pair<typename CheckerType::iterator, bool> checker_res =
+        this->checker_.insert(x);
+    iterator tree_res = this->tree_.insert(position, x);
+    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 &x) : super_type(x) {}
+  template <class InputIterator>
+  multi_checker(InputIterator b, InputIterator e) : super_type(b, e) {}
+
+  // Insertion routines.
+  iterator insert(const value_type &x) {
+    int size = this->tree_.size();
+    auto checker_res = this->checker_.insert(x);
+    iterator tree_res = this->tree_.insert(x);
+    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 &x) {
+    int size = this->tree_.size();
+    auto checker_res = this->checker_.insert(x);
+    iterator tree_res = this->tree_.insert(position, x);
+    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),
+      testing::GTEST_FLAG(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),
+      testing::GTEST_FLAG(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_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_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_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_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());
+}
+
+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.reset(new 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 K>
+void AssertKeyCompareToAdapted() {
+  using Adapted = typename key_compare_to_adapter<Compare>::type;
+  static_assert(!std::is_same<Adapted, Compare>::value,
+                "key_compare_to_adapter should have adapted this comparator.");
+  static_assert(
+      std::is_same<absl::weak_ordering,
+                   absl::result_of_t<Adapted(const K &, const K &)>>::value,
+      "Adapted comparator should be a key-compare-to comparator.");
+}
+template <typename Compare, typename K>
+void AssertKeyCompareToNotAdapted() {
+  using Unadapted = typename key_compare_to_adapter<Compare>::type;
+  static_assert(
+      std::is_same<Unadapted, Compare>::value,
+      "key_compare_to_adapter shouldn't have adapted this comparator.");
+  static_assert(
+      std::is_same<bool,
+                   absl::result_of_t<Unadapted(const K &, const K &)>>::value,
+      "Un-adapted comparator should return bool.");
+}
+
+TEST(Btree, KeyCompareToAdapter) {
+  AssertKeyCompareToAdapted<std::less<std::string>, std::string>();
+  AssertKeyCompareToAdapted<std::greater<std::string>, std::string>();
+  AssertKeyCompareToAdapted<std::less<absl::string_view>, absl::string_view>();
+  AssertKeyCompareToAdapted<std::greater<absl::string_view>,
+                            absl::string_view>();
+  AssertKeyCompareToNotAdapted<std::less<int>, int>();
+  AssertKeyCompareToNotAdapted<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);
+}
+
+}  // 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>>::SizeWithNValues(target_values_per_node);
+  }
+
+  // Yields the number of values in a (non-root) leaf node for this set.
+  template <typename Set>
+  constexpr static size_t GetNumValuesPerNode() {
+    return btree_node<typename Set::params_type>::kNodeValues;
+  }
+};
+
+namespace {
+
+// A btree set with a specific number of values per node.
+template <typename Key, int TargetValuesPerNode, typename Cmp = std::less<Key>>
+class SizedBtreeSet
+    : public btree_set_container<btree<
+          set_params<Key, 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=*/3> set3;
+  // 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::GetNumValuesPerNode<decltype(set3)>(), 3);
+  EXPECT_EQ(BtreeNodePeer::GetNumValuesPerNode<decltype(set61)>(), 61);
+  EXPECT_EQ(BtreeNodePeer::GetNumValuesPerNode<decltype(set100)>(), 100);
+  if (sizeof(void *) == 8) {
+    EXPECT_EQ(BtreeNodePeer::GetNumValuesPerNode<absl::btree_set<int32_t>>(),
+              BtreeNodePeer::GetNumValuesPerNode<decltype(set61)>());
+  }
+
+  // Test key insertion/deletion in random order.
+  ExpectOperationCounts(45281, 132551, values, &tracker, &set3);
+  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(26638, 92134, values, &tracker, &set3);
+  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(49951, 119325, values, &tracker, &set3);
+  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=*/3,
+                MovableOnlyInstanceThreeWayCompare>
+      set3;
+  // 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::GetNumValuesPerNode<decltype(set3)>(), 3);
+  EXPECT_EQ(BtreeNodePeer::GetNumValuesPerNode<decltype(set61)>(), 61);
+  EXPECT_EQ(BtreeNodePeer::GetNumValuesPerNode<decltype(set100)>(), 100);
+  if (sizeof(void *) == 8) {
+    EXPECT_EQ(BtreeNodePeer::GetNumValuesPerNode<absl::btree_set<int32_t>>(),
+              BtreeNodePeer::GetNumValuesPerNode<decltype(set61)>());
+  }
+
+  // Test key insertion/deletion in random order.
+  ExpectOperationCounts(45281, 122560, values, &tracker, &set3);
+  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(26638, 92134, values, &tracker, &set3);
+  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(49951, 109326, values, &tracker, &set3);
+  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);
+  try {
+    map.at(3);
+    FAIL() << "Exception not thrown";
+  } catch (const std::out_of_range& e) {
+    EXPECT_STREQ(e.what(), "absl::btree_map::at");
+  }
+}
+
+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);
+}
+
+// We can't use EXPECT_EQ/etc. to compare absl::weak_ordering because they
+// convert literal 0 to int and absl::weak_ordering can only be compared with
+// literal 0. Defining this function allows for avoiding ClangTidy warnings.
+bool Identity(const bool b) { return b; }
+
+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)));
+
+  absl::btree_map<std::string, int> m2;
+  EXPECT_TRUE(Identity(
+      m2.value_comp()(std::make_pair("a", 0), std::make_pair("b", 0)) < 0));
+  EXPECT_TRUE(Identity(
+      m2.value_comp()(std::make_pair("b", 0), std::make_pair("b", 0)) == 0));
+  EXPECT_TRUE(Identity(
+      m2.value_comp()(std::make_pair("b", 0), std::make_pair("a", 0)) > 0));
+}
+
+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);
+}
+
+struct Deref {
+  bool operator()(const std::unique_ptr<int> &lhs,
+                  const std::unique_ptr<int> &rhs) const {
+    return *lhs < *rhs;
+  }
+};
+
+TEST(Btree, ExtractWithUniquePtr) {
+  absl::btree_set<std::unique_ptr<int>, Deref> s;
+  s.insert(absl::make_unique<int>(1));
+  s.insert(absl::make_unique<int>(2));
+  s.insert(absl::make_unique<int>(3));
+  s.insert(absl::make_unique<int>(4));
+  s.insert(absl::make_unique<int>(5));
+  auto nh = s.extract(s.find(absl::make_unique<int>(3)));
+  EXPECT_EQ(s.size(), 4);
+  EXPECT_EQ(*nh.value(), 3);
+  s.insert(std::move(nh));
+  EXPECT_EQ(s.size(), 5);
+}
+
+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());
+}
+
+// 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)));
+}
+
+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 std::string from the literal.
+  m.try_emplace(1, "one");
+  EXPECT_EQ(1, m.size());
+
+  // Try other std::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);
+
+  absl::btree_map<int, int, 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);
+  }
+}
+
+}  // namespace
+}  // namespace container_internal
+}  // namespace absl
diff --git a/absl/container/btree_test.h b/absl/container/btree_test.h
new file mode 100644
index 000000000000..5ecf43ceebe5
--- /dev/null
+++ b/absl/container/btree_test.h
@@ -0,0 +1,153 @@
+// 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/time/time.h"
+
+namespace absl {
+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 <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
+}  // namespace absl
+
+#endif  // ABSL_CONTAINER_BTREE_TEST_H_
diff --git a/absl/container/internal/btree.h b/absl/container/internal/btree.h
new file mode 100644
index 000000000000..9561a4d62fe4
--- /dev/null
+++ b/absl/container/internal/btree.h
@@ -0,0 +1,2610 @@
+// 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/macros.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/layout.h"
+#include "absl/memory/memory.h"
+#include "absl/meta/type_traits.h"
+#include "absl/strings/string_view.h"
+#include "absl/types/compare.h"
+#include "absl/utility/utility.h"
+
+namespace absl {
+namespace container_internal {
+
+// 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<absl::result_of_t<Compare(const T &, const T &)>,
+                        absl::weak_ordering>;
+
+struct StringBtreeDefaultLess {
+  using is_transparent = void;
+
+  StringBtreeDefaultLess() = default;
+
+  // Compatibility constructor.
+  StringBtreeDefaultLess(std::less<std::string>) {}  // NOLINT
+  StringBtreeDefaultLess(std::less<string_view>) {}  // NOLINT
+
+  absl::weak_ordering operator()(absl::string_view lhs,
+                                 absl::string_view rhs) const {
+    return compare_internal::compare_result_as_ordering(lhs.compare(rhs));
+  }
+};
+
+struct StringBtreeDefaultGreater {
+  using is_transparent = void;
+
+  StringBtreeDefaultGreater() = default;
+
+  StringBtreeDefaultGreater(std::greater<std::string>) {}  // NOLINT
+  StringBtreeDefaultGreater(std::greater<string_view>) {}  // NOLINT
+
+  absl::weak_ordering operator()(absl::string_view lhs,
+                                 absl::string_view rhs) const {
+    return compare_internal::compare_result_as_ordering(rhs.compare(lhs));
+  }
+};
+
+// A helper class to convert a boolean comparison into a three-way "compare-to"
+// comparison that returns a negative value to indicate less-than, zero to
+// indicate equality and a positive value to indicate greater-than. This helper
+// class is specialized for less<std::string>, greater<std::string>,
+// less<string_view>, and greater<string_view>.
+//
+// key_compare_to_adapter is provided so that btree users
+// automatically get the more efficient compare-to code when using common
+// google string types with common comparison functors.
+// These string-like specializations also turn on heterogeneous lookup by
+// default.
+template <typename Compare>
+struct key_compare_to_adapter {
+  using type = Compare;
+};
+
+template <>
+struct key_compare_to_adapter<std::less<std::string>> {
+  using type = StringBtreeDefaultLess;
+};
+
+template <>
+struct key_compare_to_adapter<std::greater<std::string>> {
+  using type = StringBtreeDefaultGreater;
+};
+
+template <>
+struct key_compare_to_adapter<std::less<absl::string_view>> {
+  using type = StringBtreeDefaultLess;
+};
+
+template <>
+struct key_compare_to_adapter<std::greater<absl::string_view>> {
+  using type = StringBtreeDefaultGreater;
+};
+
+template <typename Key, typename Compare, typename Alloc, int TargetNodeSize,
+          bool Multi, typename SlotPolicy>
+struct common_params {
+  // If Compare is a common comparator for a std::string-like type, then we adapt it
+  // to use heterogeneous lookup and to be a key-compare-to comparator.
+  using key_compare = typename key_compare_to_adapter<Compare>::type;
+  // 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 = std::make_signed<size_t>::type;
+  using difference_type = ptrdiff_t;
+
+  // True if this is a multiset or multimap.
+  using is_multi_container = std::integral_constant<bool, Multi>;
+
+  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 &;
+
+  enum {
+    kTargetNodeSize = TargetNodeSize,
+
+    // Upper bound for the available space for values. This is largest for leaf
+    // nodes, which have overhead of at least a pointer + 4 bytes (for storing
+    // 3 field_types and an enum).
+    kNodeValueSpace =
+        TargetNodeSize - /*minimum overhead=*/(sizeof(void *) + 4),
+  };
+
+  // This is an integral type large enough to hold as many
+  // ValueSize-values as will fit a node of TargetNodeSize bytes.
+  using node_count_type =
+      absl::conditional_t<(kNodeValueSpace / sizeof(value_type) >
+                           (std::numeric_limits<uint8_t>::max)()),
+                          uint16_t, uint8_t>;  // NOLINT
+
+  // The following methods are necessary for passing this struct as PolicyTraits
+  // for node_handle and/or are used within btree.
+  static value_type &element(slot_type *slot) {
+    return slot_policy::element(slot);
+  }
+  static const value_type &element(const slot_type *slot) {
+    return slot_policy::element(slot);
+  }
+  template <class... Args>
+  static void construct(Alloc *alloc, slot_type *slot, Args &&... args) {
+    slot_policy::construct(alloc, slot, std::forward<Args>(args)...);
+  }
+  static void construct(Alloc *alloc, slot_type *slot, slot_type *other) {
+    slot_policy::construct(alloc, slot, other);
+  }
+  static void destroy(Alloc *alloc, slot_type *slot) {
+    slot_policy::destroy(alloc, slot);
+  }
+  static void transfer(Alloc *alloc, slot_type *new_slot, slot_type *old_slot) {
+    construct(alloc, new_slot, old_slot);
+    destroy(alloc, old_slot);
+  }
+  static void swap(Alloc *alloc, slot_type *a, slot_type *b) {
+    slot_policy::swap(alloc, a, b);
+  }
+  static void move(Alloc *alloc, slot_type *src, slot_type *dest) {
+    slot_policy::move(alloc, src, dest);
+  }
+  static void move(Alloc *alloc, slot_type *first, slot_type *last,
+                   slot_type *result) {
+    slot_policy::move(alloc, first, last, result);
+  }
+};
+
+// 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 Multi>
+struct map_params : common_params<Key, Compare, Alloc, TargetNodeSize, Multi,
+                                  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;
+
+  using key_compare = typename super_type::key_compare;
+  // Inherit from key_compare for empty base class optimization.
+  struct value_compare : private key_compare {
+    value_compare() = default;
+    explicit value_compare(const key_compare &cmp) : key_compare(cmp) {}
+
+    template <typename T, typename U>
+    auto operator()(const T &left, const U &right) const
+        -> decltype(std::declval<key_compare>()(left.first, right.first)) {
+      return key_compare::operator()(left.first, right.first);
+    }
+  };
+  using is_map_container = std::true_type;
+
+  static const Key &key(const value_type &x) { return x.first; }
+  static const Key &key(const init_type &x) { return x.first; }
+  static const Key &key(const slot_type *x) { return slot_policy::key(x); }
+  static mapped_type &value(value_type *value) { return value->second; }
+};
+
+// This type implements the necessary functions from the
+// absl::container_internal::slot_type interface.
+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 destroy(Alloc *alloc, slot_type *slot) {
+    absl::allocator_traits<Alloc>::destroy(*alloc, slot);
+  }
+
+  template <typename Alloc>
+  static void swap(Alloc * /*alloc*/, slot_type *a, slot_type *b) {
+    using std::swap;
+    swap(*a, *b);
+  }
+
+  template <typename Alloc>
+  static void move(Alloc * /*alloc*/, slot_type *src, slot_type *dest) {
+    *dest = std::move(*src);
+  }
+
+  template <typename Alloc>
+  static void move(Alloc *alloc, slot_type *first, slot_type *last,
+                   slot_type *result) {
+    for (slot_type *src = first, *dest = result; src != last; ++src, ++dest)
+      move(alloc, src, dest);
+  }
+};
+
+// 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 Multi>
+struct set_params : common_params<Key, Compare, Alloc, TargetNodeSize, Multi,
+                                  set_slot_policy<Key>> {
+  using value_type = Key;
+  using slot_type = typename set_params::common_params::slot_type;
+  using value_compare = typename set_params::common_params::key_compare;
+  using is_map_container = std::false_type;
+
+  static const Key &key(const value_type &x) { return x; }
+  static const Key &key(const slot_type *x) { return *x; }
+};
+
+// 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 K, typename LK>
+  bool operator()(const K &a, const LK &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> {
+  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 is_multi_container = typename Params::is_multi_container;
+  using field_type = typename Params::node_count_type;
+  using allocator_type = typename Params::allocator_type;
+  using slot_type = typename Params::slot_type;
+
+ 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 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,
+                std::is_arithmetic<key_type>::value &&
+                    (std::is_same<std::less<key_type>, key_compare>::value ||
+                     std::is_same<std::greater<key_type>, key_compare>::value)>;
+
+  // This class is organized by gtl::Layout as if it had the following
+  // structure:
+  //   // A pointer to the node's parent.
+  //   btree_node *parent;
+  //
+  //   // 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 count of the number of populated values in the node.
+  //   field_type count;
+  //   // The maximum number of values the node can hold. This is an integer in
+  //   // [1, kNodeValues] for root leaf nodes, kNodeValues for non-root leaf
+  //   // nodes, and kInternalNodeMaxCount (as a sentinel value) for internal
+  //   // nodes (even though there are still kNodeValues 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
+  //   // kNodeValues for internal nodes. Only the values in
+  //   // [start, start + count) 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 kNodeValues + 1 children for
+  //   // internal nodes.
+  //   btree_node *children[kNodeValues + 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 *, field_type,
+                                                       slot_type, btree_node *>;
+  constexpr static size_type SizeWithNValues(size_type n) {
+    return layout_type(/*parent*/ 1,
+                       /*position, start, count, max_count*/ 4,
+                       /*values*/ n,
+                       /*children*/ 0)
+        .AllocSize();
+  }
+  // A lower bound for the overhead of fields other than values in a leaf node.
+  constexpr static size_type MinimumOverhead() {
+    return SizeWithNValues(1) - sizeof(value_type);
+  }
+
+  // Compute how many values we can fit onto a leaf node taking into account
+  // padding.
+  constexpr static size_type NodeTargetValues(const int begin, const int end) {
+    return begin == end ? begin
+                        : SizeWithNValues((begin + end) / 2 + 1) >
+                                  params_type::kTargetNodeSize
+                              ? NodeTargetValues(begin, (begin + end) / 2)
+                              : NodeTargetValues((begin + end) / 2 + 1, end);
+  }
+
+  enum {
+    kTargetNodeSize = params_type::kTargetNodeSize,
+    kNodeTargetValues = NodeTargetValues(0, params_type::kTargetNodeSize),
+
+    // We need a minimum of 3 values 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).
+    kNodeValues = kNodeTargetValues >= 3 ? kNodeTargetValues : 3,
+
+    // The node is internal (i.e. is not a leaf node) if and only if `max_count`
+    // has this value.
+    kInternalNodeMaxCount = 0,
+  };
+
+  // Leaves can have less than kNodeValues values.
+  constexpr static layout_type LeafLayout(const int max_values = kNodeValues) {
+    return layout_type(/*parent*/ 1,
+                       /*position, start, count, max_count*/ 4,
+                       /*values*/ max_values,
+                       /*children*/ 0);
+  }
+  constexpr static layout_type InternalLayout() {
+    return layout_type(/*parent*/ 1,
+                       /*position, start, count, max_count*/ 4,
+                       /*values*/ kNodeValues,
+                       /*children*/ kNodeValues + 1);
+  }
+  constexpr static size_type LeafSize(const int max_values = kNodeValues) {
+    return LeafLayout(max_values).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 < 3 || !leaf());
+    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 < 3 || !leaf());
+    return InternalLayout().template Pointer<N>(
+        reinterpret_cast<const char *>(this));
+  }
+  void set_parent(btree_node *p) { *GetField<0>() = p; }
+  field_type &mutable_count() { return GetField<1>()[2]; }
+  slot_type *slot(int i) { return &GetField<2>()[i]; }
+  const slot_type *slot(int i) const { return &GetField<2>()[i]; }
+  void set_position(field_type v) { GetField<1>()[0] = v; }
+  void set_start(field_type v) { GetField<1>()[1] = v; }
+  void set_count(field_type v) { GetField<1>()[2] = v; }
+  // This method is only called by the node init methods.
+  void set_max_count(field_type v) { GetField<1>()[3] = v; }
+
+ public:
+  // Whether this is a leaf node or not. This value doesn't change after the
+  // node is created.
+  bool leaf() const { return GetField<1>()[3] != kInternalNodeMaxCount; }
+
+  // Getter for the position of this node in its parent.
+  field_type position() const { return GetField<1>()[0]; }
+
+  // Getter for the offset of the first value in the `values` array.
+  field_type start() const { return GetField<1>()[1]; }
+
+  // Getters for the number of values stored in this node.
+  field_type count() const { return GetField<1>()[2]; }
+  field_type max_count() const {
+    // Internal nodes have max_count==kInternalNodeMaxCount.
+    // Leaf nodes have max_count in [1, kNodeValues].
+    const field_type max_count = GetField<1>()[3];
+    return max_count == field_type{kInternalNodeMaxCount}
+               ? field_type{kNodeValues}
+               : 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()->leaf(); }
+  void make_root() {
+    assert(parent()->is_root());
+    set_parent(parent()->parent());
+  }
+
+  // Getters for the key/value at position i in the node.
+  const key_type &key(int i) const { return params_type::key(slot(i)); }
+  reference value(int i) { return params_type::element(slot(i)); }
+  const_reference value(int i) const { return params_type::element(slot(i)); }
+
+  // Getters/setter for the child at position i in the node.
+  btree_node *child(int i) const { return GetField<3>()[i]; }
+  btree_node *&mutable_child(int i) { return GetField<3>()[i]; }
+  void clear_child(int i) {
+    absl::container_internal::SanitizerPoisonObject(&mutable_child(i));
+  }
+  void set_child(int i, btree_node *c) {
+    absl::container_internal::SanitizerUnpoisonObject(&mutable_child(i));
+    mutable_child(i) = c;
+    c->set_position(i);
+  }
+  void init_child(int 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<int, 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>
+  int 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<int, btree_is_key_compare_to<Compare, key_type>::value>
+  linear_search(const K &k, const Compare &comp) const {
+    return linear_search_impl(k, 0, count(), comp,
+                              btree_is_key_compare_to<Compare, key_type>());
+  }
+
+  template <typename K, typename Compare>
+  SearchResult<int, btree_is_key_compare_to<Compare, key_type>::value>
+  binary_search(const K &k, const Compare &comp) const {
+    return binary_search_impl(k, 0, count(), 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<int, false> linear_search_impl(
+      const K &k, int s, const int e, const Compare &comp,
+      std::false_type /* IsCompareTo */) const {
+    while (s < e) {
+      if (!comp(key(s), k)) {
+        break;
+      }
+      ++s;
+    }
+    return {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<int, true> linear_search_impl(
+      const K &k, int s, const int 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<int, false> binary_search_impl(
+      const K &k, int s, int e, const Compare &comp,
+      std::false_type /* IsCompareTo */) const {
+    while (s != e) {
+      const int mid = (s + e) >> 1;
+      if (comp(key(mid), k)) {
+        s = mid + 1;
+      } else {
+        e = mid;
+      }
+    }
+    return {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<int, true> binary_search_impl(
+      const K &k, int s, int e, const CompareTo &comp,
+      std::true_type /* IsCompareTo */) const {
+    if (is_multi_container::value) {
+      MatchKind exact_match = MatchKind::kNe;
+      while (s != e) {
+        const int 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 this is a
+            // multi-container.
+            exact_match = MatchKind::kEq;
+          }
+        }
+      }
+      return {s, exact_match};
+    } else {  // Not a multi-container.
+      while (s != e) {
+        const int 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(size_type i, allocator_type *alloc, Args &&... args);
+
+  // Removes the value at position i, shifting all existing values and children
+  // at positions > i to the left by 1.
+  void remove_value(int i, allocator_type *alloc);
+
+  // Removes the values at positions [i, i + to_erase), shifting all values
+  // after that range to the left by to_erase. Does not change children at all.
+  void remove_values_ignore_children(int i, int to_erase,
+                                     allocator_type *alloc);
+
+  // Rebalances a node with its right sibling.
+  void rebalance_right_to_left(int to_move, btree_node *right,
+                               allocator_type *alloc);
+  void rebalance_left_to_right(int 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.
+  void merge(btree_node *sibling, allocator_type *alloc);
+
+  // Swap the contents of "this" and "src".
+  void swap(btree_node *src, allocator_type *alloc);
+
+  // Node allocation/deletion routines.
+  static btree_node *init_leaf(btree_node *n, btree_node *parent,
+                               int max_count) {
+    n->set_parent(parent);
+    n->set_position(0);
+    n->set_start(0);
+    n->set_count(0);
+    n->set_max_count(max_count);
+    absl::container_internal::SanitizerPoisonMemoryRegion(
+        n->slot(0), max_count * sizeof(slot_type));
+    return n;
+  }
+  static btree_node *init_internal(btree_node *n, btree_node *parent) {
+    init_leaf(n, parent, kNodeValues);
+    // Set `max_count` to a sentinel value to indicate that this node is
+    // internal.
+    n->set_max_count(kInternalNodeMaxCount);
+    absl::container_internal::SanitizerPoisonMemoryRegion(
+        &n->mutable_child(0), (kNodeValues + 1) * sizeof(btree_node *));
+    return n;
+  }
+  void destroy(allocator_type *alloc) {
+    for (int i = 0; i < count(); ++i) {
+      value_destroy(i, alloc);
+    }
+  }
+
+ public:
+  // Exposed only for tests.
+  static bool testonly_uses_linear_node_search() {
+    return use_linear_search::value;
+  }
+
+ private:
+  template <typename... Args>
+  void value_init(const size_type i, allocator_type *alloc, Args &&... args) {
+    absl::container_internal::SanitizerUnpoisonObject(slot(i));
+    params_type::construct(alloc, slot(i), std::forward<Args>(args)...);
+  }
+  void value_destroy(const size_type i, allocator_type *alloc) {
+    params_type::destroy(alloc, slot(i));
+    absl::container_internal::SanitizerPoisonObject(slot(i));
+  }
+
+  // Move n values starting at value i in this node into the values starting at
+  // value j in node x.
+  void uninitialized_move_n(const size_type n, const size_type i,
+                            const size_type j, btree_node *x,
+                            allocator_type *alloc) {
+    absl::container_internal::SanitizerUnpoisonMemoryRegion(
+        x->slot(j), n * sizeof(slot_type));
+    for (slot_type *src = slot(i), *end = src + n, *dest = x->slot(j);
+         src != end; ++src, ++dest) {
+      params_type::construct(alloc, dest, src);
+    }
+  }
+
+  // Destroys a range of n values, starting at index i.
+  void value_destroy_n(const size_type i, const size_type n,
+                       allocator_type *alloc) {
+    for (int j = 0; j < n; ++j) {
+      value_destroy(i + j, alloc);
+    }
+  }
+
+  template <typename P>
+  friend class btree;
+  template <typename N, typename R, typename P>
+  friend struct btree_iterator;
+  friend class BtreeNodePeer;
+};
+
+template <typename Node, typename Reference, typename Pointer>
+struct btree_iterator {
+ private:
+  using key_type = typename Node::key_type;
+  using size_type = typename Node::size_type;
+  using params_type = typename Node::params_type;
+
+  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() : node(nullptr), position(-1) {}
+  btree_iterator(Node *n, int p) : node(n), position(p) {}
+
+  // NOTE: this SFINAE allows for implicit conversions from iterator to
+  // const_iterator, but it specifically avoids defining copy constructors so
+  // that btree_iterator can be trivially copyable. This is for performance and
+  // binary size reasons.
+  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> &x)  // NOLINT
+      : node(x.node), position(x.position) {}
+
+ private:
+  // This SFINAE allows explicit conversions from const_iterator to
+  // iterator, but also avoids defining a 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> &x)
+      : node(const_cast<node_type *>(x.node)), position(x.position) {}
+
+  // Increment/decrement the iterator.
+  void increment() {
+    if (node->leaf() && ++position < node->count()) {
+      return;
+    }
+    increment_slow();
+  }
+  void increment_slow();
+
+  void decrement() {
+    if (node->leaf() && --position >= 0) {
+      return;
+    }
+    decrement_slow();
+  }
+  void decrement_slow();
+
+ public:
+  bool operator==(const const_iterator &x) const {
+    return node == x.node && position == x.position;
+  }
+  bool operator!=(const const_iterator &x) const {
+    return node != x.node || position != x.position;
+  }
+
+  // Accessors for the key/value the iterator is pointing at.
+  reference operator*() const {
+    return node->value(position);
+  }
+  pointer operator->() const {
+    return &node->value(position);
+  }
+
+  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:
+  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 N, typename R, typename P>
+  friend struct btree_iterator;
+  template <typename TreeType, typename CheckerType>
+  friend class base_checker;
+
+  const key_type &key() const { return node->key(position); }
+  slot_type *slot() { return node->slot(position); }
+
+  // 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.
+  // TODO(ezb): make this a field_type
+  int position;
+};
+
+template <typename Params>
+class btree {
+  using node_type = btree_node<Params>;
+  using is_key_compare_to = typename Params::is_key_compare_to;
+
+  // 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;
+    field_type position = 0;
+    field_type start = 0;
+    field_type count = 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
+    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 {
+    kNodeValues = node_type::kNodeValues,
+    kMinNodeValues = kNodeValues / 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 &x) {
+      leaf_nodes += x.leaf_nodes;
+      internal_nodes += x.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 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 = btree_iterator<node_type, reference, pointer>;
+  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:
+  // For use in copy_or_move_values_in_order.
+  const value_type &maybe_move_from_iterator(const_iterator x) { return *x; }
+  value_type &&maybe_move_from_iterator(iterator x) { return std::move(*x); }
+
+  // Copies or moves (depending on the template parameter) the values in
+  // x into this btree in their order in x. 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 *x);
+
+  // 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);
+
+  btree(const btree &x);
+  btree(btree &&x) noexcept
+      : root_(std::move(x.root_)),
+        rightmost_(absl::exchange(x.rightmost_, EmptyNode())),
+        size_(absl::exchange(x.size_, 0)) {
+    x.mutable_root() = EmptyNode();
+  }
+
+  ~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 x to *this.
+  btree &operator=(const btree &x);
+  btree &operator=(btree &&x) noexcept;
+
+  iterator begin() {
+    return iterator(leftmost(), 0);
+  }
+  const_iterator begin() const {
+    return const_iterator(leftmost(), 0);
+  }
+  iterator end() { return iterator(rightmost_, rightmost_->count()); }
+  const_iterator end() const {
+    return const_iterator(rightmost_, rightmost_->count());
+  }
+  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));
+  }
+  template <typename K>
+  const_iterator lower_bound(const K &key) const {
+    return internal_end(internal_lower_bound(key));
+  }
+
+  // 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 pair of
+  // the pair is equal to upper_bound(key).
+  template <typename K>
+  std::pair<iterator, iterator> equal_range(const K &key) {
+    return {lower_bound(key), upper_bound(key)};
+  }
+  template <typename K>
+  std::pair<const_iterator, const_iterator> equal_range(const K &key) const {
+    return {lower_bound(key), upper_bound(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... Args>
+  std::pair<iterator, bool> insert_unique(const key_type &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... Args>
+  std::pair<iterator, bool> insert_hint_unique(iterator position,
+                                               const key_type &key,
+                                               Args &&... args);
+
+  // Insert a range of values into the btree.
+  template <typename InputIterator>
+  void insert_iterator_unique(InputIterator b, InputIterator e);
+
+  // 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(iterator begin, iterator end);
+
+  // Erases the specified key from the btree. Returns 1 if an element was
+  // erased and 0 otherwise.
+  template <typename K>
+  size_type erase_unique(const K &key);
+
+  // Erases all of the entries matching the specified key from the
+  // btree. Returns the number of elements erased.
+  template <typename K>
+  size_type erase_multi(const K &key);
+
+  // Finds the iterator corresponding to a key or returns end() if the 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));
+  }
+
+  // Returns a count of the number of times the key appears in the btree.
+  template <typename K>
+  size_type count_unique(const K &key) const {
+    const iterator begin = internal_find(key);
+    if (begin.node == nullptr) {
+      // The key doesn't exist in the tree.
+      return 0;
+    }
+    return 1;
+  }
+  // Returns a count of the number of times the key appears in the btree.
+  template <typename K>
+  size_type count_multi(const K &key) const {
+    const auto range = equal_range(key);
+    return std::distance(range.first, range.second);
+  }
+
+  // Clear the btree, deleting all of the values it contains.
+  void clear();
+
+  // Swap the contents of *this and x.
+  void swap(btree &x);
+
+  const key_compare &key_comp() const noexcept {
+    return root_.template get<0>();
+  }
+  template <typename K, typename LK>
+  bool compare_keys(const K &x, const LK &y) const {
+    return compare_internal::compare_result_as_less_than(key_comp()(x, y));
+  }
+
+  value_compare value_comp() const { return value_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 (root()) {
+      // 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.
+  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.
+  static double average_bytes_per_value() {
+    // Returns the number of bytes per value on a leaf node that is 75%
+    // full. Experimentally, this matches up nicely with the computed number of
+    // bytes per value in trees that had their values inserted in random order.
+    return node_type::LeafSize() / (kNodeValues * 0.75);
+  }
+
+  // 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.
+  double fullness() const {
+    return static_cast<double>(size()) / (nodes() * kNodeValues);
+  }
+  // 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.
+  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:
+  // Internal accessor routines.
+  node_type *root() { return root_.template get<2>(); }
+  const node_type *root() const { return root_.template get<2>(); }
+  node_type *&mutable_root() noexcept { return root_.template get<2>(); }
+  key_compare *mutable_key_comp() noexcept { return &root_.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 &root_.template get<1>();
+  }
+  const allocator_type &allocator() const noexcept {
+    return root_.template get<1>();
+  }
+
+  // Allocates a correctly aligned node of at least size bytes using the
+  // allocator.
+  node_type *allocate(const 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 *p = allocate(node_type::InternalSize());
+    return node_type::init_internal(p, parent);
+  }
+  node_type* new_leaf_node(node_type *parent) {
+    node_type *p = allocate(node_type::LeafSize());
+    return node_type::init_leaf(p, parent, kNodeValues);
+  }
+  node_type *new_leaf_root_node(const int max_count) {
+    node_type *p = allocate(node_type::LeafSize(max_count));
+    return node_type::init_leaf(p, p, max_count);
+  }
+
+  // Deletion helper routines.
+  void erase_same_node(iterator begin, iterator end);
+  iterator erase_from_leaf_node(iterator begin, size_type to_erase);
+  iterator rebalance_after_delete(iterator iter);
+
+  // Deallocates a node of a certain size in bytes using the allocator.
+  void deallocate(const size_type size, node_type *node) {
+    absl::container_internal::Deallocate<node_type::Alignment()>(
+        mutable_allocator(), node, size);
+  }
+
+  void delete_internal_node(node_type *node) {
+    node->destroy(mutable_allocator());
+    deallocate(node_type::InternalSize(), node);
+  }
+  void delete_leaf_node(node_type *node) {
+    node->destroy(mutable_allocator());
+    deallocate(node_type::LeafSize(node->max_count()), node);
+  }
+
+  // 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 as
+  // iter.position == iter.node->count(). 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. We provide 2 versions of internal_locate. The first
+  // version uses a less-than comparator and is incapable of distinguishing when
+  // there is an exact match. The second version is for the key-compare-to
+  // specialization and distinguishes exact matches. The key-compare-to
+  // specialization 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;
+
+  template <typename K>
+  SearchResult<iterator, false> internal_locate_impl(
+      const K &key, std::false_type /* IsCompareTo */) const;
+
+  template <typename K>
+  SearchResult<iterator, true> internal_locate_impl(
+      const K &key, std::true_type /* IsCompareTo */) const;
+
+  // Internal routine which implements lower_bound().
+  template <typename K>
+  iterator 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;
+
+  // Deletes a node and all of its children.
+  void internal_clear(node_type *node);
+
+  // Verifies the tree structure of node.
+  int 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->leaf()) {
+      return node_stats(1, 0);
+    }
+    node_stats res(0, 1);
+    for (int i = 0; i <= node->count(); ++i) {
+      res += internal_stats(node->child(i));
+    }
+    return res;
+  }
+
+ public:
+  // Exposed only for tests.
+  static bool testonly_uses_linear_node_search() {
+    return node_type::testonly_uses_linear_node_search();
+  }
+
+ private:
+  // 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 *>
+      root_;
+
+  // A pointer to the rightmost node. Note that the leftmost node is stored as
+  // the root's parent.
+  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 size_type i,
+                                         allocator_type *alloc,
+                                         Args &&... args) {
+  assert(i <= count());
+  // Shift old values to create space for new value and then construct it in
+  // place.
+  if (i < count()) {
+    value_init(count(), alloc, slot(count() - 1));
+    for (size_type j = count() - 1; j > i; --j)
+      params_type::move(alloc, slot(j - 1), slot(j));
+    value_destroy(i, alloc);
+  }
+  value_init(i, alloc, std::forward<Args>(args)...);
+  set_count(count() + 1);
+
+  if (!leaf() && count() > i + 1) {
+    for (int j = count(); j > i + 1; --j) {
+      set_child(j, child(j - 1));
+    }
+    clear_child(i + 1);
+  }
+}
+
+template <typename P>
+inline void btree_node<P>::remove_value(const int i, allocator_type *alloc) {
+  if (!leaf() && count() > i + 1) {
+    assert(child(i + 1)->count() == 0);
+    for (size_type j = i + 1; j < count(); ++j) {
+      set_child(j, child(j + 1));
+    }
+    clear_child(count());
+  }
+
+  remove_values_ignore_children(i, /*to_erase=*/1, alloc);
+}
+
+template <typename P>
+inline void btree_node<P>::remove_values_ignore_children(
+    const int i, const int to_erase, allocator_type *alloc) {
+  params_type::move(alloc, slot(i + to_erase), slot(count()), slot(i));
+  value_destroy_n(count() - to_erase, to_erase, alloc);
+  set_count(count() - to_erase);
+}
+
+template <typename P>
+void btree_node<P>::rebalance_right_to_left(const int 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.
+  value_init(count(), alloc, parent()->slot(position()));
+
+  // 2) Move the (to_move - 1) values from the right node to the left node.
+  right->uninitialized_move_n(to_move - 1, 0, count() + 1, this, alloc);
+
+  // 3) Move the new delimiting value to the parent from the right node.
+  params_type::move(alloc, right->slot(to_move - 1),
+                    parent()->slot(position()));
+
+  // 4) Shift the values in the right node to their correct position.
+  params_type::move(alloc, right->slot(to_move), right->slot(right->count()),
+                    right->slot(0));
+
+  // 5) Destroy the now-empty to_move entries in the right node.
+  right->value_destroy_n(right->count() - to_move, to_move, alloc);
+
+  if (!leaf()) {
+    // Move the child pointers from the right to the left node.
+    for (int i = 0; i < to_move; ++i) {
+      init_child(count() + i + 1, right->child(i));
+    }
+    for (int i = 0; i <= right->count() - 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 the counts on the left and right nodes.
+  set_count(count() + to_move);
+  right->set_count(right->count() - to_move);
+}
+
+template <typename P>
+void btree_node<P>::rebalance_left_to_right(const int 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.
+
+  if (right->count() >= to_move) {
+    // The original location of the right->count() values are sufficient to hold
+    // the new to_move entries from the parent and left node.
+
+    // 1) Shift existing values in the right node to their correct positions.
+    right->uninitialized_move_n(to_move, right->count() - to_move,
+                                right->count(), right, alloc);
+    for (slot_type *src = right->slot(right->count() - to_move - 1),
+                   *dest = right->slot(right->count() - 1),
+                   *end = right->slot(0);
+         src >= end; --src, --dest) {
+      params_type::move(alloc, src, dest);
+    }
+
+    // 2) Move the delimiting value in the parent to the right node.
+    params_type::move(alloc, parent()->slot(position()),
+                      right->slot(to_move - 1));
+
+    // 3) Move the (to_move - 1) values from the left node to the right node.
+    params_type::move(alloc, slot(count() - (to_move - 1)), slot(count()),
+                      right->slot(0));
+  } else {
+    // The right node does not have enough initialized space to hold the new
+    // to_move entries, so part of them will move to uninitialized space.
+
+    // 1) Shift existing values in the right node to their correct positions.
+    right->uninitialized_move_n(right->count(), 0, to_move, right, alloc);
+
+    // 2) Move the delimiting value in the parent to the right node.
+    right->value_init(to_move - 1, alloc, parent()->slot(position()));
+
+    // 3) Move the (to_move - 1) values from the left node to the right node.
+    const size_type uninitialized_remaining = to_move - right->count() - 1;
+    uninitialized_move_n(uninitialized_remaining,
+                         count() - uninitialized_remaining, right->count(),
+                         right, alloc);
+    params_type::move(alloc, slot(count() - (to_move - 1)),
+                      slot(count() - uninitialized_remaining), right->slot(0));
+  }
+
+  // 4) Move the new delimiting value to the parent from the left node.
+  params_type::move(alloc, slot(count() - to_move), parent()->slot(position()));
+
+  // 5) Destroy the now-empty to_move entries in the left node.
+  value_destroy_n(count() - to_move, to_move, alloc);
+
+  if (!leaf()) {
+    // Move the child pointers from the left to the right node.
+    for (int i = right->count(); i >= 0; --i) {
+      right->init_child(i + to_move, right->child(i));
+      right->clear_child(i);
+    }
+    for (int i = 1; i <= to_move; ++i) {
+      right->init_child(i - 1, child(count() - to_move + i));
+      clear_child(count() - to_move + i);
+    }
+  }
+
+  // Fixup the counts on the left and right nodes.
+  set_count(count() - to_move);
+  right->set_count(right->count() + 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() == kNodeValues);
+
+  // 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 == 0) {
+    dest->set_count(count() - 1);
+  } else if (insert_position == kNodeValues) {
+    dest->set_count(0);
+  } else {
+    dest->set_count(count() / 2);
+  }
+  set_count(count() - dest->count());
+  assert(count() >= 1);
+
+  // Move values from the left sibling to the right sibling.
+  uninitialized_move_n(dest->count(), count(), 0, dest, alloc);
+
+  // Destroy the now-empty entries in the left node.
+  value_destroy_n(count(), dest->count(), alloc);
+
+  // The split key is the largest value in the left sibling.
+  set_count(count() - 1);
+  parent()->emplace_value(position(), alloc, slot(count()));
+  value_destroy(count(), alloc);
+  parent()->init_child(position() + 1, dest);
+
+  if (!leaf()) {
+    for (int i = 0; i <= dest->count(); ++i) {
+      assert(child(count() + i + 1) != nullptr);
+      dest->init_child(i, child(count() + i + 1));
+      clear_child(count() + i + 1);
+    }
+  }
+}
+
+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(count(), alloc, parent()->slot(position()));
+
+  // Move the values from the right to the left node.
+  src->uninitialized_move_n(src->count(), 0, count() + 1, this, alloc);
+
+  // Destroy the now-empty entries in the right node.
+  src->value_destroy_n(0, src->count(), alloc);
+
+  if (!leaf()) {
+    // Move the child pointers from the right to the left node.
+    for (int i = 0; i <= src->count(); ++i) {
+      init_child(count() + i + 1, src->child(i));
+      src->clear_child(i);
+    }
+  }
+
+  // Fixup the counts on the src and dest nodes.
+  set_count(1 + count() + src->count());
+  src->set_count(0);
+
+  // Remove the value on the parent node.
+  parent()->remove_value(position(), alloc);
+}
+
+template <typename P>
+void btree_node<P>::swap(btree_node *x, allocator_type *alloc) {
+  using std::swap;
+  assert(leaf() == x->leaf());
+
+  // Determine which is the smaller/larger node.
+  btree_node *smaller = this, *larger = x;
+  if (smaller->count() > larger->count()) {
+    swap(smaller, larger);
+  }
+
+  // Swap the values.
+  for (slot_type *a = smaller->slot(0), *b = larger->slot(0),
+                 *end = a + smaller->count();
+       a != end; ++a, ++b) {
+    params_type::swap(alloc, a, b);
+  }
+
+  // Move values that can't be swapped.
+  const size_type to_move = larger->count() - smaller->count();
+  larger->uninitialized_move_n(to_move, smaller->count(), smaller->count(),
+                               smaller, alloc);
+  larger->value_destroy_n(smaller->count(), to_move, alloc);
+
+  if (!leaf()) {
+    // Swap the child pointers.
+    std::swap_ranges(&smaller->mutable_child(0),
+                     &smaller->mutable_child(smaller->count() + 1),
+                     &larger->mutable_child(0));
+    // Update swapped children's parent pointers.
+    int i = 0;
+    for (; i <= smaller->count(); ++i) {
+      smaller->child(i)->set_parent(smaller);
+      larger->child(i)->set_parent(larger);
+    }
+    // Move the child pointers that couldn't be swapped.
+    for (; i <= larger->count(); ++i) {
+      smaller->init_child(i, larger->child(i));
+      larger->clear_child(i);
+    }
+  }
+
+  // Swap the counts.
+  swap(mutable_count(), x->mutable_count());
+}
+
+////
+// btree_iterator methods
+template <typename N, typename R, typename P>
+void btree_iterator<N, R, P>::increment_slow() {
+  if (node->leaf()) {
+    assert(position >= node->count());
+    btree_iterator save(*this);
+    while (position == node->count() && !node->is_root()) {
+      assert(node->parent()->child(node->position()) == node);
+      position = node->position();
+      node = node->parent();
+    }
+    if (position == node->count()) {
+      *this = save;
+    }
+  } else {
+    assert(position < node->count());
+    node = node->child(position + 1);
+    while (!node->leaf()) {
+      node = node->child(0);
+    }
+    position = 0;
+  }
+}
+
+template <typename N, typename R, typename P>
+void btree_iterator<N, R, P>::decrement_slow() {
+  if (node->leaf()) {
+    assert(position <= -1);
+    btree_iterator save(*this);
+    while (position < 0 && !node->is_root()) {
+      assert(node->parent()->child(node->position()) == node);
+      position = node->position() - 1;
+      node = node->parent();
+    }
+    if (position < 0) {
+      *this = save;
+    }
+  } else {
+    assert(position >= 0);
+    node = node->child(position);
+    while (!node->leaf()) {
+      node = node->child(node->count());
+    }
+    position = node->count() - 1;
+  }
+}
+
+////
+// btree methods
+template <typename P>
+template <typename Btree>
+void btree<P>::copy_or_move_values_in_order(Btree *x) {
+  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 = x->begin();
+  if (iter == x->end()) return;
+  insert_multi(maybe_move_from_iterator(iter));
+  ++iter;
+  for (; iter != x->end(); ++iter) {
+    // If the btree is not empty, we can just insert the new value at the end
+    // of the tree.
+    internal_emplace(end(), maybe_move_from_iterator(iter));
+  }
+}
+
+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(
+      kNodeValues < (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.
+  using compare_result_type =
+      absl::result_of_t<key_compare(key_type, key_type)>;
+  static_assert(
+      std::is_same<compare_result_type, bool>::value ||
+          std::is_convertible<compare_result_type, absl::weak_ordering>::value,
+      "key comparison function must return absl::{weak,strong}_ordering or "
+      "bool.");
+
+  // Test the assumption made in setting kNodeValueSpace.
+  static_assert(node_type::MinimumOverhead() >= sizeof(void *) + 4,
+                "node space assumption incorrect");
+
+  return true;
+}
+
+template <typename P>
+btree<P>::btree(const key_compare &comp, const allocator_type &alloc)
+    : root_(comp, alloc, EmptyNode()), rightmost_(EmptyNode()), size_(0) {}
+
+template <typename P>
+btree<P>::btree(const btree &x) : btree(x.key_comp(), x.allocator()) {
+  copy_or_move_values_in_order(&x);
+}
+
+template <typename P>
+template <typename... Args>
+auto btree<P>::insert_unique(const key_type &key, Args &&... args)
+    -> std::pair<iterator, bool> {
+  if (empty()) {
+    mutable_root() = rightmost_ = new_leaf_root_node(1);
+  }
+
+  auto 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... Args>
+inline auto btree<P>::insert_hint_unique(iterator position, const key_type &key,
+                                         Args &&... args)
+    -> std::pair<iterator, bool> {
+  if (!empty()) {
+    if (position == end() || compare_keys(key, position.key())) {
+      iterator prev = position;
+      if (position == begin() || compare_keys((--prev).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>
+void btree<P>::insert_iterator_unique(InputIterator b, InputIterator e) {
+  for (; b != e; ++b) {
+    insert_hint_unique(end(), params_type::key(*b), *b);
+  }
+}
+
+template <typename P>
+template <typename ValueType>
+auto btree<P>::insert_multi(const key_type &key, ValueType &&v) -> iterator {
+  if (empty()) {
+    mutable_root() = 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)) {
+      iterator prev = position;
+      if (position == begin() || !compare_keys(key, (--prev).key())) {
+        // prev.key() <= key <= position.key()
+        return internal_emplace(position, std::forward<ValueType>(v));
+      }
+    } else {
+      iterator next = position;
+      ++next;
+      if (next == end() || !compare_keys(next.key(), key)) {
+        // position.key() < key <= next.key()
+        return internal_emplace(next, 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 &x) -> btree & {
+  if (this != &x) {
+    clear();
+
+    *mutable_key_comp() = x.key_comp();
+    if (absl::allocator_traits<
+            allocator_type>::propagate_on_container_copy_assignment::value) {
+      *mutable_allocator() = x.allocator();
+    }
+
+    copy_or_move_values_in_order(&x);
+  }
+  return *this;
+}
+
+template <typename P>
+auto btree<P>::operator=(btree &&x) noexcept -> btree & {
+  if (this != &x) {
+    clear();
+
+    using std::swap;
+    if (absl::allocator_traits<
+            allocator_type>::propagate_on_container_copy_assignment::value) {
+      // Note: `root_` also contains the allocator and the key comparator.
+      swap(root_, x.root_);
+      swap(rightmost_, x.rightmost_);
+      swap(size_, x.size_);
+    } else {
+      if (allocator() == x.allocator()) {
+        swap(mutable_root(), x.mutable_root());
+        swap(*mutable_key_comp(), *x.mutable_key_comp());
+        swap(rightmost_, x.rightmost_);
+        swap(size_, x.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 `x` and `this` to have `x`s key comparator
+        // while moving the values so we can't swap the key comparators.
+        *mutable_key_comp() = x.key_comp();
+        copy_or_move_values_in_order(&x);
+      }
+    }
+  }
+  return *this;
+}
+
+template <typename P>
+auto btree<P>::erase(iterator iter) -> iterator {
+  bool internal_delete = false;
+  if (!iter.node->leaf()) {
+    // Deletion of a value on an internal node. First, move the largest value
+    // from our left child here, then delete that position (in remove_value()
+    // below). We can get to the largest value from our left child by
+    // decrementing iter.
+    iterator internal_iter(iter);
+    --iter;
+    assert(iter.node->leaf());
+    assert(!compare_keys(internal_iter.key(), iter.key()));
+    params_type::move(mutable_allocator(), iter.node->slot(iter.position),
+                      internal_iter.node->slot(internal_iter.position));
+    internal_delete = true;
+  }
+
+  // Delete the key from the leaf.
+  iter.node->remove_value(iter.position, mutable_allocator());
+  --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.node = iter.node->parent();
+  }
+
+  // Adjust our return value. If we're pointing at the end of a node, advance
+  // the iterator.
+  if (res.position == res.node->count()) {
+    res.position = res.node->count() - 1;
+    ++res;
+  }
+
+  return res;
+}
+
+template <typename P>
+auto btree<P>::erase(iterator begin, iterator end)
+    -> std::pair<size_type, iterator> {
+  difference_type count = std::distance(begin, end);
+  assert(count >= 0);
+
+  if (count == 0) {
+    return {0, begin};
+  }
+
+  if (count == size_) {
+    clear();
+    return {count, this->end()};
+  }
+
+  if (begin.node == end.node) {
+    erase_same_node(begin, end);
+    size_ -= count;
+    return {count, rebalance_after_delete(begin)};
+  }
+
+  const size_type target_size = size_ - count;
+  while (size_ > target_size) {
+    if (begin.node->leaf()) {
+      const size_type remaining_to_erase = size_ - target_size;
+      const size_type remaining_in_node = begin.node->count() - begin.position;
+      begin = erase_from_leaf_node(
+          begin, (std::min)(remaining_to_erase, remaining_in_node));
+    } else {
+      begin = erase(begin);
+    }
+  }
+  return {count, begin};
+}
+
+template <typename P>
+void btree<P>::erase_same_node(iterator begin, iterator end) {
+  assert(begin.node == end.node);
+  assert(end.position > begin.position);
+
+  node_type *node = begin.node;
+  size_type to_erase = end.position - begin.position;
+  if (!node->leaf()) {
+    // Delete all children between begin and end.
+    for (size_type i = 0; i < to_erase; ++i) {
+      internal_clear(node->child(begin.position + i + 1));
+    }
+    // Rotate children after end into new positions.
+    for (size_type i = begin.position + to_erase + 1; i <= node->count(); ++i) {
+      node->set_child(i - to_erase, node->child(i));
+      node->clear_child(i);
+    }
+  }
+  node->remove_values_ignore_children(begin.position, to_erase,
+                                      mutable_allocator());
+
+  // Do not need to update rightmost_, because
+  // * either end == this->end(), and therefore node == rightmost_, and still
+  //   exists
+  // * or end != this->end(), and therefore rightmost_ hasn't been erased, since
+  //   it wasn't covered in [begin, end)
+}
+
+template <typename P>
+auto btree<P>::erase_from_leaf_node(iterator begin, size_type to_erase)
+    -> iterator {
+  node_type *node = begin.node;
+  assert(node->leaf());
+  assert(node->count() > begin.position);
+  assert(begin.position + to_erase <= node->count());
+
+  node->remove_values_ignore_children(begin.position, to_erase,
+                                      mutable_allocator());
+
+  size_ -= to_erase;
+
+  return rebalance_after_delete(begin);
+}
+
+template <typename P>
+template <typename K>
+auto btree<P>::erase_unique(const K &key) -> size_type {
+  const iterator iter = internal_find(key);
+  if (iter.node == nullptr) {
+    // The key doesn't exist in the tree, return nothing done.
+    return 0;
+  }
+  erase(iter);
+  return 1;
+}
+
+template <typename P>
+template <typename K>
+auto btree<P>::erase_multi(const K &key) -> size_type {
+  const iterator begin = internal_lower_bound(key);
+  if (begin.node == nullptr) {
+    // The key doesn't exist in the tree, return nothing done.
+    return 0;
+  }
+  // Delete all of the keys between begin and upper_bound(key).
+  const iterator end = internal_end(internal_upper_bound(key));
+  return erase(begin, end).first;
+}
+
+template <typename P>
+void btree<P>::clear() {
+  if (!empty()) {
+    internal_clear(root());
+  }
+  mutable_root() = EmptyNode();
+  rightmost_ = EmptyNode();
+  size_ = 0;
+}
+
+template <typename P>
+void btree<P>::swap(btree &x) {
+  using std::swap;
+  if (absl::allocator_traits<
+          allocator_type>::propagate_on_container_swap::value) {
+    // Note: `root_` also contains the allocator and the key comparator.
+    swap(root_, x.root_);
+  } else {
+    // It's undefined behavior if the allocators are unequal here.
+    assert(allocator() == x.allocator());
+    swap(mutable_root(), x.mutable_root());
+    swap(*mutable_key_comp(), *x.mutable_key_comp());
+  }
+  swap(rightmost_, x.rightmost_);
+  swap(size_, x.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()->count())).node);
+  assert(leftmost()->leaf());
+  assert(rightmost_->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(kNodeValues == node->max_count());
+
+  // First try to make room on the node by rebalancing.
+  node_type *parent = node->parent();
+  if (node != root()) {
+    if (node->position() > 0) {
+      // Try rebalancing with our left sibling.
+      node_type *left = parent->child(node->position() - 1);
+      assert(left->max_count() == kNodeValues);
+      if (left->count() < kNodeValues) {
+        // 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.
+        int to_move = (kNodeValues - left->count()) /
+                      (1 + (insert_position < kNodeValues));
+        to_move = (std::max)(1, to_move);
+
+        if (((insert_position - to_move) >= 0) ||
+            ((left->count() + to_move) < kNodeValues)) {
+          left->rebalance_right_to_left(to_move, node, mutable_allocator());
+
+          assert(node->max_count() - node->count() == to_move);
+          insert_position = insert_position - to_move;
+          if (insert_position < 0) {
+            insert_position = insert_position + left->count() + 1;
+            node = left;
+          }
+
+          assert(node->count() < node->max_count());
+          return;
+        }
+      }
+    }
+
+    if (node->position() < parent->count()) {
+      // Try rebalancing with our right sibling.
+      node_type *right = parent->child(node->position() + 1);
+      assert(right->max_count() == kNodeValues);
+      if (right->count() < kNodeValues) {
+        // 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.
+        int to_move =
+            (kNodeValues - right->count()) / (1 + (insert_position > 0));
+        to_move = (std::max)(1, to_move);
+
+        if ((insert_position <= (node->count() - to_move)) ||
+            ((right->count() + to_move) < kNodeValues)) {
+          node->rebalance_left_to_right(to_move, right, mutable_allocator());
+
+          if (insert_position > node->count()) {
+            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() == kNodeValues);
+    if (parent->count() == kNodeValues) {
+      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->init_child(0, root());
+    mutable_root() = parent;
+    // If the former root was a leaf node, then it's now the rightmost node.
+    assert(!parent->child(0)->leaf() || parent->child(0) == rightmost_);
+  }
+
+  // Split the node.
+  node_type *split_node;
+  if (node->leaf()) {
+    split_node = new_leaf_node(parent);
+    node->split(insert_position, split_node, mutable_allocator());
+    if (rightmost_ == node) rightmost_ = split_node;
+  } else {
+    split_node = new_internal_node(parent);
+    node->split(insert_position, split_node, mutable_allocator());
+  }
+
+  if (insert_position > node->count()) {
+    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 (right->leaf()) {
+    if (rightmost_ == right) rightmost_ = left;
+    delete_leaf_node(right);
+  } else {
+    delete_internal_node(right);
+  }
+}
+
+template <typename P>
+bool btree<P>::try_merge_or_rebalance(iterator *iter) {
+  node_type *parent = iter->node->parent();
+  if (iter->node->position() > 0) {
+    // Try merging with our left sibling.
+    node_type *left = parent->child(iter->node->position() - 1);
+    assert(left->max_count() == kNodeValues);
+    if ((1 + left->count() + iter->node->count()) <= kNodeValues) {
+      iter->position += 1 + left->count();
+      merge_nodes(left, iter->node);
+      iter->node = left;
+      return true;
+    }
+  }
+  if (iter->node->position() < parent->count()) {
+    // Try merging with our right sibling.
+    node_type *right = parent->child(iter->node->position() + 1);
+    assert(right->max_count() == kNodeValues);
+    if ((1 + iter->node->count() + right->count()) <= kNodeValues) {
+      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 > 0))) {
+      int to_move = (right->count() - iter->node->count()) / 2;
+      to_move = (std::min)(to_move, right->count() - 1);
+      iter->node->rebalance_right_to_left(to_move, right, mutable_allocator());
+      return false;
+    }
+  }
+  if (iter->node->position() > 0) {
+    // 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->count()))) {
+      int to_move = (left->count() - iter->node->count()) / 2;
+      to_move = (std::min)(to_move, 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() {
+  if (root()->count() > 0) {
+    return;
+  }
+  // Deleted the last item on the root node, shrink the height of the tree.
+  if (root()->leaf()) {
+    assert(size() == 0);
+    delete_leaf_node(root());
+    mutable_root() = EmptyNode();
+    rightmost_ = EmptyNode();
+  } else {
+    node_type *child = root()->child(0);
+    child->make_root();
+    delete_internal_node(root());
+    mutable_root() = child;
+  }
+}
+
+template <typename P>
+template <typename IterType>
+inline IterType btree<P>::internal_last(IterType iter) {
+  assert(iter.node != nullptr);
+  while (iter.position == iter.node->count()) {
+    iter.position = iter.node->position();
+    iter.node = iter.node->parent();
+    if (iter.node->leaf()) {
+      iter.node = nullptr;
+      break;
+    }
+  }
+  return iter;
+}
+
+template <typename P>
+template <typename... Args>
+inline auto btree<P>::internal_emplace(iterator iter, Args &&... args)
+    -> iterator {
+  if (!iter.node->leaf()) {
+    // 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 int max_count = iter.node->max_count();
+  if (iter.node->count() == max_count) {
+    // Make room in the leaf for the new item.
+    if (max_count < kNodeValues) {
+      // 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((std::min<int>)(kNodeValues, 2 * max_count));
+      iter.node->swap(root(), mutable_allocator());
+      delete_leaf_node(root());
+      mutable_root() = iter.node;
+      rightmost_ = iter.node;
+    } else {
+      rebalance_or_split(&iter);
+    }
+  }
+  iter.node->emplace_value(iter.position, mutable_allocator(),
+                           std::forward<Args>(args)...);
+  ++size_;
+  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> {
+  return internal_locate_impl(key, is_key_compare_to());
+}
+
+template <typename P>
+template <typename K>
+inline auto btree<P>::internal_locate_impl(
+    const K &key, std::false_type /* IsCompareTo */) const
+    -> SearchResult<iterator, false> {
+  iterator iter(const_cast<node_type *>(root()), 0);
+  for (;;) {
+    iter.position = iter.node->lower_bound(key, key_comp()).value;
+    // NOTE: 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->leaf()) {
+      break;
+    }
+    iter.node = iter.node->child(iter.position);
+  }
+  return {iter};
+}
+
+template <typename P>
+template <typename K>
+inline auto btree<P>::internal_locate_impl(
+    const K &key, std::true_type /* IsCompareTo */) const
+    -> SearchResult<iterator, true> {
+  iterator iter(const_cast<node_type *>(root()), 0);
+  for (;;) {
+    SearchResult<int, true> res = iter.node->lower_bound(key, key_comp());
+    iter.position = res.value;
+    if (res.match == MatchKind::kEq) {
+      return {iter, MatchKind::kEq};
+    }
+    if (iter.node->leaf()) {
+      break;
+    }
+    iter.node = iter.node->child(iter.position);
+  }
+  return {iter, MatchKind::kNe};
+}
+
+template <typename P>
+template <typename K>
+auto btree<P>::internal_lower_bound(const K &key) const -> iterator {
+  iterator iter(const_cast<node_type *>(root()), 0);
+  for (;;) {
+    iter.position = iter.node->lower_bound(key, key_comp()).value;
+    if (iter.node->leaf()) {
+      break;
+    }
+    iter.node = iter.node->child(iter.position);
+  }
+  return internal_last(iter);
+}
+
+template <typename P>
+template <typename K>
+auto btree<P>::internal_upper_bound(const K &key) const -> iterator {
+  iterator iter(const_cast<node_type *>(root()), 0);
+  for (;;) {
+    iter.position = iter.node->upper_bound(key, key_comp());
+    if (iter.node->leaf()) {
+      break;
+    }
+    iter.node = iter.node->child(iter.position);
+  }
+  return internal_last(iter);
+}
+
+template <typename P>
+template <typename K>
+auto btree<P>::internal_find(const K &key) const -> iterator {
+  auto 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>
+void btree<P>::internal_clear(node_type *node) {
+  if (!node->leaf()) {
+    for (int i = 0; i <= node->count(); ++i) {
+      internal_clear(node->child(i));
+    }
+    delete_internal_node(node);
+  } else {
+    delete_leaf_node(node);
+  }
+}
+
+template <typename P>
+int 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(0), *lo));
+  }
+  if (hi) {
+    assert(!compare_keys(*hi, node->key(node->count() - 1)));
+  }
+  for (int i = 1; i < node->count(); ++i) {
+    assert(!compare_keys(node->key(i), node->key(i - 1)));
+  }
+  int count = node->count();
+  if (!node->leaf()) {
+    for (int i = 0; i <= node->count(); ++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 == 0) ? lo : &node->key(i - 1),
+          (i == node->count()) ? hi : &node->key(i));
+    }
+  }
+  return count;
+}
+
+}  // namespace container_internal
+}  // namespace absl
+
+#endif  // ABSL_CONTAINER_INTERNAL_BTREE_H_
diff --git a/absl/container/internal/btree_container.h b/absl/container/internal/btree_container.h
new file mode 100644
index 000000000000..726861d5bbb1
--- /dev/null
+++ b/absl/container/internal/btree_container.h
@@ -0,0 +1,609 @@
+// 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/internal/throw_delegate.h"
+#include "absl/container/internal/btree.h"  // IWYU pragma: export
+#include "absl/container/internal/common.h"
+#include "absl/meta/type_traits.h"
+
+namespace absl {
+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<IsTransparent<typename Tree::key_compare>::value>::
+          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::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) {}
+  btree_container(const btree_container &x) = default;
+  btree_container(btree_container &&x) noexcept = default;
+  btree_container &operator=(const btree_container &x) = default;
+  btree_container &operator=(btree_container &&x) 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>
+  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(iterator(first), iterator(last)).second;
+  }
+
+  // Extract routines.
+  node_type extract(iterator position) {
+    // Use Move instead of Transfer, because the rebalancing code expects to
+    // have a valid object to scribble metadata bits on top of.
+    auto node = CommonAccess::Move<node_type>(get_allocator(), position.slot());
+    erase(position);
+    return node;
+  }
+  node_type extract(const_iterator position) {
+    return extract(iterator(position));
+  }
+
+ public:
+  // Utility routines.
+  void clear() { tree_.clear(); }
+  void swap(btree_container &x) { tree_.swap(x.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 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:
+  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::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 constructor.
+  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);
+  }
+
+  // Initializer list constructor.
+  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) {}
+
+  // Lookup routines.
+  template <typename K = key_type>
+  size_type count(const key_arg<K> &key) const {
+    return this->tree_.count_unique(key);
+  }
+
+  // Insertion routines.
+  std::pair<iterator, bool> insert(const value_type &x) {
+    return this->tree_.insert_unique(params_type::key(x), x);
+  }
+  std::pair<iterator, bool> insert(value_type &&x) {
+    return this->tree_.insert_unique(params_type::key(x), std::move(x));
+  }
+  template <typename... Args>
+  std::pair<iterator, bool> emplace(Args &&... args) {
+    init_type v(std::forward<Args>(args)...);
+    return this->tree_.insert_unique(params_type::key(v), std::move(v));
+  }
+  iterator insert(const_iterator position, const value_type &x) {
+    return this->tree_
+        .insert_hint_unique(iterator(position), params_type::key(x), x)
+        .first;
+  }
+  iterator insert(const_iterator position, value_type &&x) {
+    return this->tree_
+        .insert_hint_unique(iterator(position), params_type::key(x),
+                            std::move(x))
+        .first;
+  }
+  template <typename... Args>
+  iterator emplace_hint(const_iterator position, Args &&... args) {
+    init_type v(std::forward<Args>(args)...);
+    return this->tree_
+        .insert_hint_unique(iterator(position), params_type::key(v),
+                            std::move(v))
+        .first;
+  }
+  template <typename InputIterator>
+  void insert(InputIterator b, InputIterator e) {
+    this->tree_.insert_iterator_unique(b, e);
+  }
+  void insert(std::initializer_list<init_type> init) {
+    this->tree_.insert_iterator_unique(init.begin(), init.end());
+  }
+  insert_return_type insert(node_type &&node) {
+    if (!node) return {this->end(), false, node_type()};
+    std::pair<iterator, bool> res =
+        insert(std::move(params_type::element(CommonAccess::GetSlot(node))));
+    if (res.second) {
+      CommonAccess::Reset(&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)),
+        std::move(params_type::element(CommonAccess::GetSlot(node))));
+    if (res.second) CommonAccess::Reset(&node);
+    return res.first;
+  }
+
+  // Deletion routines.
+  template <typename K = key_type>
+  size_type erase(const key_arg<K> &key) {
+    return this->tree_.erase_unique(key);
+  }
+  using super_type::erase;
+
+  // Node extraction routines.
+  template <typename K = key_type>
+  node_type extract(const key_arg<K> &key) {
+    auto it = find(key);
+    return it == this->end() ? node_type() : extract(it);
+  }
+  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(*src_it)).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;
+
+ protected:
+  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::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.
+  template <typename... Args>
+  std::pair<iterator, bool> try_emplace(const key_type &k, Args &&... args) {
+    return this->tree_.insert_unique(
+        k, std::piecewise_construct, std::forward_as_tuple(k),
+        std::forward_as_tuple(std::forward<Args>(args)...));
+  }
+  template <typename... Args>
+  std::pair<iterator, bool> try_emplace(key_type &&k, Args &&... args) {
+    // Note: `key_ref` exists to avoid a ClangTidy warning about moving from `k`
+    // and then using `k` unsequenced. This is safe because the move is into a
+    // forwarding reference and insert_unique guarantees that `key` is never
+    // referenced after consuming `args`.
+    const key_type& key_ref = k;
+    return this->tree_.insert_unique(
+        key_ref, std::piecewise_construct, std::forward_as_tuple(std::move(k)),
+        std::forward_as_tuple(std::forward<Args>(args)...));
+  }
+  template <typename... Args>
+  iterator try_emplace(const_iterator hint, const key_type &k,
+                       Args &&... args) {
+    return this->tree_
+        .insert_hint_unique(iterator(hint), k, std::piecewise_construct,
+                            std::forward_as_tuple(k),
+                            std::forward_as_tuple(std::forward<Args>(args)...))
+        .first;
+  }
+  template <typename... Args>
+  iterator try_emplace(const_iterator hint, key_type &&k, Args &&... args) {
+    // Note: `key_ref` exists to avoid a ClangTidy warning about moving from `k`
+    // and then using `k` unsequenced. This is safe because the move is into a
+    // forwarding reference and insert_hint_unique guarantees that `key` is
+    // never referenced after consuming `args`.
+    const key_type& key_ref = k;
+    return this->tree_
+        .insert_hint_unique(iterator(hint), key_ref, std::piecewise_construct,
+                            std::forward_as_tuple(std::move(k)),
+                            std::forward_as_tuple(std::forward<Args>(args)...))
+        .first;
+  }
+  mapped_type &operator[](const key_type &k) {
+    return try_emplace(k).first->second;
+  }
+  mapped_type &operator[](key_type &&k) {
+    return try_emplace(std::move(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;
+  }
+};
+
+// 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;
+
+  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::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 constructor.
+  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);
+  }
+
+  // Initializer list constructor.
+  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) {}
+
+  // Lookup routines.
+  template <typename K = key_type>
+  size_type count(const key_arg<K> &key) const {
+    return this->tree_.count_multi(key);
+  }
+
+  // Insertion routines.
+  iterator insert(const value_type &x) { return this->tree_.insert_multi(x); }
+  iterator insert(value_type &&x) {
+    return this->tree_.insert_multi(std::move(x));
+  }
+  iterator insert(const_iterator position, const value_type &x) {
+    return this->tree_.insert_hint_multi(iterator(position), x);
+  }
+  iterator insert(const_iterator position, value_type &&x) {
+    return this->tree_.insert_hint_multi(iterator(position), std::move(x));
+  }
+  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) {
+    return this->tree_.insert_multi(init_type(std::forward<Args>(args)...));
+  }
+  template <typename... Args>
+  iterator emplace_hint(const_iterator position, Args &&... args) {
+    return this->tree_.insert_hint_multi(
+        iterator(position), init_type(std::forward<Args>(args)...));
+  }
+
+ private:
+  template <typename... Args>
+  iterator insert_node_helper(node_type &&node, Args &&... args) {
+    if (!node) return this->end();
+    iterator res =
+        insert(std::forward<Args>(args)...,
+               std::move(params_type::element(CommonAccess::GetSlot(node))));
+    CommonAccess::Reset(&node);
+    return res;
+  }
+
+ public:
+  iterator insert(node_type &&node) {
+    return insert_node_helper(std::move(node));
+  }
+  iterator insert(const_iterator hint, node_type &&node) {
+    return insert_node_helper(std::move(node), hint);
+  }
+
+  // Deletion routines.
+  template <typename K = key_type>
+  size_type erase(const key_arg<K> &key) {
+    return this->tree_.erase_multi(key);
+  }
+  using super_type::erase;
+
+  // Node extraction routines.
+  template <typename K = key_type>
+  node_type extract(const key_arg<K> &key) {
+    auto it = find(key);
+    return it == this->end() ? node_type() : extract(it);
+  }
+  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
+    insert(std::make_move_iterator(src.begin()),
+           std::make_move_iterator(src.end()));
+    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;
+
+ public:
+  using mapped_type = typename params_type::mapped_type;
+
+  // Inherit constructors.
+  using super_type::super_type;
+  btree_multimap_container() {}
+};
+
+}  // namespace container_internal
+}  // namespace absl
+
+#endif  // ABSL_CONTAINER_INTERNAL_BTREE_CONTAINER_H_