Skip to content

Commit

Permalink
Make precision computation consistent with width
Browse files Browse the repository at this point in the history
  • Loading branch information
vitaut committed May 11, 2022
1 parent f63afd1 commit 358f5a7
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
15 changes: 10 additions & 5 deletions include/fmt/format.h
Original file line number Diff line number Diff line change
Expand Up @@ -680,8 +680,8 @@ FMT_CONSTEXPR inline size_t compute_width(string_view s) {
}

inline auto compute_width(basic_string_view<char8_type> s) -> size_t {
return compute_width(basic_string_view<char>(
reinterpret_cast<const char*>(s.data()), s.size()));
return compute_width(
string_view(reinterpret_cast<const char*>(s.data()), s.size()));
}

template <typename Char>
Expand All @@ -691,16 +691,21 @@ inline auto code_point_index(basic_string_view<Char> s, size_t n) -> size_t {
}

// Calculates the index of the nth code point in a UTF-8 string.
inline auto code_point_index(basic_string_view<char8_type> s, size_t n)
-> size_t {
const char8_type* data = s.data();
inline auto code_point_index(string_view s, size_t n) -> size_t {
const char* data = s.data();
size_t num_code_points = 0;
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();
}

inline auto code_point_index(basic_string_view<char8_type> s, size_t n)
-> size_t {
return code_point_index(
string_view(reinterpret_cast<const char*>(s.data()), s.size()), n);
}

#ifndef FMT_USE_FLOAT128
# ifdef __SIZEOF_FLOAT128__
# define FMT_USE_FLOAT128 1
Expand Down
1 change: 1 addition & 0 deletions test/format-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1035,6 +1035,7 @@ TEST(format_test, precision) {
format_error, "number is too big");

EXPECT_EQ("st", fmt::format("{0:.2}", "str"));
EXPECT_EQ("вожык", fmt::format("{0:.5}", "вожыкі"));
}

TEST(format_test, runtime_precision) {
Expand Down

0 comments on commit 358f5a7

Please sign in to comment.