From 4e49c81474d0723e242c44451774e9f4fc22deba Mon Sep 17 00:00:00 2001 From: Tim Ohliger Date: Fri, 10 Jan 2025 11:15:04 +0100 Subject: [PATCH] Fixed wrong computation of sanitized string literal length --- include/pybind11/typing.h | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/include/pybind11/typing.h b/include/pybind11/typing.h index b65207fcca..6660855bbc 100644 --- a/include/pybind11/typing.h +++ b/include/pybind11/typing.h @@ -18,6 +18,7 @@ #if defined(__cpp_nontype_template_args) && __cpp_nontype_template_args >= 201911L # define PYBIND11_TYPING_H_HAS_STRING_LITERAL +# include # include # include #endif @@ -259,12 +260,15 @@ struct handle_type_name { template consteval auto sanitize_string_literal() { constexpr std::string_view v(StrLit.name); - char result[v.size() + std::ranges::count(v, '!') + std::ranges::count(v, '@') - + std::ranges::count(v, '%') + std::ranges::count(v, '{') - + std::ranges::count(v, '}') + 1]; + constexpr std::string_view special_chars("!@%{}-"); + constexpr auto num_special_chars = std::accumulate( + special_chars.begin(), special_chars.end(), 0, [&v](auto acc, const char &c) { + return std::move(acc) + std::ranges::count(v, c); + }); + char result[v.size() + num_special_chars + 1]; size_t i = 0; for (auto c : StrLit.name) { - if (c == '!' || c == '@' || c == '%' || c == '{' || c == '}' || c == '-') { + if (special_chars.find(c) != std::string_view::npos) { result[i++] = '!'; } result[i++] = c;