set.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #ifndef CARBON_COMMON_SET_H_
  5. #define CARBON_COMMON_SET_H_
  6. #include <concepts>
  7. #include "common/check.h"
  8. #include "common/hashtable_key_context.h"
  9. #include "common/raw_hashtable.h"
  10. #include "llvm/Support/Compiler.h"
  11. namespace Carbon {
  12. // Forward declarations to resolve cyclic references.
  13. template <typename KeyT, typename KeyContextT>
  14. class SetView;
  15. template <typename KeyT, typename KeyContextT>
  16. class SetBase;
  17. template <typename KeyT, ssize_t SmallSize, typename KeyContextT>
  18. class Set;
  19. // A read-only view type for a set of keys.
  20. //
  21. // This view is a cheap-to-copy type that should be passed by value, but
  22. // provides view or read-only reference semantics to the underlying set data
  23. // structure.
  24. //
  25. // This should always be preferred to a `const`-ref parameter for the `SetBase`
  26. // or `Set` type as it provides more flexibility and a cleaner API.
  27. //
  28. // Note that while this type is a read-only view, that applies to the underlying
  29. // *set* data structure, not the individual entries stored within it. Those can
  30. // be mutated freely as long as both the hashes and equality of the keys are
  31. // preserved. If we applied a deep-`const` design here, it would prevent using
  32. // this type in situations where the keys carry state (unhashed and not part of
  33. // equality) that is mutated while the associative container is not. A view of
  34. // immutable data can always be obtained by using `SetView<const T>`, and we
  35. // enable conversions to more-const views. This mirrors the semantics of views
  36. // like `std::span`.
  37. //
  38. // A specific `KeyContextT` type can optionally be provided to configure how
  39. // keys will be hashed and compared. The default is `DefaultKeyContext` which is
  40. // stateless and will hash using `Carbon::HashValue` and compare using
  41. // `operator==`. Every method accepting a lookup key or operating on the keys in
  42. // the table will also accept an instance of this type. For stateless context
  43. // types, including the default, an instance will be default constructed if not
  44. // provided to these methods. However, stateful contexts should be constructed
  45. // and passed in explicitly. The context type should be small and reasonable to
  46. // pass by value, often a wrapper or pointer to the relevant context needed for
  47. // hashing and comparing keys. For more details about the key context, see
  48. // `hashtable_key_context.h`.
  49. template <typename InputKeyT, typename InputKeyContextT = DefaultKeyContext>
  50. class SetView : RawHashtable::ViewImpl<InputKeyT, void, InputKeyContextT> {
  51. using ImplT = RawHashtable::ViewImpl<InputKeyT, void, InputKeyContextT>;
  52. public:
  53. using KeyT = typename ImplT::KeyT;
  54. using KeyContextT = typename ImplT::KeyContextT;
  55. using MetricsT = typename ImplT::MetricsT;
  56. // This type represents the result of lookup operations. It encodes whether
  57. // the lookup was a success as well as accessors for the key.
  58. class LookupResult {
  59. public:
  60. LookupResult() = default;
  61. explicit LookupResult(KeyT& key) : key_(&key) {}
  62. explicit operator bool() const { return key_ != nullptr; }
  63. auto key() const -> KeyT& { return *key_; }
  64. private:
  65. KeyT* key_ = nullptr;
  66. };
  67. // Enable implicit conversions that add `const`-ness to the key type.
  68. // NOLINTNEXTLINE(google-explicit-constructor)
  69. SetView(SetView<std::remove_const_t<KeyT>, KeyContextT> other_view)
  70. requires(!std::same_as<KeyT, std::remove_const_t<KeyT>>)
  71. : ImplT(other_view) {}
  72. // Tests whether a key is present in the set.
  73. template <typename LookupKeyT>
  74. auto Contains(LookupKeyT lookup_key,
  75. KeyContextT key_context = KeyContextT()) const -> bool;
  76. // Lookup a key in the set.
  77. template <typename LookupKeyT>
  78. auto Lookup(LookupKeyT lookup_key,
  79. KeyContextT key_context = KeyContextT()) const -> LookupResult;
  80. // Run the provided callback for every key in the set.
  81. template <typename CallbackT>
  82. void ForEach(CallbackT callback)
  83. requires(std::invocable<CallbackT, KeyT&>);
  84. // This routine is relatively inefficient and only intended for use in
  85. // benchmarking or logging of performance anomalies. The specific metrics
  86. // returned have no specific guarantees beyond being informative in
  87. // benchmarks.
  88. auto ComputeMetrics(KeyContextT key_context = KeyContextT()) -> MetricsT {
  89. return ImplT::ComputeMetricsImpl(key_context);
  90. }
  91. private:
  92. template <typename SetKeyT, ssize_t SmallSize, typename KeyContextT>
  93. friend class Set;
  94. friend class SetBase<KeyT, KeyContextT>;
  95. friend class SetView<const KeyT, KeyContextT>;
  96. using EntryT = typename ImplT::EntryT;
  97. SetView() = default;
  98. // NOLINTNEXTLINE(google-explicit-constructor): Implicit by design.
  99. SetView(ImplT base) : ImplT(base) {}
  100. SetView(ssize_t size, RawHashtable::Storage* storage)
  101. : ImplT(size, storage) {}
  102. };
  103. // A base class for a `Set` type that remains mutable while type-erasing the
  104. // `SmallSize` (SSO) template parameter.
  105. //
  106. // A pointer or reference to this type is the preferred way to pass a mutable
  107. // handle to a `Set` type across API boundaries as it avoids encoding specific
  108. // SSO sizing information while providing a near-complete mutable API.
  109. template <typename InputKeyT, typename InputKeyContextT>
  110. class SetBase
  111. : protected RawHashtable::BaseImpl<InputKeyT, void, InputKeyContextT> {
  112. protected:
  113. using ImplT = RawHashtable::BaseImpl<InputKeyT, void, InputKeyContextT>;
  114. public:
  115. using KeyT = typename ImplT::KeyT;
  116. using KeyContextT = typename ImplT::KeyContextT;
  117. using ViewT = SetView<KeyT, KeyContextT>;
  118. using LookupResult = typename ViewT::LookupResult;
  119. using MetricsT = typename ImplT::MetricsT;
  120. // The result type for insertion operations both indicates whether an insert
  121. // was needed (as opposed to the key already being in the set), and provides
  122. // access to the key.
  123. class InsertResult {
  124. public:
  125. InsertResult() = default;
  126. explicit InsertResult(bool inserted, KeyT& key)
  127. : key_(&key), inserted_(inserted) {}
  128. auto is_inserted() const -> bool { return inserted_; }
  129. auto key() const -> KeyT& { return *key_; }
  130. private:
  131. KeyT* key_;
  132. bool inserted_;
  133. };
  134. // Implicitly convertible to the relevant view type.
  135. //
  136. // NOLINTNEXTLINE(google-explicit-constructor): Designed to implicitly decay.
  137. operator ViewT() const { return this->view_impl(); }
  138. // We can't chain the above conversion with the conversions on `ViewT` to add
  139. // const, so explicitly support adding const to produce a view here.
  140. //
  141. // NOLINTNEXTLINE(google-explicit-constructor): Designed to implicitly decay.
  142. operator SetView<const KeyT, KeyContextT>() const { return ViewT(*this); }
  143. // Convenience forwarder to the view type.
  144. template <typename LookupKeyT>
  145. auto Contains(LookupKeyT lookup_key,
  146. KeyContextT key_context = KeyContextT()) const -> bool {
  147. return ViewT(*this).Contains(lookup_key, key_context);
  148. }
  149. // Convenience forwarder to the view type.
  150. template <typename LookupKeyT>
  151. auto Lookup(LookupKeyT lookup_key,
  152. KeyContextT key_context = KeyContextT()) const -> LookupResult {
  153. return ViewT(*this).Lookup(lookup_key, key_context);
  154. }
  155. // Convenience forwarder to the view type.
  156. template <typename CallbackT>
  157. void ForEach(CallbackT callback)
  158. requires(std::invocable<CallbackT, KeyT&>)
  159. {
  160. return ViewT(*this).ForEach(callback);
  161. }
  162. // Convenience forwarder to the view type.
  163. auto ComputeMetrics(KeyContextT key_context = KeyContextT()) const
  164. -> MetricsT {
  165. return ViewT(*this).ComputeMetrics(key_context);
  166. }
  167. // Insert a key into the set. If the key is already present, no insertion is
  168. // performed and that present key is available in the result. Otherwise a new
  169. // key is inserted and constructed from the argument and available in the
  170. // result.
  171. template <typename LookupKeyT>
  172. auto Insert(LookupKeyT lookup_key, KeyContextT key_context = KeyContextT())
  173. -> InsertResult;
  174. // Insert a key into the map and call the provided callback if necessary to
  175. // produce a new key when no existing value is found.
  176. //
  177. // Example: `m.Insert(key_equivalent, [] { return real_key; });`
  178. //
  179. // The point of this function is when the lookup key is _different_from the
  180. // stored key. However, we don't restrict it in case that blocks generic
  181. // usage.
  182. template <typename LookupKeyT, typename KeyCallbackT>
  183. auto Insert(LookupKeyT lookup_key, KeyCallbackT key_cb,
  184. KeyContextT key_context = KeyContextT()) -> InsertResult
  185. requires(
  186. !std::same_as<KeyT, KeyCallbackT> &&
  187. std::convertible_to<decltype(std::declval<KeyCallbackT>()()), KeyT>);
  188. // Insert a key into the set and call the provided callback to allow in-place
  189. // construction of the key if not already present. The lookup key is passed
  190. // through to the callback so it needn't be captured and can be kept in a
  191. // register argument throughout.
  192. //
  193. // Example:
  194. // ```cpp
  195. // m.Insert("widget", [](MyStringViewType lookup_key, void* key_storage) {
  196. // new (key_storage) MyStringType(lookup_key);
  197. // });
  198. // ```
  199. template <typename LookupKeyT, typename InsertCallbackT>
  200. auto Insert(LookupKeyT lookup_key, InsertCallbackT insert_cb,
  201. KeyContextT key_context = KeyContextT()) -> InsertResult
  202. requires std::invocable<InsertCallbackT, LookupKeyT, void*>;
  203. // Grow the set to a specific allocation size.
  204. //
  205. // This will grow the set's hashtable if necessary for it to have an
  206. // allocation size of `target_alloc_size` which must be a power of two. Note
  207. // that this will not allow that many keys to be inserted, but a smaller
  208. // number based on the maximum load factor. If a specific number of insertions
  209. // need to be achieved without triggering growth, use the `GrowForInsertCount`
  210. // method.
  211. auto GrowToAllocSize(ssize_t target_alloc_size,
  212. KeyContextT key_context = KeyContextT()) -> void;
  213. // Grow the set sufficiently to allow inserting the specified number of keys.
  214. auto GrowForInsertCount(ssize_t count,
  215. KeyContextT key_context = KeyContextT()) -> void;
  216. // Erase a key from the set.
  217. template <typename LookupKeyT>
  218. auto Erase(LookupKeyT lookup_key, KeyContextT key_context = KeyContextT())
  219. -> bool;
  220. // Clear all key/value pairs from the set but leave the underlying hashtable
  221. // allocated and in place.
  222. void Clear();
  223. protected:
  224. using ImplT::ImplT;
  225. };
  226. // A data structure for a set of keys.
  227. //
  228. // This set supports small size optimization (or "SSO"). The provided
  229. // `SmallSize` type parameter indicates the size of an embedded buffer for
  230. // storing sets small enough to fit. The default is zero, which always allocates
  231. // a heap buffer on construction. When non-zero, must be a multiple of the
  232. // `MaxGroupSize` which is currently 16. The library will check that the size is
  233. // valid and provide an error at compile time if not. We don't automatically
  234. // select the next multiple or otherwise fit the size to the constraints to make
  235. // it clear in the code how much memory is used by the SSO buffer.
  236. //
  237. // This data structure optimizes heavily for small key types that are cheap to
  238. // move and even copy. Using types with large keys or expensive to copy keys may
  239. // create surprising performance bottlenecks. A `std::string` key should be fine
  240. // with generally small strings, but if some or many strings are large heap
  241. // allocations the performance of hashtable routines may be unacceptably bad and
  242. // another data structure or key design is likely preferable.
  243. //
  244. // Note that this type should typically not appear on API boundaries; either
  245. // `SetBase` or `SetView` should be used instead.
  246. template <typename InputKeyT, ssize_t SmallSize = 0,
  247. typename InputKeyContextT = DefaultKeyContext>
  248. class Set : public RawHashtable::TableImpl<SetBase<InputKeyT, InputKeyContextT>,
  249. SmallSize> {
  250. using BaseT = SetBase<InputKeyT, InputKeyContextT>;
  251. using ImplT = RawHashtable::TableImpl<BaseT, SmallSize>;
  252. public:
  253. using KeyT = typename BaseT::KeyT;
  254. Set() = default;
  255. Set(const Set& arg) = default;
  256. Set(Set&& arg) noexcept = default;
  257. auto operator=(const Set& arg) -> Set& = default;
  258. auto operator=(Set&& arg) noexcept -> Set& = default;
  259. // Reset the entire state of the hashtable to as it was when constructed,
  260. // throwing away any intervening allocations.
  261. void Reset();
  262. };
  263. template <typename InputKeyT, typename InputKeyContextT>
  264. template <typename LookupKeyT>
  265. auto SetView<InputKeyT, InputKeyContextT>::Contains(
  266. LookupKeyT lookup_key, KeyContextT key_context) const -> bool {
  267. return this->LookupEntry(lookup_key, key_context) != nullptr;
  268. }
  269. template <typename InputKeyT, typename InputKeyContextT>
  270. template <typename LookupKeyT>
  271. auto SetView<InputKeyT, InputKeyContextT>::Lookup(LookupKeyT lookup_key,
  272. KeyContextT key_context) const
  273. -> LookupResult {
  274. EntryT* entry = this->LookupEntry(lookup_key, key_context);
  275. if (!entry) {
  276. return LookupResult();
  277. }
  278. return LookupResult(entry->key());
  279. }
  280. template <typename InputKeyT, typename InputKeyContextT>
  281. template <typename CallbackT>
  282. void SetView<InputKeyT, InputKeyContextT>::ForEach(CallbackT callback)
  283. requires(std::invocable<CallbackT, KeyT&>)
  284. {
  285. this->ForEachEntry([callback](EntryT& entry) { callback(entry.key()); },
  286. [](auto...) {});
  287. }
  288. template <typename InputKeyT, typename InputKeyContextT>
  289. template <typename LookupKeyT>
  290. auto SetBase<InputKeyT, InputKeyContextT>::Insert(LookupKeyT lookup_key,
  291. KeyContextT key_context)
  292. -> InsertResult {
  293. return Insert(
  294. lookup_key,
  295. [](LookupKeyT lookup_key, void* key_storage) {
  296. new (key_storage) KeyT(std::move(lookup_key));
  297. },
  298. key_context);
  299. }
  300. template <typename InputKeyT, typename InputKeyContextT>
  301. template <typename LookupKeyT, typename KeyCallbackT>
  302. auto SetBase<InputKeyT, InputKeyContextT>::Insert(LookupKeyT lookup_key,
  303. KeyCallbackT key_cb,
  304. KeyContextT key_context)
  305. -> InsertResult
  306. requires(!std::same_as<KeyT, KeyCallbackT> &&
  307. std::convertible_to<decltype(std::declval<KeyCallbackT>()()), KeyT>)
  308. {
  309. return Insert(
  310. lookup_key,
  311. [&key_cb](LookupKeyT /*lookup_key*/, void* key_storage) {
  312. new (key_storage) KeyT(key_cb());
  313. },
  314. key_context);
  315. }
  316. template <typename InputKeyT, typename InputKeyContextT>
  317. template <typename LookupKeyT, typename InsertCallbackT>
  318. auto SetBase<InputKeyT, InputKeyContextT>::Insert(LookupKeyT lookup_key,
  319. InsertCallbackT insert_cb,
  320. KeyContextT key_context)
  321. -> InsertResult
  322. requires std::invocable<InsertCallbackT, LookupKeyT, void*>
  323. {
  324. auto [entry, inserted] = this->InsertImpl(lookup_key, key_context);
  325. CARBON_DCHECK(entry, "Should always result in a valid index.");
  326. if (LLVM_LIKELY(!inserted)) {
  327. return InsertResult(false, entry->key());
  328. }
  329. insert_cb(lookup_key, static_cast<void*>(&entry->key_storage));
  330. return InsertResult(true, entry->key());
  331. }
  332. template <typename InputKeyT, typename InputKeyContextT>
  333. void SetBase<InputKeyT, InputKeyContextT>::GrowToAllocSize(
  334. ssize_t target_alloc_size, KeyContextT key_context) {
  335. this->GrowToAllocSizeImpl(target_alloc_size, key_context);
  336. }
  337. template <typename InputKeyT, typename InputKeyContextT>
  338. void SetBase<InputKeyT, InputKeyContextT>::GrowForInsertCount(
  339. ssize_t count, KeyContextT key_context) {
  340. this->GrowForInsertCountImpl(count, key_context);
  341. }
  342. template <typename InputKeyT, typename InputKeyContextT>
  343. template <typename LookupKeyT>
  344. auto SetBase<InputKeyT, InputKeyContextT>::Erase(LookupKeyT lookup_key,
  345. KeyContextT key_context)
  346. -> bool {
  347. return this->EraseImpl(lookup_key, key_context);
  348. }
  349. template <typename InputKeyT, typename InputKeyContextT>
  350. void SetBase<InputKeyT, InputKeyContextT>::Clear() {
  351. this->ClearImpl();
  352. }
  353. template <typename InputKeyT, ssize_t SmallSize, typename InputKeyContextT>
  354. void Set<InputKeyT, SmallSize, InputKeyContextT>::Reset() {
  355. this->ResetImpl();
  356. }
  357. } // namespace Carbon
  358. #endif // CARBON_COMMON_SET_H_