]> git.ipfire.org Git - thirdparty/gcc.git/commitdiff
libstdc++: Fix std::format("{}", negative_integer) [PR114325]
authorJonathan Wakely <jwakely@redhat.com>
Wed, 13 Mar 2024 21:19:54 +0000 (21:19 +0000)
committerJonathan Wakely <jwakely@redhat.com>
Thu, 14 Mar 2024 16:58:15 +0000 (16:58 +0000)
The fast path for "{}" format strings has a bug for negative integers
where the length passed to std::to_chars is too long.

libstdc++-v3/ChangeLog:

PR libstdc++/114325
* include/std/format (_Scanner::_M_scan): Pass correct length to
__to_chars_10_impl.
* testsuite/std/format/functions/format.cc: Check negative
integers with empty format-spec.

libstdc++-v3/include/std/format
libstdc++-v3/testsuite/std/format/functions/format.cc

index 1e839e88db48f8a2491886197e1ce188f34eb11e..613016d1a10728fd519c28bfa099138188af7fb1 100644 (file)
@@ -4091,6 +4091,7 @@ namespace __format
        __sink_out = __sink.out();
 
       if constexpr (is_same_v<_CharT, char>)
+       // Fast path for "{}" format strings and simple format arg types.
        if (__fmt.size() == 2 && __fmt[0] == '{' && __fmt[1] == '}')
          {
            bool __done = false;
@@ -4124,14 +4125,14 @@ namespace __format
                    __uval = make_unsigned_t<_Tp>(~__arg) + 1u;
                  else
                    __uval = __arg;
-                 const auto __n = __detail::__to_chars_len(__uval) + __neg;
-                 if (auto __res = __sink_out._M_reserve(__n))
+                 const auto __n = __detail::__to_chars_len(__uval);
+                 if (auto __res = __sink_out._M_reserve(__n + __neg))
                    {
                      auto __ptr = __res.get();
                      *__ptr = '-';
                      __detail::__to_chars_10_impl(__ptr + (int)__neg, __n,
                                                   __uval);
-                     __res._M_bump(__n);
+                     __res._M_bump(__n + __neg);
                      __done = true;
                    }
                }
index a27fbe74631b79e8e3585c472cb54849c77d2d22..4499397aaf9744f5c9c40620e08bbfadc707a629 100644 (file)
@@ -157,6 +157,11 @@ test_std_examples()
 
     // Restore
     std::locale::global(std::locale::classic());
+
+    string s5 = format("{}", -100); // PR libstdc++/114325
+    VERIFY(s5 == "-100");
+    string s6 = format("{:d} {:d}", -123, 999);
+    VERIFY(s6 == "-123 999");
   }
 }