From: Bruno Haible <bruno@clisp.org>
Date: Wed, 22 Mar 2023 21:42:58 +0000 (+0100)
Subject: vasnprintf: Fix potentially wrong zero-padding.
X-Git-Url: https://gitweb.git.savannah.gnu.org/gitweb/?a=commitdiff_plain;h=d1a355527a3e83b123f0bfb68858f52a2fd739aa;p=gnulib.git

vasnprintf: Fix potentially wrong zero-padding.

* lib/vasnprintf.c (VASNPRINTF): Fix zero-padding when the result starts
with a prefix "0x" or "0b".
---

diff --git a/ChangeLog b/ChangeLog
index 3eeafa854d..f99842cdd6 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,9 @@
+2023-03-19  Bruno Haible  <bruno@clisp.org>
+
+	vasnprintf: Fix potentially wrong zero-padding.
+	* lib/vasnprintf.c (VASNPRINTF): Fix zero-padding when the result starts
+	with a prefix "0x" or "0b".
+
 2023-03-19  Paul Eggert  <eggert@cs.ucla.edu>
 
 	test-pselect, test-select: use different ports
diff --git a/lib/vasnprintf.c b/lib/vasnprintf.c
index 2280e9e71d..ad61dbba92 100644
--- a/lib/vasnprintf.c
+++ b/lib/vasnprintf.c
@@ -5596,6 +5596,22 @@ VASNPRINTF (DCHAR_T *resultbuf, size_t *lengthp,
                                   if ((*pad_ptr >= 'A' && *pad_ptr <= 'Z')
                                       || (*pad_ptr >= 'a' && *pad_ptr <= 'z'))
                                     pad_ptr = NULL;
+                                  else
+                                    /* Do the zero-padding after the "0x" or
+                                       "0b" prefix, not before.  */
+                                    if (p - rp >= 2
+                                        && *rp == '0'
+                                        && (((dp->conversion == 'a'
+                                              || dp->conversion == 'x')
+                                             && rp[1] == 'x')
+                                            || ((dp->conversion == 'A'
+                                                 || dp->conversion == 'X')
+                                                && rp[1] == 'X')
+                                            || (dp->conversion == 'b'
+                                                && rp[1] == 'b')
+                                            || (dp->conversion == 'B'
+                                                && rp[1] == 'B')))
+                                      pad_ptr += 2;
                                 }
                               /* The generated string now extends from rp to p,
                                  with the zero padding insertion point being at