Files
carbon-lang/common/map.h
T
Chandler Carruth d037848a96 Replace hashtable ForEach callback with range-based iteration (#7806)
Replaces the callback-based `ForEach` methods on `RawHashtable`, `Map`,
and
`Set` with a range object supporting range-for loops, structured
bindings, and
the standard range concepts.

- Adds `.entries()` on `Map`, `Set`, and `RawHashtable`, returning a
range that
  models `std::ranges::forward_range` and `std::ranges::common_range`.
  Obtaining one is an explicit call rather than `begin()`/`end()` on the
container, as scanning a whole table is costly and shouldn't be hidden.
- Iterating a `Map` yields a `std::pair` of key and value references,
which
fits in two registers and is returned without being materialized in
memory.
- `Map::Range` and `Set::Range` are aliases of the raw hashtable's range
rather
than wrappers around it. The raw iterator produces the user-facing
reference
itself -- a `KeyT&` for a set, a pair of references for a map -- picked
by
`StorageEntry`, which is already specialized on whether there is a value
  type. That leaves one iterator to reason about instead of three.
- Deletes the rvalue `.entries()` overloads on the owning containers, as
a
  range built from a temporary table would dangle. Views don't own their
  storage, so the operation remains available on them.
- In release builds, the walk over the groups is a single induction
variable: a
  negative byte offset counting up to zero, anchored at the ends of the
metadata and entry arrays. Both arrays are then reached by indexed
addressing
off a base that stays put, and the entry pointer is formed only once a
group
  with a present entry has been found.
- In debug builds, the range hashes the table's metadata when it is
built and
re-checks that hash when it is destroyed, catching mutation of the table
while a range is live. It also picks a random starting group and a
random odd
group stride, which varies the traversal order between ranges while
still
visiting every group exactly once. That entropy is drawn when the range
is
built rather than in `begin()`, so `begin()` stays a pure function of
the
  range and the multi-pass guarantee holds.
- Removes `ForEachEntry` and all of its callers.

Measured against the iteration benchmark added in its own commit, a
traversal is at or ahead of what the callback compiled to across nearly
the
whole size range. The largest tables spend 3-5% fewer cycles, small
`Set`s as
much as 24% fewer, and instruction counts stay within about 1%. What
remains
behind is a handful of mid-sized `Map`s by up to 1%, and `Set` at 65536,
which
sits at exactly half its load factor, by 2%.

Both revisions were built with `-c opt --copt=-march=x86-64-v3` and
compared
with:

```
./scripts/bench_runner.py --exp_benchmark=... --base_benchmark=... \
    --benchmark_args=--benchmark_perf_counters=INSTRUCTIONS,CYCLES \
    --benchmark_args='--benchmark_filter=(Set|Map)Iterate<(Set|Map)<' \
    --extra_metrics_filter='(INSTRUCTIONS|CYCLES)'
```

Trimmed below to the primary integer configurations and to the two
counters;
the pointer- and string-keyed configurations follow the same pattern.

```
 Benchmark                             ┃           CYCLES            ┃        INSTRUCTIONS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 BM_MapIterate<Map<int, int>>/1....... │ 👍  -6.032%      p=1.14e-05 │      ??          p=0.752
                             baseline: │     12.06      ±   1.520%   │     64         ±   3.125%
                           experiment: │     11.33      ±   2.765%   │     65.5       ±   3.817%
                                       │                             │
 BM_MapIterate<Map<int, int>>/2....... │      ??          p=0.155    │      ??          p=0.343
                             baseline: │      7.587     ±   1.285%   │     41         ±   0.000%
                           experiment: │      7.652     ±   0.865%   │     41         ±   2.439%
                                       │                             │
 BM_MapIterate<Map<int, int>>/3....... │      ??          p=0.343    │ 👍  -1.020%      p=0.0039
                             baseline: │      6.663     ±   4.260%   │     32.67      ±   2.041%
                           experiment: │      6.368     ±  12.224%   │     32.33      ±   2.062%
                                       │                             │
 BM_MapIterate<Map<int, int>>/4....... │      ??          p=0.343    │ 👍  -1.786%      p=0.0297
                             baseline: │      6.091     ±  15.470%   │     28         ±   3.571%
                           experiment: │      5.957     ±   8.932%   │     27.5       ±   3.636%
                                       │                             │
 BM_MapIterate<Map<int, int>>/8....... │      ??          p=0.323    │ 👍  -1.220%      p=0.000148
                             baseline: │      4.845     ±   0.800%   │     20.5       ±   0.000%
                           experiment: │      4.814     ±   3.585%   │     20.25      ±   0.000%
                                       │                             │
 BM_MapIterate<Map<int, int>>/16...... │ 👍  -2.195%      p=0.00908  │ 👍   0.769%      p=6.58e-06
                             baseline: │      4.312     ±   0.187%   │     16.25      ±   0.000%
                           experiment: │      4.218     ±   2.368%   │     16.13      ±   0.000%
                                       │                             │
 BM_MapIterate<Map<int, int>>/32...... │      ??          p=0.236    │ 👍   0.442%      p=9.53e-06
                             baseline: │      4.051     ±   1.084%   │     14.13      ±   0.000%
                           experiment: │      4.063     ±   0.737%   │     14.06      ±   0.000%
                                       │                             │
 BM_MapIterate<Map<int, int>>/64...... │      ??          p=0.693    │ 👎   0.227%      p=4.52e-06
                             baseline: │      4.021     ±   0.239%   │     13.75      ±   0.000%
                           experiment: │      4.019     ±   0.417%   │     13.78      ±   0.000%
                                       │                             │
 BM_MapIterate<Map<int, int>>/256..... │ 👍   0.360%      p=0.00119  │ 👎   0.754%      p=1.37e-05
                             baseline: │      3.996     ±   0.173%   │     13.47      ±   0.000%
                           experiment: │      3.982     ±   0.272%   │     13.57      ±   0.000%
                                       │                             │
 BM_MapIterate<Map<int, int>>/4096.... │ 👍   0.581%      p=1.96e-05 │ 👎   0.923%      p=1.96e-05
                             baseline: │      4.005     ±   0.816%   │     13.38      ±   0.000%
                           experiment: │      3.981     ±   0.192%   │     13.5       ±   0.000%
                                       │                             │
 BM_MapIterate<Map<int, int>>/65536... │ 👍  -4.957%      p=1.14e-05 │ 👎   0.934%      p=1.14e-05
                             baseline: │      5.307     ±   0.501%   │     13.38      ±   0.000%
                           experiment: │      5.044     ±   1.746%   │     13.5       ±   0.000%
                                       │                             │
 BM_MapIterate<Map<int, int>>/1048576. │ 👍  -3.947%      p=9.09e-05 │ 👎   0.935%      p=3.3e-05
                             baseline: │      6.074     ±   0.807%   │     13.38      ±   0.000%
                           experiment: │      5.834     ±   2.159%   │     13.5       ±   0.000%
                                       │                             │
 BM_MapIterate<Map<int, int>>/16777216 │      ??          p=0.155    │ 👎   0.935%      p=2.11e-05
                             baseline: │      5.082     ±   3.650%   │     13.38      ±   0.000%
                           experiment: │      5.012     ±   1.316%   │     13.5       ±   0.000%
                                       │                             │
 BM_MapIterate<Map<int, int>>/56...... │ 👎   0.825%      p=0.0268   │ 👍   0.270%      p=1.14e-05
                             baseline: │      3.918     ±   0.501%   │     13.21      ±   0.000%
                           experiment: │      3.951     ±   0.342%   │     13.18      ±   0.000%
                                       │                             │
 BM_MapIterate<Map<int, int>>/224..... │ 👎   0.788%      p=0.000504 │ 👎   0.346%      p=1.64e-05
                             baseline: │      3.895     ±   0.111%   │     12.89      ±   0.000%
                           experiment: │      3.926     ±   0.285%   │     12.94      ±   0.000%
                                       │                             │
 BM_MapIterate<Map<int, int>>/3584.... │ 👎   1.028%      p=0.000148 │ 👎   0.545%      p=1.14e-05
                             baseline: │      3.913     ±   0.427%   │     12.79      ±   0.000%
                           experiment: │      3.954     ±   0.325%   │     12.86      ±   0.000%
                                       │                             │
 BM_MapIterate<Map<int, int>>/57344... │      ??          p=0.236    │ 👎   0.558%      p=2.55e-06
                             baseline: │      4.574     ±   0.721%   │     12.79      ±   0.000%
                           experiment: │      4.51      ±   3.709%   │     12.86      ±   0.000%
                                       │                             │
 BM_MapIterate<Map<int, int>>/917504.. │ 👍  -3.826%      p=6.58e-06 │ 👎   0.559%      p=2.33e-05
                             baseline: │      5.221     ±   0.507%   │     12.79      ±   0.000%
                           experiment: │      5.021     ±   0.556%   │     12.86      ±   0.000%
                                       │                             │
 BM_MapIterate<Map<int, int>>/14680064 │ 👍  -3.839%      p=1.37e-05 │ 👎   0.559%      p=3.31e-05
                             baseline: │      5.129     ±   1.194%   │     12.79      ±   0.000%
                           experiment: │      4.932     ±   1.475%   │     12.86      ±   0.000%
                                       │                             │

 Benchmark                        ┃           CYCLES            ┃        INSTRUCTIONS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 BM_SetIterate<Set<int>>/1....... │ 👍  -3.104%      p=0.000583 │      ??          p=0.206
                        baseline: │     11.2       ±   6.323%   │     60         ±   3.333%
                      experiment: │     10.85      ±   5.820%   │     61         ±   3.279%
                                  │                             │
 BM_SetIterate<Set<int>>/2....... │ 👍  -7.037%      p=0.0362   │      ??          p=0.155
                        baseline: │      7.086     ±  16.857%   │     37         ±   0.000%
                      experiment: │      6.587     ±   0.479%   │     36         ±   4.167%
                                  │                             │
 BM_SetIterate<Set<int>>/3....... │ 👎   1.400%      p=2.34e-05 │ 👍  -1.163%      p=0.00136
                        baseline: │      5.363     ±   0.463%   │     28.67      ±   2.326%
                      experiment: │      5.438     ±  32.763%   │     28.33      ±   1.176%
                                  │                             │
 BM_SetIterate<Set<int>>/4....... │      ??          p=0.968    │      ??          p=0.286
                        baseline: │      4.642     ±  32.751%   │     23.5       ±   2.128%
                      experiment: │      4.658     ±  38.416%   │     23.63      ±   3.704%
                                  │                             │
 BM_SetIterate<Set<int>>/8....... │ 👍 -23.823%      p=3.74e-06 │ 👍  -1.515%      p=5.52e-05
                        baseline: │      4.701     ±   6.589%   │     16.5       ±   0.000%
                      experiment: │      3.581     ±   7.790%   │     16.25      ±   0.000%
                                  │                             │
 BM_SetIterate<Set<int>>/16...... │ 👍  -4.502%      p=1.37e-05 │ 👍  -1.020%      p=3.31e-05
                        baseline: │      3.124     ±   0.585%   │     12.25      ±   0.000%
                      experiment: │      2.983     ±   0.625%   │     12.13      ±   0.000%
                                  │                             │
 BM_SetIterate<Set<int>>/32...... │ 👍  -4.032%      p=5.46e-06 │ 👍   0.617%      p=1.96e-05
                        baseline: │      2.957     ±   0.260%   │     10.13      ±   0.000%
                      experiment: │      2.838     ±   0.434%   │     10.06      ±   0.000%
                                  │                             │
 BM_SetIterate<Set<int>>/64...... │ 👍  -5.054%      p=4.52e-06 │ 👎   0.321%      p=1.37e-05
                        baseline: │      2.937     ±   0.301%   │      9.75      ±   0.000%
                      experiment: │      2.788     ±   1.143%   │      9.781     ±   0.000%
                                  │                             │
 BM_SetIterate<Set<int>>/256..... │ 👍  -5.325%      p=1.14e-05 │ 👎   1.073%      p=6.58e-06
                        baseline: │      2.916     ±   0.220%   │      9.469     ±   0.000%
                      experiment: │      2.761     ±   0.142%   │      9.57      ±   0.000%
                                  │                             │
 BM_SetIterate<Set<int>>/4096.... │ 👍  -4.865%      p=4.52e-06 │ 👎   1.317%      p=2.34e-05
                        baseline: │      2.921     ±   0.194%   │      9.381     ±   0.000%
                      experiment: │      2.779     ±   0.224%   │      9.504     ±   0.000%
                                  │                             │
 BM_SetIterate<Set<int>>/65536... │ 👎   1.961%      p=3.93e-05 │ 👎   1.332%      p=1.49e-05
                        baseline: │      4.015     ±   0.482%   │      9.375     ±   0.000%
                      experiment: │      4.094     ±   0.613%   │      9.5       ±   0.000%
                                  │                             │
 BM_SetIterate<Set<int>>/1048576. │ 👍  -4.843%      p=1.14e-05 │ 👎   1.333%      p=5.38e-06
                        baseline: │      5.239     ±   0.144%   │      9.375     ±   0.000%
                      experiment: │      4.986     ±   0.139%   │      9.5       ±   0.000%
                                  │                             │
 BM_SetIterate<Set<int>>/16777216 │ 👍   0.840%      p=0.0362   │ 👎   1.333%      p=2.52e-06
                        baseline: │      3.719     ±   1.420%   │      9.375     ±   0.000%
                      experiment: │      3.688     ±   1.308%   │      9.5       ±   0.000%
                                  │                             │
 BM_SetIterate<Set<int>>/56...... │ 👍  -2.857%      p=9.53e-06 │ 👍   0.388%      p=3.31e-05
                        baseline: │      2.942     ±   0.439%   │      9.214     ±   0.000%
                      experiment: │      2.858     ±   0.619%   │      9.179     ±   0.000%
                                  │                             │
 BM_SetIterate<Set<int>>/224..... │ 👍  -2.161%      p=2.34e-05 │ 👎   0.502%      p=4.52e-06
                        baseline: │      2.888     ±   0.347%   │      8.893     ±   0.000%
                      experiment: │      2.826     ±   0.450%   │      8.938     ±   0.000%
                                  │                             │
 BM_SetIterate<Set<int>>/3584.... │ 👍  -1.750%      p=6.58e-06 │ 👎   0.793%      p=2.34e-05
                        baseline: │      2.89      ±   0.261%   │      8.792     ±   0.000%
                      experiment: │      2.84      ±   0.411%   │      8.862     ±   0.000%
                                  │                             │
 BM_SetIterate<Set<int>>/57344... │      ??          p=0.502    │ 👎   0.812%      p=2.78e-05
                        baseline: │      3.684     ±   4.246%   │      8.786     ±   0.000%
                      experiment: │      3.644     ±   4.431%   │      8.857     ±   0.000%
                                  │                             │
 BM_SetIterate<Set<int>>/917504.. │ 👍  -2.629%      p=0.000148 │ 👎   0.813%      p=3.08e-06
                        baseline: │      4.372     ±   0.693%   │      8.786     ±   0.000%
                      experiment: │      4.257     ±   0.210%   │      8.857     ±   0.000%
                                  │                             │
 BM_SetIterate<Set<int>>/14680064 │ 👍  -2.927%      p=0.0219   │ 👎   0.813%      p=3.03e-06
                        baseline: │      4.154     ±   3.286%   │      8.786     ±   0.000%
                      experiment: │      4.032     ±   3.198%   │      8.857     ±   0.000%
                                  │                             │
```

Assisted-by: Antigravity with Opus
2026-09-18 20:19:46 +00:00

596 lines
24 KiB
C++

// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#ifndef CARBON_COMMON_MAP_H_
#define CARBON_COMMON_MAP_H_
#include <algorithm>
#include <concepts>
#include <utility>
#include "common/check.h"
#include "common/concepts.h"
#include "common/hashtable_key_context.h"
#include "common/raw_hashtable.h"
#include "llvm/Support/Compiler.h"
namespace Carbon {
// Forward declarations to resolve cyclic references.
template <typename KeyT, typename ValueT, typename KeyContextT>
class MapView;
template <typename KeyT, typename ValueT, typename KeyContextT>
class MapBase;
template <typename KeyT, typename ValueT, ssize_t SmallSize,
typename KeyContextT>
class Map;
// A read-only view type for a map from key to value.
//
// This view is a cheap-to-copy type that should be passed by value, but
// provides view or read-only reference semantics to the underlying map data
// structure.
//
// This should always be preferred to a `const`-ref parameter for the `MapBase`
// or `Map` type as it provides more flexibility and a cleaner API. By default a
// `MapView` provides no more immutability than a `const Map`: elements can't be
// added or removed, but both keys and values can be mutated, and the user is
// responsible for avoiding mutations that affect the key's hash value or
// equality comparison. However, the key and value types can be
// `const`-qualified to prevent those mutations. For example, a `MapView<K, V>`
// can be converted to `MapView<const K, V>` to prevent mutating the keys. As
// with any other view type, `const` on the `MapView` itself is "shallow": it
// prevents rebinding the `MapView` to a different underlying map, but doesn't
// affect mutability of the underlying map.
//
// A specific `KeyContextT` type can optionally be provided to configure how
// keys will be hashed and compared. The default is `DefaultKeyContext` which is
// stateless and will hash using `Carbon::HashValue` and compare using
// `operator==`. Every method accepting a lookup key or operating on the keys in
// the table will also accept an instance of this type. For stateless context
// types, including the default, an instance will be default constructed if not
// provided to these methods. However, stateful contexts should be constructed
// and passed in explicitly. The context type should be small and reasonable to
// pass by value, often a wrapper or pointer to the relevant context needed for
// hashing and comparing keys. For more details about the key context, see
// `hashtable_key_context.h`.
template <typename InputKeyT, typename InputValueT,
typename InputKeyContextT = DefaultKeyContext>
class MapView
: RawHashtable::ViewImpl<InputKeyT, InputValueT, InputKeyContextT> {
using ImplT =
RawHashtable::ViewImpl<InputKeyT, InputValueT, InputKeyContextT>;
using EntryT = ImplT::EntryT;
public:
using KeyT = ImplT::KeyT;
using ValueT = ImplT::ValueT;
using KeyContextT = ImplT::KeyContextT;
using MetricsT = ImplT::MetricsT;
// A key and its value, as a pair of references. This is what iterating the
// map produces; there is no object in the table combining the two.
using Entry = ImplT::EntryRefT;
// A range over the key-value entries of the map. Bound to the lifetime of
// the viewed map, and invalidated by mutating it.
using Range = ImplT::EntryRange;
// This type represents the result of lookup operations. It encodes whether
// the lookup was a success as well as accessors for the key and value.
class LookupKVResult {
public:
LookupKVResult() = default;
explicit LookupKVResult(EntryT* entry) : entry_(entry) {}
explicit operator bool() const { return entry_ != nullptr; }
auto key() const -> KeyT& { return entry_->key(); }
auto value() const -> ValueT& { return entry_->value(); }
private:
EntryT* entry_ = nullptr;
};
// Enable implicit conversions that add `const`-ness to either key or value
// type. This is always safe to do with a view. We use a template to avoid
// needing all 3 versions.
template <typename OtherKeyT, typename OtherValueT>
explicit(false)
MapView(MapView<OtherKeyT, OtherValueT, KeyContextT> other_view)
requires(SameAsOneOf<KeyT, OtherKeyT, const OtherKeyT> &&
SameAsOneOf<ValueT, OtherValueT, const OtherValueT>)
: ImplT(other_view) {}
// Tests whether a key is present in the map.
template <typename LookupKeyT>
auto Contains(LookupKeyT lookup_key,
KeyContextT key_context = KeyContextT()) const -> bool;
// Lookup a key in the map.
template <typename LookupKeyT>
auto Lookup(LookupKeyT lookup_key,
KeyContextT key_context = KeyContextT()) const -> LookupKVResult;
// Lookup a key in the map and try to return a pointer to its value. Returns
// null on a missing key.
template <typename LookupKeyT>
auto operator[](LookupKeyT lookup_key) const -> ValueT*
requires(std::default_initializable<KeyContextT>);
// Returns a range for iterating over all key-value entries in the map.
auto entries() const -> Range;
// This routine is relatively inefficient and only intended for use in
// benchmarking or logging of performance anomalies. The specific metrics
// returned have no specific guarantees beyond being informative in
// benchmarks.
auto ComputeMetrics(KeyContextT key_context = KeyContextT()) -> MetricsT {
return ImplT::ComputeMetricsImpl(key_context);
}
private:
template <typename MapKeyT, typename MapValueT, ssize_t MinSmallSize,
typename KeyContextT>
friend class Map;
friend class MapBase<KeyT, ValueT, KeyContextT>;
friend class MapView<const KeyT, ValueT, KeyContextT>;
friend class MapView<KeyT, const ValueT, KeyContextT>;
friend class MapView<const KeyT, const ValueT, KeyContextT>;
MapView() = default;
explicit(false) MapView(ImplT base) : ImplT(base) {}
MapView(ssize_t size, RawHashtable::Storage* storage)
: ImplT(size, storage) {}
};
// A base class for a `Map` type that remains mutable while type-erasing the
// `SmallSize` (SSO) template parameter.
//
// Note that `MapBase` has "shallow" const semantics: a `const MapBase<K, V>&`
// can't be used to mutate the map data structure itself (e.g. by changing the
// number of elements), but it can be used to mutate the keys and values it
// contains. The user is responsible for avoiding mutations that would change
// the hash value or equality of a key. A `MapView` with const-qualified key and
// value types can be used to provide read-only access to the elements of a
// `MapBase<T>`.
//
// A pointer or reference to this type is the preferred way to pass a mutable
// handle to a `Map` type across API boundaries as it avoids encoding specific
// SSO sizing information while providing a near-complete mutable API.
template <typename InputKeyT, typename InputValueT,
typename InputKeyContextT = DefaultKeyContext>
class MapBase : protected RawHashtable::BaseImpl<InputKeyT, InputValueT,
InputKeyContextT> {
protected:
using ImplT =
RawHashtable::BaseImpl<InputKeyT, InputValueT, InputKeyContextT>;
using EntryT = ImplT::EntryT;
public:
using KeyT = ImplT::KeyT;
using ValueT = ImplT::ValueT;
using KeyContextT = ImplT::KeyContextT;
using ViewT = MapView<KeyT, ValueT, KeyContextT>;
using LookupKVResult = ViewT::LookupKVResult;
using MetricsT = ImplT::MetricsT;
using Entry = ViewT::Entry;
using Range = ViewT::Range;
// The result type for insertion operations both indicates whether an insert
// was needed (as opposed to finding an existing element), and provides access
// to the element's key and value.
class InsertKVResult {
public:
InsertKVResult() = default;
explicit InsertKVResult(bool inserted, EntryT& entry)
: entry_(&entry), inserted_(inserted) {}
auto is_inserted() const -> bool { return inserted_; }
auto key() const -> KeyT& { return entry_->key(); }
auto value() const -> ValueT& { return entry_->value(); }
private:
EntryT* entry_;
bool inserted_;
};
// Implicitly convertible to the relevant view type.
//
// NOLINTNEXTLINE(google-explicit-constructor): Designed to implicitly decay.
explicit(false) operator ViewT() const { return this->view_impl(); }
// We can't chain the above conversion with the conversions on `ViewT` to add
// const, so explicitly support adding const to produce a view here.
template <typename OtherKeyT, typename OtherValueT>
// NOLINTNEXTLINE(google-explicit-constructor)
explicit(false) operator MapView<OtherKeyT, OtherValueT, KeyContextT>() const
requires(SameAsOneOf<OtherKeyT, KeyT, const KeyT> &&
SameAsOneOf<OtherValueT, ValueT, const ValueT>)
{
return ViewT(*this);
}
// Convenience forwarder to the view type.
template <typename LookupKeyT>
auto Contains(LookupKeyT lookup_key,
KeyContextT key_context = KeyContextT()) const -> bool {
return ViewT(*this).Contains(lookup_key, key_context);
}
// Convenience forwarder to the view type.
template <typename LookupKeyT>
auto Lookup(LookupKeyT lookup_key,
KeyContextT key_context = KeyContextT()) const -> LookupKVResult {
return ViewT(*this).Lookup(lookup_key, key_context);
}
// Convenience forwarder to the view type.
template <typename LookupKeyT>
auto operator[](LookupKeyT lookup_key) const -> ValueT*
requires(std::default_initializable<KeyContextT>)
{
return ViewT(*this)[lookup_key];
}
// Convenience forwarder to the view type.
auto entries() const& -> Range { return ViewT(*this).entries(); }
// Deleted on rvalues: the range refers to storage owned by this table, so a
// range built from a temporary map would dangle. Both qualifiers are needed
// as `&&` alone would leave a const rvalue binding to the `const&` overload.
auto entries() && = delete;
auto entries() const&& = delete;
// Convenience forwarder to the view type.
auto ComputeMetrics(KeyContextT key_context = KeyContextT()) const
-> MetricsT {
return ViewT(*this).ComputeMetrics(key_context);
}
// Insert a key and value into the map. If the key is already present, the new
// value is discarded and the existing value preserved.
template <typename LookupKeyT>
auto Insert(LookupKeyT lookup_key, ValueT new_v,
KeyContextT key_context = KeyContextT()) -> InsertKVResult;
// Insert a key into the map and call the provided callback if necessary to
// produce a new value when no existing value is found.
//
// Example: `m.Insert(key, [] { return default_value; });`
//
// TODO: The `;` formatting below appears to be bugs in clang-format with
// concepts that should be filed upstream.
template <typename LookupKeyT, typename ValueCallbackT>
auto Insert(LookupKeyT lookup_key, ValueCallbackT value_cb,
KeyContextT key_context = KeyContextT()) -> InsertKVResult
requires(
!std::same_as<ValueT, ValueCallbackT> &&
std::convertible_to<decltype(std::declval<ValueCallbackT>()()), ValueT>)
;
// Lookup a key in the map and if missing insert it and call the provided
// callback to in-place construct both the key and value. The lookup key is
// passed through to the callback so it needn't be captured and can be kept in
// a register argument throughout.
//
// Example:
// ```cpp
// m.Insert("widget", [](MyStringViewType lookup_key, void* key_storage,
// void* value_storage) {
// new (key_storage) MyStringType(lookup_key);
// new (value_storage) MyValueType(....);
// });
// ```
template <typename LookupKeyT, typename InsertCallbackT>
auto Insert(LookupKeyT lookup_key, InsertCallbackT insert_cb,
KeyContextT key_context = KeyContextT()) -> InsertKVResult
requires(!std::same_as<ValueT, InsertCallbackT> &&
std::invocable<InsertCallbackT, LookupKeyT, void*, void*>);
// Replace a key's value in a map if already present or insert it if not
// already present. The new value is always used.
template <typename LookupKeyT>
auto Update(LookupKeyT lookup_key, ValueT new_v,
KeyContextT key_context = KeyContextT()) -> InsertKVResult;
// Lookup or insert a key into the map, and set it's value to the result of
// the `value_cb` callback. The callback is always run and its result is
// always used, whether the key was already in the map or not. Any existing
// value is replaced with the result.
//
// Example: `m.Update(key, [] { return new_value; });`
template <typename LookupKeyT, typename ValueCallbackT>
auto Update(LookupKeyT lookup_key, ValueCallbackT value_cb,
KeyContextT key_context = KeyContextT()) -> InsertKVResult
requires(
!std::same_as<ValueT, ValueCallbackT> &&
std::convertible_to<decltype(std::declval<ValueCallbackT>()()), ValueT>)
;
// Lookup or insert a key into the map. If not already present and the key is
// inserted, the `insert_cb` is used to construct the new key and value in
// place. When inserting, the lookup key is passed through to the callback so
// it needn't be captured and can be kept in a register argument throughout.
// If the key was already present, the `update_cb` is called to update the
// existing key and value as desired.
//
// Example of counting occurrences:
// ```cpp
// m.Update(item, /*insert_cb=*/[](MyStringViewType lookup_key,
// void* key_storage, void* value_storage) {
// new (key_storage) MyItem(lookup_key);
// new (value_storage) Count(1);
// },
// /*update_cb=*/[](MyItem& /*key*/, Count& count) {
// ++count;
// });
// ```
template <typename LookupKeyT, typename InsertCallbackT,
typename UpdateCallbackT>
auto Update(LookupKeyT lookup_key, InsertCallbackT insert_cb,
UpdateCallbackT update_cb,
KeyContextT key_context = KeyContextT()) -> InsertKVResult
requires(!std::same_as<ValueT, InsertCallbackT> &&
std::invocable<InsertCallbackT, LookupKeyT, void*, void*> &&
std::invocable<UpdateCallbackT, KeyT&, ValueT&>);
// Grow the map to a specific allocation size.
//
// This will grow the map's hashtable if necessary for it to have an
// allocation size of `target_alloc_size` which must be a power of two. Note
// that this will not allow that many keys to be inserted, but a smaller
// number based on the maximum load factor. If a specific number of insertions
// need to be achieved without triggering growth, use the `GrowForInsertCount`
// method.
auto GrowToAllocSize(ssize_t target_alloc_size,
KeyContextT key_context = KeyContextT()) -> void;
// Grow the map sufficiently to allow inserting the specified number of keys.
auto GrowForInsertCount(ssize_t count,
KeyContextT key_context = KeyContextT()) -> void;
// Erase a key from the map.
template <typename LookupKeyT>
auto Erase(LookupKeyT lookup_key, KeyContextT key_context = KeyContextT())
-> bool;
// Clear all key/value pairs from the map but leave the underlying hashtable
// allocated and in place.
auto Clear() -> void;
protected:
using ImplT::ImplT;
};
// A data structure mapping from key to value.
//
// This map also supports small size optimization (or "SSO"). The provided
// `SmallSize` type parameter indicates the size of an embedded buffer for
// storing maps small enough to fit. The default is zero, which always allocates
// a heap buffer on construction. When non-zero, must be a multiple of the
// `MaxGroupSize` which is currently 16. The library will check that the size is
// valid and provide an error at compile time if not. We don't automatically
// select the next multiple or otherwise fit the size to the constraints to make
// it clear in the code how much memory is used by the SSO buffer.
//
// This data structure optimizes heavily for small key types that are cheap to
// move and even copy. Using types with large keys or expensive to copy keys may
// create surprising performance bottlenecks. A `std::string` key should be fine
// with generally small strings, but if some or many strings are large heap
// allocations the performance of hashtable routines may be unacceptably bad and
// another data structure or key design is likely preferable.
//
// Note that like `MapBase`, `Map` has "shallow" const semantics. Note also that
// this type should typically not appear on API boundaries; either `MapBase` or
// `MapView` should be used instead.
template <typename InputKeyT, typename InputValueT, ssize_t SmallSize = 0,
typename InputKeyContextT = DefaultKeyContext>
class Map : public RawHashtable::TableImpl<
MapBase<InputKeyT, InputValueT, InputKeyContextT>, SmallSize> {
using BaseT = MapBase<InputKeyT, InputValueT, InputKeyContextT>;
using ImplT = RawHashtable::TableImpl<BaseT, SmallSize>;
public:
using KeyT = BaseT::KeyT;
using ValueT = BaseT::ValueT;
Map() = default;
Map(const Map& arg) = default;
Map(Map&& arg) noexcept = default;
auto operator=(const Map& arg) -> Map& = default;
auto operator=(Map&& arg) noexcept -> Map& = default;
// Reset the entire state of the hashtable to as it was when constructed,
// throwing away any intervening allocations.
auto Reset() -> void;
};
template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
template <typename LookupKeyT>
auto MapView<InputKeyT, InputValueT, InputKeyContextT>::Contains(
LookupKeyT lookup_key, KeyContextT key_context) const -> bool {
return this->LookupEntry(lookup_key, key_context) != nullptr;
}
template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
template <typename LookupKeyT>
auto MapView<InputKeyT, InputValueT, InputKeyContextT>::Lookup(
LookupKeyT lookup_key, KeyContextT key_context) const -> LookupKVResult {
return LookupKVResult(this->LookupEntry(lookup_key, key_context));
}
template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
template <typename LookupKeyT>
auto MapView<InputKeyT, InputValueT, InputKeyContextT>::operator[](
LookupKeyT lookup_key) const -> ValueT*
requires(std::default_initializable<KeyContextT>)
{
auto result = Lookup(lookup_key, KeyContextT());
return result ? &result.value() : nullptr;
}
template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
auto MapView<InputKeyT, InputValueT, InputKeyContextT>::entries() const
-> Range {
return this->ImplT::EntriesImpl();
}
template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
template <typename LookupKeyT>
[[clang::always_inline]] auto
MapBase<InputKeyT, InputValueT, InputKeyContextT>::Insert(
LookupKeyT lookup_key, ValueT new_v, KeyContextT key_context)
-> InsertKVResult {
return Insert(
lookup_key,
[&new_v](LookupKeyT lookup_key, void* key_storage, void* value_storage) {
new (key_storage) KeyT(lookup_key);
new (value_storage) ValueT(std::move(new_v));
},
key_context);
}
template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
template <typename LookupKeyT, typename ValueCallbackT>
[[clang::always_inline]] auto
MapBase<InputKeyT, InputValueT, InputKeyContextT>::Insert(
LookupKeyT lookup_key, ValueCallbackT value_cb, KeyContextT key_context)
-> InsertKVResult
requires(
!std::same_as<ValueT, ValueCallbackT> &&
std::convertible_to<decltype(std::declval<ValueCallbackT>()()), ValueT>)
{
return Insert(
lookup_key,
[&value_cb](LookupKeyT lookup_key, void* key_storage,
void* value_storage) {
new (key_storage) KeyT(lookup_key);
new (value_storage) ValueT(value_cb());
},
key_context);
}
template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
template <typename LookupKeyT, typename InsertCallbackT>
[[clang::always_inline]] auto
MapBase<InputKeyT, InputValueT, InputKeyContextT>::Insert(
LookupKeyT lookup_key, InsertCallbackT insert_cb, KeyContextT key_context)
-> InsertKVResult
requires(!std::same_as<ValueT, InsertCallbackT> &&
std::invocable<InsertCallbackT, LookupKeyT, void*, void*>)
{
auto [entry, inserted] = this->InsertImpl(lookup_key, key_context);
CARBON_DCHECK(entry, "Should always result in a valid index.");
if (LLVM_LIKELY(!inserted)) {
return InsertKVResult(false, *entry);
}
insert_cb(lookup_key, static_cast<void*>(&entry->key_storage),
static_cast<void*>(&entry->value_storage));
return InsertKVResult(true, *entry);
}
template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
template <typename LookupKeyT>
[[clang::always_inline]] auto
MapBase<InputKeyT, InputValueT, InputKeyContextT>::Update(
LookupKeyT lookup_key, ValueT new_v, KeyContextT key_context)
-> InsertKVResult {
return Update(
lookup_key,
[&new_v](LookupKeyT lookup_key, void* key_storage, void* value_storage) {
new (key_storage) KeyT(lookup_key);
new (value_storage) ValueT(std::move(new_v));
},
[&new_v](KeyT& /*key*/, ValueT& value) {
value.~ValueT();
new (&value) ValueT(std::move(new_v));
},
key_context);
}
template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
template <typename LookupKeyT, typename ValueCallbackT>
[[clang::always_inline]] auto
MapBase<InputKeyT, InputValueT, InputKeyContextT>::Update(
LookupKeyT lookup_key, ValueCallbackT value_cb, KeyContextT key_context)
-> InsertKVResult
requires(
!std::same_as<ValueT, ValueCallbackT> &&
std::convertible_to<decltype(std::declval<ValueCallbackT>()()), ValueT>)
{
return Update(
lookup_key,
[&value_cb](LookupKeyT lookup_key, void* key_storage,
void* value_storage) {
new (key_storage) KeyT(lookup_key);
new (value_storage) ValueT(value_cb());
},
[&value_cb](KeyT& /*key*/, ValueT& value) {
value.~ValueT();
new (&value) ValueT(value_cb());
},
key_context);
}
template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
template <typename LookupKeyT, typename InsertCallbackT,
typename UpdateCallbackT>
[[clang::always_inline]] auto
MapBase<InputKeyT, InputValueT, InputKeyContextT>::Update(
LookupKeyT lookup_key, InsertCallbackT insert_cb, UpdateCallbackT update_cb,
KeyContextT key_context) -> InsertKVResult
requires(!std::same_as<ValueT, InsertCallbackT> &&
std::invocable<InsertCallbackT, LookupKeyT, void*, void*> &&
std::invocable<UpdateCallbackT, KeyT&, ValueT&>)
{
auto [entry, inserted] = this->InsertImpl(lookup_key, key_context);
CARBON_DCHECK(entry, "Should always result in a valid index.");
if (LLVM_LIKELY(!inserted)) {
update_cb(entry->key(), entry->value());
return InsertKVResult(false, *entry);
}
insert_cb(lookup_key, static_cast<void*>(&entry->key_storage),
static_cast<void*>(&entry->value_storage));
return InsertKVResult(true, *entry);
}
template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
auto MapBase<InputKeyT, InputValueT, InputKeyContextT>::GrowToAllocSize(
ssize_t target_alloc_size, KeyContextT key_context) -> void {
this->GrowToAllocSizeImpl(target_alloc_size, key_context);
}
template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
auto MapBase<InputKeyT, InputValueT, InputKeyContextT>::GrowForInsertCount(
ssize_t count, KeyContextT key_context) -> void {
this->GrowForInsertCountImpl(count, key_context);
}
template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
template <typename LookupKeyT>
auto MapBase<InputKeyT, InputValueT, InputKeyContextT>::Erase(
LookupKeyT lookup_key, KeyContextT key_context) -> bool {
return this->EraseImpl(lookup_key, key_context);
}
template <typename InputKeyT, typename InputValueT, typename InputKeyContextT>
auto MapBase<InputKeyT, InputValueT, InputKeyContextT>::Clear() -> void {
this->ClearImpl();
}
template <typename InputKeyT, typename InputValueT, ssize_t SmallSize,
typename InputKeyContextT>
auto Map<InputKeyT, InputValueT, SmallSize, InputKeyContextT>::Reset() -> void {
this->ResetImpl();
}
} // namespace Carbon
#endif // CARBON_COMMON_MAP_H_