set.h 16 KB

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