v8
V8 is Google’s open source high-performance JavaScript and WebAssembly engine, written in C++.
Loading...
Searching...
No Matches
cached-unordered-map.h
Go to the documentation of this file.
1// Copyright 2024 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef V8_HEAP_BASE_CACHED_UNORDERED_MAP_H_
6#define V8_HEAP_BASE_CACHED_UNORDERED_MAP_H_
7
8#include <unordered_map>
9
10#include "absl/container/flat_hash_map.h"
11#include "src/base/hashing.h"
12
13namespace heap::base {
14
15// A cached map that speeds up `operator[]` if used in LRU fashion.
16template <typename _Key, typename _Value, typename _Hash = v8::base::hash<_Key>>
17class CachedUnorderedMap final {
18 using MapT = absl::flat_hash_map<_Key, _Value, _Hash>;
19
20 public:
21 using Key = typename MapT::key_type;
22 using Mapped = typename MapT::mapped_type;
23
25 // nullptr value is used to indicate absence of a last key.
27
28 if (key == last_key_) {
29 return *last_mapped_;
30 }
31
32 auto it = map_.find(key);
33 if (it == map_.end()) {
34 auto result = map_.emplace(key, Mapped());
35 DCHECK(result.second);
36 it = result.first;
37 }
38
39 last_key_ = key;
40 last_mapped_ = &it->second;
41
42 return it->second;
43 }
44
45 typename MapT::size_type erase(const Key& key) {
46 if (key == last_key_) {
47 last_key_ = nullptr;
48 last_mapped_ = nullptr;
49 }
50 return map_.erase(key);
51 }
52
53 // No iterator is cached in this class so an actual find() has to be executed
54 // everytime.
55 typename MapT::iterator find(const Key& key) { return map_.find(key); }
56
57 typename MapT::iterator begin() { return map_.begin(); }
58 typename MapT::iterator end() { return map_.end(); }
59 typename MapT::const_iterator begin() const { return map_.begin(); }
60 typename MapT::const_iterator end() const { return map_.begin(); }
61
62 bool contains(const Key& key) const { return map_.contains(key); }
63
64 void clear() {
65 last_key_ = nullptr;
66 last_mapped_ = nullptr;
67 map_.clear();
68 }
69
70 bool empty() const { return map_.empty(); }
71
73 last_key_ = nullptr;
74 last_mapped_ = nullptr;
75
76 MapT tmp(std::move(map_));
77 map_.clear();
78 return tmp;
79 }
80
81 private:
82 Key last_key_ = nullptr;
83 Mapped* last_mapped_ = nullptr;
85};
86
87} // namespace heap::base
88
89#endif // V8_HEAP_BASE_CACHED_UNORDERED_MAP_H_
MapT::const_iterator end() const
Mapped & operator[](const Key &key)
MapT::const_iterator begin() const
bool contains(const Key &key) const
MapT::iterator find(const Key &key)
typename MapT::mapped_type Mapped
absl::flat_hash_map< _Key, _Value, _Hash > MapT
MapT::size_type erase(const Key &key)
ZoneVector< RpoNumber > & result
Register tmp
#define DCHECK_NOT_NULL(val)
Definition logging.h:492
#define DCHECK(condition)
Definition logging.h:482
std::unique_ptr< ValueMirror > key