Fix buffer overflow if output iterator is std::back_insert_iterator and value is escaped (debug format)

Signed-off-by: Vladislav Shchapov <vladislav@shchapov.ru>
This commit is contained in:
Vladislav Shchapov 2024-01-10 16:52:52 +05:00 committed by Victor Zverovich
parent 401f087394
commit 961df829b9
2 changed files with 15 additions and 2 deletions

View File

@ -2388,9 +2388,12 @@ FMT_CONSTEXPR auto write(OutputIt out, basic_string_view<Char> s,
size = code_point_index(s, to_unsigned(specs.precision)); size = code_point_index(s, to_unsigned(specs.precision));
bool is_debug = specs.type == presentation_type::debug; bool is_debug = specs.type == presentation_type::debug;
size_t width = 0; size_t width = 0;
if (is_debug) size = write_escaped_string(counting_iterator{}, s).count();
if (specs.width != 0) { if (specs.width != 0) {
if (is_debug) if (is_debug)
width = write_escaped_string(counting_iterator{}, s).count(); width = size;
else else
width = compute_width(basic_string_view<Char>(data, size)); width = compute_width(basic_string_view<Char>(data, size));
} }

View File

@ -85,6 +85,16 @@ TEST(compile_test, format_default) {
# endif # endif
} }
TEST(compile_test, format_escape) {
EXPECT_EQ("\"string\"", fmt::format(FMT_COMPILE("{:?}"), "string"));
EXPECT_EQ("prefix \"string\"",
fmt::format(FMT_COMPILE("prefix {:?}"), "string"));
EXPECT_EQ("\"string\" suffix",
fmt::format(FMT_COMPILE("{:?} suffix"), "string"));
EXPECT_EQ("\"abc\"", fmt::format(FMT_COMPILE("{0:<5?}"), "abc"));
EXPECT_EQ("\"abc\" ", fmt::format(FMT_COMPILE("{0:<7?}"), "abc"));
}
TEST(compile_test, format_wide_string) { TEST(compile_test, format_wide_string) {
EXPECT_EQ(L"42", fmt::format(FMT_COMPILE(L"{}"), 42)); EXPECT_EQ(L"42", fmt::format(FMT_COMPILE(L"{}"), 42));
} }