diff --git a/include/fmt/format.h b/include/fmt/format.h index 4a1663bb3e27..ed48a7c07be9 100644 --- a/include/fmt/format.h +++ b/include/fmt/format.h @@ -773,7 +773,8 @@ inline auto code_point_index(string_view s, size_t n) -> size_t { for (size_t i = 0, size = s.size(); i != size; ++i) { if ((data[i] & 0xc0) != 0x80 && ++num_code_points > n) return i; } - return s.size(); + size_t size = s.size(); + return n < size ? n : size; } inline auto code_point_index(basic_string_view s, size_t n) diff --git a/test/xchar-test.cc b/test/xchar-test.cc index 1deab2d02c9d..96fb4cfbea84 100644 --- a/test/xchar-test.cc +++ b/test/xchar-test.cc @@ -155,6 +155,8 @@ TEST(xchar_test, format_utf8_precision) { EXPECT_EQ(fmt::detail::compute_width(result), 4); EXPECT_EQ(result.size(), 5); EXPECT_EQ(from_u8str(result), from_u8str(str.substr(0, 5))); + + EXPECT_EQ(fmt::format("{:.0}", "\xad").size(), 0); } TEST(xchar_test, format_to) {