Skip to content

Commit

Permalink
Escape range items convertible to std::string_view
Browse files Browse the repository at this point in the history
  • Loading branch information
vitaut committed Dec 27, 2021
1 parent 33ee4cc commit 796662a
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
11 changes: 10 additions & 1 deletion include/fmt/ranges.h
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,9 @@ template <typename T> class is_std_string_like {

public:
static FMT_CONSTEXPR_DECL const bool value =
is_string<T>::value || !std::is_void<decltype(check<T>(nullptr))>::value;
is_string<T>::value ||
std::is_convertible<T, std_string_view<char>>::value ||
!std::is_void<decltype(check<T>(nullptr))>::value;
};

template <typename Char>
Expand Down Expand Up @@ -520,6 +522,13 @@ auto write_range_entry(OutputIt out, basic_string_view<Char> str) -> OutputIt {
return out;
}

template <typename Char, typename OutputIt, typename T,
FMT_ENABLE_IF(std::is_convertible<T, std_string_view<char>>::value)>
inline auto write_range_entry(OutputIt out, const T& str) -> OutputIt {
auto sv = std_string_view<Char>(str);
return write_range_entry<Char>(out, basic_string_view<Char>(sv));
}

template <typename Char, typename OutputIt, typename Arg,
FMT_ENABLE_IF(std::is_same<Arg, Char>::value)>
OutputIt write_range_entry(OutputIt out, const Arg v) {
Expand Down
11 changes: 11 additions & 0 deletions test/ranges-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -350,3 +350,14 @@ TEST(ranges_test, escape_string) {
"[\"\\xf4\\x8f\\xbf\\xc0\"]");
}
}

#ifdef FMT_USE_STRING_VIEW
struct convertible_to_string_view {
operator std::string_view() const { return "foo"; }
};

TEST(ranges_test, escape_convertible_to_string_view) {
EXPECT_EQ(fmt::format("{}", std::vector<convertible_to_string_view>(1)),
"[\"foo\"]");
}
#endif // FMT_USE_STRING_VIEW

0 comments on commit 796662a

Please sign in to comment.