Skip to content

Commit

Permalink
Fix chrono formatting with invalid argument id (#1132)
Browse files Browse the repository at this point in the history
  • Loading branch information
vitaut committed Apr 28, 2019
1 parent 8d8ea21 commit 4c721e3
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 10 deletions.
31 changes: 21 additions & 10 deletions include/fmt/chrono.h
Original file line number Diff line number Diff line change
Expand Up @@ -585,28 +585,39 @@ struct formatter<std::chrono::duration<Rep, Period>, Char> {
}
};

public:
formatter() : spec(), precision(-1) {}
typedef typename basic_parse_context<Char>::iterator iterator;
struct parse_range {
iterator begin;
iterator end;
};

FMT_CONSTEXPR auto parse(basic_parse_context<Char>& ctx)
-> decltype(ctx.begin()) {
FMT_CONSTEXPR parse_range do_parse(basic_parse_context<Char>& ctx) {
auto begin = ctx.begin(), end = ctx.end();
if (begin == end) return begin;
if (begin == end) return {begin, end};
spec_handler handler{*this, ctx, format_str};
begin = internal::parse_align(begin, end, handler);
if (begin == end) return begin;
if (begin == end) return {begin, end};
begin = internal::parse_width(begin, end, handler);
if (begin == end) return begin;
if (begin == end) return {begin, end};
if (*begin == '.') {
if (std::is_floating_point<Rep>::value)
begin = internal::parse_precision(begin, end, handler);
else
handler.on_error("precision not allowed for this argument type");
}
end = parse_chrono_format(begin, end, internal::chrono_format_checker());
format_str =
basic_string_view<Char>(&*begin, internal::to_unsigned(end - begin));
return end;
return {begin, end};
}

public:
formatter() : spec(), precision(-1) {}

FMT_CONSTEXPR auto parse(basic_parse_context<Char>& ctx)
-> decltype(ctx.begin()) {
auto range = do_parse(ctx);
format_str = basic_string_view<Char>(
&*range.begin, internal::to_unsigned(range.end - range.begin));
return range.end;
}

template <typename FormatContext>
Expand Down
5 changes: 5 additions & 0 deletions test/chrono-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -296,4 +296,9 @@ TEST(ChronoTest, FormatFullSpecsQq) {
EXPECT_EQ("*1.2340 ms*", fmt::format("{:*^11.4%Q %q}", dms(1.234)));
}

TEST(ChronoTest, InvalidWidthId) {
EXPECT_THROW(fmt::format("{:{o}", std::chrono::seconds(0)),
fmt::format_error);
}

#endif // FMT_STATIC_THOUSANDS_SEPARATOR

0 comments on commit 4c721e3

Please sign in to comment.