From 9075a1a4bfdf120647320f2a979bb48ebbad75be Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Mon, 21 Jul 2025 18:17:45 +0200 Subject: [PATCH] src: use C++20 `consteval` for `FastStringKey` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This makes it easier to avoid unintentional mis-usage of the API. PR-URL: https://github.com/nodejs/node/pull/59148 Reviewed-By: James M Snell Reviewed-By: Juan José Arboleda Reviewed-By: Daeyeon Jeong Reviewed-By: Ilyas Shabi --- src/util-inl.h | 9 ++++++++- src/util.h | 8 +++++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/util-inl.h b/src/util-inl.h index cc41a1fb545..b21f7a8260c 100644 --- a/src/util-inl.h +++ b/src/util-inl.h @@ -598,7 +598,14 @@ constexpr bool FastStringKey::operator==(const FastStringKey& other) const { return name_ == other.name_; } -constexpr FastStringKey::FastStringKey(std::string_view name) +consteval FastStringKey::FastStringKey(std::string_view name) + : FastStringKey(name, 0) {} + +constexpr FastStringKey FastStringKey::AllowDynamic(std::string_view name) { + return FastStringKey(name, 0); +} + +constexpr FastStringKey::FastStringKey(std::string_view name, int dummy) : name_(name), cached_hash_(HashImpl(name)) {} constexpr std::string_view FastStringKey::as_string_view() const { diff --git a/src/util.h b/src/util.h index 6376cf4f811..dbec6624785 100644 --- a/src/util.h +++ b/src/util.h @@ -817,7 +817,11 @@ class PersistentToLocal { // computations. class FastStringKey { public: - constexpr explicit FastStringKey(std::string_view name); + // consteval ensures that the argument is a compile-time constant. + consteval explicit FastStringKey(std::string_view name); + // passing something that is not a compile-time constant needs explicit + // opt-in via this helper, as it defeats the purpose of FastStringKey. + static constexpr FastStringKey AllowDynamic(std::string_view name); struct Hash { constexpr size_t operator()(const FastStringKey& key) const; @@ -827,6 +831,8 @@ class FastStringKey { constexpr std::string_view as_string_view() const; private: + constexpr explicit FastStringKey(std::string_view name, int dummy); + static constexpr size_t HashImpl(std::string_view str); const std::string_view name_;