chromium/base/containers/small_map.h

// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef BASE_CONTAINERS_SMALL_MAP_H_
#define BASE_CONTAINERS_SMALL_MAP_H_

#include <stddef.h>

#include <array>
#include <limits>
#include <map>
#include <memory>
#include <new>
#include <type_traits>
#include <utility>

#include "base/check.h"
#include "base/check_op.h"
#include "base/containers/adapters.h"
#include "base/containers/span.h"
#include "base/memory/stack_allocated.h"
#include "base/numerics/safe_conversions.h"
#include "base/types/to_address.h"

inline constexpr size_t kUsingFullMapSentinel =;

namespace base {

// small_map is a container with a std::map-like interface. It starts out backed
// by an unsorted array but switches to some other container type if it grows
// beyond this fixed size.
//
// Please see //base/containers/README.md for an overview of which container
// to select.
//
// PROS
//
//  - Good memory locality and low overhead for smaller maps.
//  - Handles large maps without the degenerate performance of flat_map.
//
// CONS
//
//  - Larger code size than the alternatives.
//
// IMPORTANT NOTES
//
//  - Iterators are invalidated across mutations.
//
// DETAILS
//
// base::small_map will pick up the comparator from the underlying map type. In
// std::map only a "less" operator is defined, which requires us to do two
// comparisons per element when doing the brute-force search in the simple
// array. std::unordered_map has a key_equal function which will be used.
//
// We define default overrides for the common map types to avoid this
// double-compare, but you should be aware of this if you use your own operator<
// for your map and supply your own version of == to the small_map. You can use
// regular operator== by just doing:
//
//   base::small_map<std::map<MyKey, MyValue>, 4, std::equal_to<KyKey>>
//
//
// USAGE
// -----
//
// NormalMap:  The map type to fall back to. This also defines the key and value
//             types for the small_map.
// kArraySize:  The size of the initial array of results. This will be allocated
//              with the small_map object rather than separately on the heap.
//              Once the map grows beyond this size, the map type will be used
//              instead.
// EqualKey:  A functor which tests two keys for equality. If the wrapped map
//            type has a "key_equal" member (unordered_map does), then that will
//            be used by default. If the wrapped map type has a strict weak
//            ordering "key_compare" (std::map does), that will be used to
//            implement equality by default.
// MapInit: A functor that takes a NormalMap* and uses it to initialize the map.
//          This functor will be called at most once per small_map, when the map
//          exceeds the threshold of kArraySize and we are about to copy values
//          from the array to the map. The functor *must* initialize the
//          NormalMap* argument with placement new, since after it runs we
//          assume that the NormalMap has been initialized.
//
// Example:
//   base::small_map<std::map<string, int>> days;
//   days["sunday"   ] = 0;
//   days["monday"   ] = 1;
//   days["tuesday"  ] = 2;
//   days["wednesday"] = 3;
//   days["thursday" ] = 4;
//   days["friday"   ] = 5;
//   days["saturday" ] = 6;

namespace internal {

template <typename NormalMap>
class small_map_default_init {};

// has_key_equal<M>::value is true iff there exists a type M::key_equal. This is
// used to dispatch to one of the select_equal_key<> metafunctions below.
template <typename M>
struct has_key_equal {};
template <typename M> const bool has_key_equal<M>::value;

// Base template used for map types that do NOT have an M::key_equal member,
// e.g., std::map<>. These maps have a strict weak ordering comparator rather
// than an equality functor, so equality will be implemented in terms of that
// comparator.
//
// There's a partial specialization of this template below for map types that do
// have an M::key_equal member.
template <typename M, bool has_key_equal_value>
struct select_equal_key {};

// Partial template specialization handles case where M::key_equal exists, e.g.,
// unordered_map<>.
select_equal_key<M, true>;

}  // namespace internal

template <typename NormalMap,
          size_t kArraySize = 4,
          typename EqualKey = typename internal::select_equal_key<
              NormalMap,
              internal::has_key_equal<NormalMap>::value>::equal_key,
          typename MapInit = internal::small_map_default_init<NormalMap>>
class small_map {
  static_assert(kArraySize > 0, "Initial size must be greater than 0");
  static_assert(kArraySize != kUsingFullMapSentinel,
                "Initial size out of range");

 public:
  using key_type = NormalMap::key_type;
  using data_type = NormalMap::mapped_type;
  using mapped_type = NormalMap::mapped_type;
  using value_type = NormalMap::value_type;
  using key_equal = EqualKey;

  constexpr small_map() :{}

  constexpr explicit small_map(const MapInit& functor) :{}

  // Allow copy-constructor and assignment, since STL allows them too.
  constexpr small_map(const small_map& src) {}

  constexpr void operator=(const small_map& src) {}

  ~small_map() {}

  // The elements in the inline array storage. They are held in a union so that
  // they can be constructed lazily as they are inserted, and can be destroyed
  // when they are erased.
  union ArrayElement {
    ArrayElement() {}
    ~ArrayElement() {}

    value_type value;
  };

  class const_iterator;

  class iterator {
    STACK_ALLOCATED();

    using map_iterator = NormalMap::iterator;
    using array_iterator = span<ArrayElement>::iterator;

   public:
    using iterator_category = map_iterator::iterator_category;
    using value_type = map_iterator::value_type;
    using difference_type = map_iterator::difference_type;
    using pointer = map_iterator::pointer;
    using reference = map_iterator::reference;

