diff mbox

[kvm-unit-tests,3/6] libcflat: fix padding in printf

Message ID 20170517201405.19867-4-rkrcmar@redhat.com (mailing list archive)
State New, archived
Headers show

Commit Message

Radim Krčmář May 17, 2017, 8:14 p.m. UTC
A simple test:

  printf(".%8p.\n",  (void *)0);
  printf(".%-8p.\n", (void *)0);
  printf(".%8p.\n",  (void *)1);
  printf(".%-8p.\n", (void *)1);
  printf(".%8p.\n",  (void *)0x123456);
  printf(".%-8p.\n", (void *)0x123456);

  printf(".%2p.\n",  (void *)0);
  printf(".%-2p.\n", (void *)0);
  printf(".%2p.\n",  (void *)1);
  printf(".%-2p.\n", (void *)1);

glibc:

  .   (nil).
  .(nil)   .
  .     0x1.
  .0x1     .
  .0x123456.
  .0x123456.
  .(nil).
  .(nil).
  .0x1.
  .0x1.

before patch:

  .      0x       0.
  .0x      0       .
  .      0x       1.
  .0x      1       .
  .      0x  123456.
  .0x      123456  .
  .0x 0.
  .0x0 .
  .0x 1.
  .0x1 .

after patch:

  .       0.
  .0       .
  .     0x1.
  .0x1     .
  .0x123456.
  .0x123456.
  . 0.
  .0 .
  .0x1.
  .0x1.

(nil) would be possible with a small change, but the standard leaves it
to the implementation and 0 is acceptable, IMO.

Signed-off-by: Radim Krčmář <rkrcmar@redhat.com>
---
 lib/printf.c | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
diff mbox

Patch

diff --git a/lib/printf.c b/lib/printf.c
index e7818e1ded0e..944768f3080d 100644
--- a/lib/printf.c
+++ b/lib/printf.c
@@ -18,6 +18,7 @@  typedef struct pstream {
 typedef struct strprops {
     char pad;
     int npad;
+    bool alternate;
 } strprops_t;
 
 static void addchar(pstream_t *p, char c)
@@ -94,7 +95,7 @@  void print_int(pstream_t *ps, long long n, int base, strprops_t props)
 void print_unsigned(pstream_t *ps, unsigned long long n, int base,
 		    strprops_t props)
 {
-    char buf[sizeof(long) * 3 + 1], *p = buf;
+    char buf[sizeof(long) * 3 + 3], *p = buf;
     int i;
 
     while (n) {
@@ -104,6 +105,10 @@  void print_unsigned(pstream_t *ps, unsigned long long n, int base,
 
     if (p == buf)
 	*p++ = '0';
+    else if (props.alternate && base == 16) {
+	*p++ = 'x';
+	*p++ = '0';
+    }
 
     for (i = 0; i < (p - buf) / 2; ++i) {
 	char tmp;
@@ -225,7 +230,7 @@  int vsnprintf(char *buf, int size, const char *fmt, va_list va)
 	    }
 	    break;
 	case 'p':
-	    print_str(&s, "0x", props);
+	    props.alternate = true;
 	    print_unsigned(&s, (unsigned long)va_arg(va, void *), 16, props);
 	    break;
 	case 's':