Repository navigation
Expand file tree
/
Copy pathindex.h
More file actions
360 lines (312 loc) · 13.3 KB
/
Copy pathindex.h
File metadata and controls
360 lines (312 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
// Copyright 2010-2025 Google LLC
// 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
//
// http://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 ORTOOLS_GRAPH_INDEX_H_
#define ORTOOLS_GRAPH_INDEX_H_
#include <concepts>
#include <cstddef>
#include <cstring>
#include <functional>
#include <initializer_list>
#include <memory>
#include <optional>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#include "absl/base/attributes.h"
#include "absl/log/check.h"
#include "absl/strings/has_absl_stringify.h"
#include "absl/strings/has_ostream_operator.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/types/span.h"
#include "ortools/graph/hash_or_tree_container.h"
namespace util {
namespace graph {
// Stores a set of unique objects in a vector and provides O(1) lookup by value,
// if T is hashable (else O(log n)).
// In other words, this maps arbitrary objects to dense integers, fast.
template <typename T, typename CompareOrHashT = PreferHashOrCompare<T>,
typename Eq = std::equal_to<>>
class Index {
public:
typedef T value_type;
explicit Index(int reserve_num_objects = 0,
CompareOrHashT compare_or_hash = CompareOrHashT(),
Eq eq = Eq());
// Initializer list constructor and implicit conversion, e.g.,
// Index<std::string> idx{"a", "b", "c"}.
// ... and/or later: idx = {"foo", "bar"}.
Index(std::initializer_list<T> init,
CompareOrHashT compare_or_hash = CompareOrHashT(), Eq eq = Eq());
int LookupOrAdd(T object) { return TryEmplace(std::move(object)).first; }
std::optional<int> Lookup(const T& object) const {
return impl_->Lookup(object);
}
int LookupOrDie(const T& object) const;
// DCHECKs that the index is valid.
const T& operator[](int index) const { return impl_->operator[](index); }
absl::Span<const T> span() const { return impl_->objects_; }
int size() const { return span().size(); }
// Like LookupOrAdd(), but also returns whether the object was newly inserted.
template <typename U>
std::pair<int, bool> TryEmplace(U&& object) {
return impl_->TryEmplace(std::forward<U>(object));
}
template <typename U>
int AddOrDie(U&& object);
// For direct range iteration.
absl::Span<const T>::iterator begin() const { return span().begin(); }
absl::Span<const T>::iterator end() const { return span().end(); }
void clear() { impl_->clear(); }
// Move out the underlying vector<T>. *this must be being moved.
// EXAMPLE: std::vector<T> v = std::move(index).Extract();
std::vector<T> Extract() && { return std::move(impl_->objects_); }
private:
// We use an indirection via unique_ptr<Impl> to make *this movable, because
// Impl requires pointer stability of `this` across moves.
class Impl;
std::unique_ptr<Impl> impl_;
};
// =============================================================================
// IMPLEMENTATION DETAILS BELOW THIS LINE
// =============================================================================
// Internal helpers.
namespace internal {
template <typename H, typename ValueT>
concept LooksLikeHasher = requires(const H& h, const ValueT& v) {
{ h(v) } -> std::integral;
};
// To print a T object in the OrDie() variants's CHECK message, we try to use
// AbslStringify(), else <<, else we just print the pointer.
template <typename T>
std::string PrintForCheck(T&& value) {
using BaseT = std::remove_cvref_t<T>;
if constexpr (absl::HasAbslStringify<BaseT>::value) {
return absl::StrCat(value);
} else if constexpr (absl::HasOstreamOperator<BaseT>::value) {
std::ostringstream oss;
oss << value;
return oss.str();
} else {
return absl::StrFormat("<%d bytes object at %p>", sizeof(BaseT),
std::addressof(value));
}
}
} // namespace internal
template <typename T, typename CompareOrHashT, typename Eq>
int Index<T, CompareOrHashT, Eq>::LookupOrDie(const T& object) const {
const std::optional<int> index = impl_->Lookup(object);
CHECK(index.has_value()) << "Not found: " << internal::PrintForCheck(object);
return *index;
}
template <typename T, typename CompareOrHashT, typename Eq>
template <typename U>
int Index<T, CompareOrHashT, Eq>::AddOrDie(U&& object) {
const auto [index, inserted] = impl_->TryEmplace(std::forward<U>(object));
// NOTE(user): TryEmplace() may move `object`, but only if it is inserted.
// So we can safely refer to it again in the CHECK message.
CHECK(inserted) << "Already exists: "
<< internal::PrintForCheck(std::forward<U>(object));
return index;
}
// Implementation of `Index`. Conceptually this is a `vector<T>` of objects, and
// a set of `T*` (represented has a hash set or ordered set depending on
// `CompareOrHashT`). A subtlety is that instead of storing pointers as `T*`, we
// store indices into the vector of objects, from which we can retrieve the
// actual object pointers. Adding a new object to the vector invalidates
// pointers, but not indices. Storing indices therefore allows adding new
// objects to the vector without having to touch other entries in the set.
//
// The indices are represented in a type-safe way as `ObjectIndex`.
// We rely on heterogeneous lookup (https://abseil.io/tips/144) to allow lookups
// into the set by `const T& t`, while the actual set keys are `ObjectIndex`:
// we simply need to compare the object `t` with the object at corresponding
// index in the vector.
// More generally, when the functors `CompareOrHashT` and `Eq` are transparent,
// lookups are allowed using any key type `U&&` that can be transparently
// compared with `T`.
//
// For insertions (see `TryEmplace`), the situation is a a bit more complex.
// We want to be able to do the lookup and insertion in one step using
// `try_emplace`, without constructing unnecessary temporaries. So we need both
// an index (in case the object is not present and needs to be inserted) and a
// `U&&` lookup key. This is represented by `EmplaceableObject`, whis is a
// temporary value-typed object that acts as a lookup key but converts to an
// `ObjectIndex`, inserting a new `T` in the vector when the set decides that it
// needs to be inserted.
template <typename T, typename CompareOrHashT, typename Eq>
class Index<T, CompareOrHashT, Eq>::Impl {
public:
// A temporary object to represent a potential new object in the index.
template <typename U>
struct EmplaceableObject {
static constexpr bool kIsEmplaceableObject = true;
const U& key_ref() const { return key; }
U&& key; // The lookup key (might be different from T if transparent).
int index_if_inserted; // The index to give the newly emplaced object.
Impl* const impl;
};
class ObjectIndex {
public:
using ValueType = int;
template <typename U>
explicit ObjectIndex(EmplaceableObject<U> emplaceable)
: ObjectIndex(emplaceable.index_if_inserted) {
// We need to emplace the object here instead of in `TryInsert`, because
// in debug mode absl containers immediately rehash/compare the keys to
// check invariants, and looking up by `ObjectIndex` will try to look up
// by index, so the object needs to already be inserted.
emplaceable.impl->objects_.emplace_back(std::forward<U>(emplaceable.key));
}
explicit ObjectIndex(ValueType index) {
memcpy(index_, &index, sizeof(ValueType));
}
ValueType index() const {
ValueType index;
memcpy(&index, index_, sizeof(ValueType));
return index;
}
private:
// This is really an int. Why encode it as a char[]? Because the ObjectIndex
// keys are stored as std::pair<ObjectIndex, Empty> in a map (TODO below).
// This trick reduces the byte overhead of `Empty` to just 1 byte, instead
// of 4 bytes (due to padding) if we were using `int` directly.
char index_[sizeof(ValueType)];
};
// To support heterogeneous lookup, we need to wrap the functors. See usage.
struct FunctorWrapper;
struct CompareOrHashTWrapper;
struct EqWrapper;
struct Empty {};
// TODO(user): Ideally this would be a `Set`, but
// guaranteed-not-to-construct emplace is only supported for maps through
// `try_emplace`.
using Container =
typename HashOrTreeContainer<ObjectIndex, CompareOrHashTWrapper,
EqWrapper>::template Map<Empty>;
static_assert(sizeof(typename Container::value_type) ==
sizeof(typename ObjectIndex::ValueType) + 1);
static_assert(alignof(typename Container::value_type) == 1);
static Container MakeContainer(Impl* impl, int reserve_num_objects,
CompareOrHashT compare_or_hash, Eq eq) {
if constexpr (internal::LooksLikeHasher<CompareOrHashT, T>) {
return Container(
reserve_num_objects,
CompareOrHashTWrapper{{impl}, std::move(compare_or_hash)},
EqWrapper{{impl}, std::move(eq)});
} else {
return Container(
CompareOrHashTWrapper{{impl}, std::move(compare_or_hash)});
}
}
explicit Impl(int reserve_num_objects, CompareOrHashT compare_or_hash, Eq eq)
: index_(MakeContainer(this, reserve_num_objects,
std::move(compare_or_hash), std::move(eq))) {
objects_.reserve(reserve_num_objects);
}
// Replication of the public API.
template <typename U>
std::pair<int, bool> TryEmplace(U&& u) {
const auto [it, inserted] = index_.try_emplace(EmplaceableObject<U>{
.key = std::forward<U>(u),
.index_if_inserted = static_cast<int>(objects_.size()),
.impl = this});
return std::make_pair(it->first.index(), inserted);
}
std::optional<int> Lookup(const T& object) const {
auto it = index_.find(object);
if (it == index_.end()) return std::nullopt;
return it->first.index();
}
const T& operator[](int index) const {
DCHECK_GE(index, 0);
DCHECK_LT(index, objects_.size());
return objects_[index];
}
void clear() {
index_.clear();
objects_.clear();
}
// Contains all inserted objects. Natural map from dense int to object.
std::vector<T> objects_;
// Behaves like a map<T, int>, but without storing the object T again, which
// are already stored in 'objects_'. Instead, we store the dense index of
// each object, and use custom hash/comparison/eq functors that uses
// objects_[i] to convert int i before hashing/comparing it.
Container index_;
};
template <typename T, typename CompareOrHashT, typename Eq>
Index<T, CompareOrHashT, Eq>::Index(int reserve_num_objects,
CompareOrHashT compare_or_hash, Eq eq)
: impl_(std::make_unique<Impl>(
reserve_num_objects, std::move(compare_or_hash), std::move(eq))) {}
template <typename T, typename CompareOrHashT, typename Eq>
Index<T, CompareOrHashT, Eq>::Index(std::initializer_list<T> init,
CompareOrHashT compare_or_hash, Eq eq)
: impl_(std::make_unique<Impl>(init.size(), std::move(compare_or_hash),
std::move(eq))) {
for (const auto& object : init) {
LookupOrAdd(object);
}
}
template <typename T, typename CompareOrHashT, typename Eq>
struct Index<T, CompareOrHashT, Eq>::Impl::FunctorWrapper {
using is_transparent = void;
template <typename KeyT>
decltype(auto) GetKey(const KeyT& k) const {
if constexpr (std::is_same_v<KeyT, ObjectIndex>) {
// This is the index of an object in our vector of objects.
return impl->objects_[k.index()];
} else if constexpr (requires { k.kIsEmplaceableObject; }) {
// This is an EmplaceableObject, use the transparent lookup key.
return k.key_ref();
} else {
// This is a transparent lookup key.
return k;
}
}
const Index::Impl* impl = nullptr;
};
template <typename T, typename CompareOrHashT, typename Eq>
struct Index<T, CompareOrHashT, Eq>::Impl::CompareOrHashTWrapper
: public FunctorWrapper {
// If CompareOrHashT is a hasher, here's its heterogeneous lookup API.
template <typename KeyT>
size_t operator()(const KeyT& k) const
requires internal::LooksLikeHasher<CompareOrHashT, T>
{
return compare_or_hash(FunctorWrapper::GetKey(k));
}
// If CompareOrHashT is a comparator, here's its heterogeneous lookup API.
template <typename KeyT1, typename KeyT2>
bool operator()(const KeyT1& a, const KeyT2& b) const
requires(!internal::LooksLikeHasher<CompareOrHashT, T>)
{
return compare_or_hash(FunctorWrapper::GetKey(a),
FunctorWrapper::GetKey(b));
}
ABSL_ATTRIBUTE_NO_UNIQUE_ADDRESS CompareOrHashT compare_or_hash;
};
template <typename T, typename CompareOrHashT, typename Eq>
struct Index<T, CompareOrHashT, Eq>::Impl::EqWrapper : public FunctorWrapper {
template <typename KeyT1, typename KeyT2>
bool operator()(const KeyT1& a, const KeyT2& b) const {
return eq(FunctorWrapper::GetKey(a), FunctorWrapper::GetKey(b));
}
ABSL_ATTRIBUTE_NO_UNIQUE_ADDRESS Eq eq;
};
} // namespace graph
} // namespace util
#endif // ORTOOLS_GRAPH_INDEX_H_