diff mbox series

[committed] libstdc++: Fix std::format for chrono::duration with unsigned rep [PR115668]

Message ID 20240627085231.95403-1-jwakely@redhat.com
State New
Headers show
Series [committed] libstdc++: Fix std::format for chrono::duration with unsigned rep [PR115668] | expand

Commit Message

Jonathan Wakely June 27, 2024, 8:51 a.m. UTC
Tested x86_64-linux. Pushed to trunk. Backports needed to 13 and 14.

-- >8 --

Using std::chrono::abs is only valid if numeric_limits<rep>::is_signed
is true, so using it unconditionally made it ill-formed to format a
duration with an unsigned rep.

The duration formatter might as negate the duration itself instead of
using chrono::abs, because it already needs to check for a negative
value.

libstdc++-v3/ChangeLog:

	PR libstdc++/115668
	* include/bits/chrono_io.h (formatter<duration<R,P, C>::format):
	Do not use chrono::abs.
	* testsuite/20_util/duration/io.cc: Check formatting a duration
	with unsigned rep.
---
 libstdc++-v3/include/bits/chrono_io.h         | 5 ++++-
 libstdc++-v3/testsuite/20_util/duration/io.cc | 6 ++++++
 2 files changed, 10 insertions(+), 1 deletion(-)
diff mbox series

Patch

diff --git a/libstdc++-v3/include/bits/chrono_io.h b/libstdc++-v3/include/bits/chrono_io.h
index 3b34992b42a..72c66a0fef0 100644
--- a/libstdc++-v3/include/bits/chrono_io.h
+++ b/libstdc++-v3/include/bits/chrono_io.h
@@ -1607,7 +1607,10 @@  namespace __format
 	format(const chrono::duration<_Rep, _Period>& __d,
 	       basic_format_context<_Out, _CharT>& __fc) const
 	{
-	  return _M_f._M_format(chrono::abs(__d), __fc, __d < __d.zero());
+	  if constexpr (numeric_limits<_Rep>::is_signed)
+	    if (__d < __d.zero())
+	      return _M_f._M_format(-__d, __fc, true);
+	  return _M_f._M_format(__d, __fc, false);
 	}
 
     private:
diff --git a/libstdc++-v3/testsuite/20_util/duration/io.cc b/libstdc++-v3/testsuite/20_util/duration/io.cc
index 2f940ef86b7..6b00689672c 100644
--- a/libstdc++-v3/testsuite/20_util/duration/io.cc
+++ b/libstdc++-v3/testsuite/20_util/duration/io.cc
@@ -100,6 +100,12 @@  test_format()
   std::chrono::duration<float, std::milli> d{0.5};
   s = std::format("{}", d);
   VERIFY( s == "0.5ms" );
+
+  std::chrono::duration<unsigned, std::milli> u{500}; // PR libstdc++/115668
+  s = std::format("{}", u);
+  VERIFY( s == "500ms" );
+  s = std::format("{:%Q %q}", u);
+  VERIFY( s == "500 ms" );
 }
 
 void