Skip to content

Commit 86babf9

Browse files
addaleaxaduh95
authored andcommitted
src: use C++20 consteval for FastStringKey
This makes it easier to avoid unintentional mis-usage of the API. PR-URL: #59148 Reviewed-By: James M Snell <[email protected]> Reviewed-By: Juan José Arboleda <[email protected]> Reviewed-By: Daeyeon Jeong <[email protected]> Reviewed-By: Ilyas Shabi <[email protected]>
1 parent 7e0a0fc commit 86babf9

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

src/util-inl.h

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -618,7 +618,14 @@ constexpr bool FastStringKey::operator==(const FastStringKey& other) const {
618618
return name_ == other.name_;
619619
}
620620

621-
constexpr FastStringKey::FastStringKey(std::string_view name)
621+
consteval FastStringKey::FastStringKey(std::string_view name)
622+
: FastStringKey(name, 0) {}
623+
624+
constexpr FastStringKey FastStringKey::AllowDynamic(std::string_view name) {
625+
return FastStringKey(name, 0);
626+
}
627+
628+
constexpr FastStringKey::FastStringKey(std::string_view name, int dummy)
622629
: name_(name), cached_hash_(HashImpl(name)) {}
623630

624631
constexpr std::string_view FastStringKey::as_string_view() const {

src/util.h

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -822,7 +822,11 @@ class PersistentToLocal {
822822
// computations.
823823
class FastStringKey {
824824
public:
825-
constexpr explicit FastStringKey(std::string_view name);
825+
// consteval ensures that the argument is a compile-time constant.
826+
consteval explicit FastStringKey(std::string_view name);
827+
// passing something that is not a compile-time constant needs explicit
828+
// opt-in via this helper, as it defeats the purpose of FastStringKey.
829+
static constexpr FastStringKey AllowDynamic(std::string_view name);
826830

827831
struct Hash {
828832
constexpr size_t operator()(const FastStringKey& key) const;
@@ -832,6 +836,8 @@ class FastStringKey {
832836
constexpr std::string_view as_string_view() const;
833837

834838
private:
839+
constexpr explicit FastStringKey(std::string_view name, int dummy);
840+
835841
static constexpr size_t HashImpl(std::string_view str);
836842

837843
const std::string_view name_;

0 commit comments

Comments
 (0)