Skip to content

Commit 9075a1a

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 <jasnell@gmail.com> Reviewed-By: Juan JosΓ© Arboleda <soyjuanarbol@gmail.com> Reviewed-By: Daeyeon Jeong <daeyeon.dev@gmail.com> Reviewed-By: Ilyas Shabi <ilyasshabi94@gmail.com>
1 parent 3aee762 commit 9075a1a

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
@@ -598,7 +598,14 @@ constexpr bool FastStringKey::operator==(const FastStringKey& other) const {
598598
return name_ == other.name_;
599599
}
600600

601-
constexpr FastStringKey::FastStringKey(std::string_view name)
601+
consteval FastStringKey::FastStringKey(std::string_view name)
602+
: FastStringKey(name, 0) {}
603+
604+
constexpr FastStringKey FastStringKey::AllowDynamic(std::string_view name) {
605+
return FastStringKey(name, 0);
606+
}
607+
608+
constexpr FastStringKey::FastStringKey(std::string_view name, int dummy)
602609
: name_(name), cached_hash_(HashImpl(name)) {}
603610

604611
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
@@ -817,7 +817,11 @@ class PersistentToLocal {
817817
// computations.
818818
class FastStringKey {
819819
public:
820-
constexpr explicit FastStringKey(std::string_view name);
820+
// consteval ensures that the argument is a compile-time constant.
821+
consteval explicit FastStringKey(std::string_view name);
822+
// passing something that is not a compile-time constant needs explicit
823+
// opt-in via this helper, as it defeats the purpose of FastStringKey.
824+
static constexpr FastStringKey AllowDynamic(std::string_view name);
821825

822826
struct Hash {
823827
constexpr size_t operator()(const FastStringKey& key) const;
@@ -827,6 +831,8 @@ class FastStringKey {
827831
constexpr std::string_view as_string_view() const;
828832

829833
private:
834+
constexpr explicit FastStringKey(std::string_view name, int dummy);
835+
830836
static constexpr size_t HashImpl(std::string_view str);
831837

832838
const std::string_view name_;

0 commit comments

Comments
 (0)