Skip to content

Commit

Permalink
<chrono: Rewrite %r spec for C locale (#1865)
Browse files Browse the repository at this point in the history
put_time(%r) does the wrong thing when we use the C locale, due to some
internal machinery. It could get fixed further down level, but that
change is a lot more impactful. Instead, we simply rewrite %r when the C
locale is used in chrono.

This basically has to do with the way that _Strftime, _Gettnames, and
expand_time work together. _Gettnames returns a copy of its data and
expand_time figures out the locale based on pointer comparison.
  • Loading branch information
eldakesh-ms authored Apr 20, 2021
1 parent 65ad8a7 commit d488200
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
14 changes: 14 additions & 0 deletions stl/inc/chrono
Original file line number Diff line number Diff line change
Expand Up @@ -6014,6 +6014,20 @@ namespace chrono {
}
_Os << _Time.tm_mday;
return true;
case 'r':
if constexpr (_Is_specialization_v<_Ty, hh_mm_ss>) {
// put_time uses _Strftime in order to bypass reference-counting that locale uses. This function
// takes the locale information by pointer, but the pointer (from _Gettnames) returns a copy.
// _Strftime delegates to other functions but eventually (for the C locale) has the %r specifier
// rewritten. It checks for the locale by comparing pointers, which do not compare equal as we have
// a copy of the pointer instead of the original. Therefore, we replace %r for the C locale
// ourselves.
if (_Os.getloc() == locale::classic()) {
_Os << _STD put_time(&_Time, _STATICALLY_WIDEN(_CharT, "%I:%M:%S %p"));
return true;
}
}
return false;
case 'j':
if constexpr (_Is_specialization_v<_Ty, duration>) {
_Os << _STD abs(_CHRONO duration_cast<days>(_Val).count());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -595,10 +595,10 @@ void test_hh_mm_ss_formatter() {
empty_braces_helper(hh_mm_ss{65745s}, STR("18:15:45"));

assert(format(STR("{:%H %I %M %S %r %R %T %p}"), hh_mm_ss{13h + 14min + 15351ms})
== STR("13 01 14 15.351 13:14:15 13:14 13:14:15.351 PM"));
== STR("13 01 14 15.351 01:14:15 PM 13:14 13:14:15.351 PM"));

assert(format(STR("{:%H %I %M %S %r %R %T %p}"), hh_mm_ss{-13h - 14min - 15351ms})
== STR("-13 01 14 15.351 13:14:15 13:14 13:14:15.351 PM"));
== STR("-13 01 14 15.351 01:14:15 PM 13:14 13:14:15.351 PM"));

throw_helper(STR("{}"), hh_mm_ss{24h});
throw_helper(STR("{}"), hh_mm_ss{-24h});
Expand Down

0 comments on commit d488200

Please sign in to comment.