Skip to content

Avoiding __builtin_strlen #4429

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Apr 27, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion include/fmt/base.h
Original file line number Diff line number Diff line change
Expand Up @@ -539,7 +539,7 @@ template <typename Char> class basic_string_view {
#endif
FMT_CONSTEXPR20 basic_string_view(const Char* s) : data_(s) {
#if FMT_HAS_BUILTIN(__builtin_strlen) || FMT_GCC_VERSION || FMT_CLANG_VERSION
if (std::is_same<Char, char>::value) {
if (std::is_same<Char, char>::value && !detail::is_constant_evaluated()) {
size_ = __builtin_strlen(detail::narrow(s));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the advantage of still using __builtin_strlen? Will gcc or clang still end up producing a constant in some scenarios that they wouldn't if just strlen was used?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well... libstdc++ __builtin_strlen in char_traits, so I guess there's that.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There was some benefit to the debug codegen at some point but probably no longer matters on newer compilers.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

More importantly, strlen is not constexpr.

return;
}
Expand Down
23 changes: 23 additions & 0 deletions test/base-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,29 @@ TEST(string_view_test, compare) {
check_op<std::greater_equal>();
}

#if FMT_USE_CONSTEVAL
namespace {

template <size_t N>
struct fixed_string {
char data[N] = {};

constexpr fixed_string(char const (&m)[N]) {
for (size_t i = 0; i != N; ++i) {
data[i] = m[i];
}
}
};

}

TEST(string_view_test, from_constexpr_fixed_string) {
static constexpr auto fs = fixed_string<5>("x={}");
static constexpr auto fmt = fmt::string_view(fs.data);
EXPECT_EQ(fmt, "x={}");
}
#endif

TEST(base_test, is_locking) {
EXPECT_FALSE(fmt::detail::is_locking<const char(&)[3]>());
}
Expand Down