    iterator() = default;

    constexpr iterator& operator++() {
      if (has_array_iter()) {
        ++array_iter_;
      } else {
        ++map_iter_;
      }
      return *this;
    }

    constexpr iterator operator++(int /*unused*/) {
      iterator result(*this);
      ++(*this);
      return result;
    }

    constexpr value_type* operator->() const {
      return has_array_iter() ? std::addressof(array_iter_->value)
                              : std::addressof(*map_iter_);
    }

    constexpr value_type& operator*() const {
      return has_array_iter() ? array_iter_->value : *map_iter_;
    }

    constexpr bool operator==(const iterator& other) const {
      if (has_array_iter()) {
        return array_iter_ == other.array_iter_;
      } else {
        return !other.has_array_iter() && map_iter_ == other.map_iter_;
      }
    }

   private:
    friend class small_map;
    friend class const_iterator;
    constexpr explicit iterator(const array_iterator& init)
        : array_iter_(init) {}
    constexpr explicit iterator(const map_iterator& init) : map_iter_(init) {}

    constexpr bool has_array_iter() const {
      return base::to_address(array_iter_) != nullptr;
    }

    array_iterator array_iter_;
    map_iterator map_iter_;
  };

  class const_iterator {
    STACK_ALLOCATED();

    using map_iterator = NormalMap::const_iterator;
    using array_iterator = span<const ArrayElement>::iterator;

   public:
    using iterator_category = map_iterator::iterator_category;
    using value_type = map_iterator::value_type;
    using difference_type = map_iterator::difference_type;
    using pointer = map_iterator::pointer;
    using reference = map_iterator::reference;

    const_iterator() = default;

    // Non-explicit constructor lets us convert regular iterators to const
    // iterators.
    constexpr const_iterator(const iterator& other)
        : array_iter_(other.array_iter_), map_iter_(other.map_iter_) {}

    constexpr const_iterator& operator++() {
      if (has_array_iter()) {
        ++array_iter_;
      } else {
        ++map_iter_;
      }
      return *this;
    }

    constexpr const_iterator operator++(int /*unused*/) {
      const_iterator result(*this);
      ++(*this);
      return result;
    }

    constexpr const value_type* operator->() const {
      return has_array_iter() ? std::addressof(array_iter_->value)
                              : std::addressof(*map_iter_);
    }

    constexpr const value_type& operator*() const {
      return has_array_iter() ? array_iter_->value : *map_iter_;
    }

    constexpr bool operator==(const const_iterator& other) const {
      if (has_array_iter()) {
        return array_iter_ == other.array_iter_;
      }
      return !other.has_array_iter() && map_iter_ == other.map_iter_;
    }

   private:
    friend class small_map;
    constexpr explicit const_iterator(const array_iterator& init)
        : array_iter_(init) {}
    constexpr explicit const_iterator(const map_iterator& init)
        : map_iter_(init) {}

    constexpr bool has_array_iter() const {
      return base::to_address(array_iter_) != nullptr;
    }

    array_iterator array_iter_;
    map_iterator map_iter_;
  };

  constexpr iterator find(const key_type& key) {}

  constexpr const_iterator find(const key_type& key) const {}

  // Invalidates iterators.
  constexpr data_type& operator[](const key_type& key)
    requires(std::is_default_constructible_v<data_type>)
  {}

  // Invalidates iterators.
  constexpr std::pair<iterator, bool> insert(const value_type& x) {}

  // Invalidates iterators.
  template <class InputIterator>
  constexpr void insert(InputIterator f, InputIterator l) {}

  // Invalidates iterators.
  template <typename... Args>
  constexpr std::pair<iterator, bool> emplace(Args&&... args) {}

  constexpr iterator begin() {}

  constexpr const_iterator begin() const {}

  constexpr iterator end() {}

  constexpr const_iterator end() const {}

  constexpr void clear() {}

  // Invalidates iterators. Returns iterator following the last removed element.
  constexpr iterator erase(const iterator& position) {}

  constexpr size_t erase(const key_type& key) {}

  constexpr size_t count(const key_type& key) const {}

  constexpr size_t size() const {}

  constexpr bool empty() const {}

  // Returns true if we have fallen back to using the underlying map
  // representation.
  constexpr bool UsingFullMap() const {}

  constexpr NormalMap* map() {}

  constexpr const NormalMap* map() const {}

 private:
  // When `size_ == kUsingFullMapSentinel`, we have switched storage strategies
  // from `array_[kArraySize] to `NormalMap map_`. See ConvertToRealMap and
  // UsingFullMap.
  size_t size_ = 0u;

  MapInit functor_;

  // We want to call constructors and destructors manually, but we don't want
  // to allocate and deallocate the memory used for them separately. Since
  // array_ and map_ are mutually exclusive, we'll put them in a union.
  using ArrayMap = std::array<ArrayElement, kArraySize>;
  union {
    ArrayMap array_;
    NormalMap map_;
  };

  constexpr span<ArrayElement> sized_array_span() {}
  constexpr span<const ArrayElement> sized_array_span() const {}

  constexpr void ConvertToRealMap() {}

  // Helpers for constructors and destructors.
  constexpr void InitEmpty() {}
  constexpr void InitFrom(const small_map& src) {}

  constexpr void Destroy() {}
};

}  // namespace base

#endif  // BASE_CONTAINERS_SMALL_MAP_H_