diff mbox

[kvm-unit-tests,5/6] libcflat: support # flag in printf

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

Commit Message

Radim Krčmář May 17, 2017, 8:14 p.m. UTC
The only use is with %#x, where we'll automatically get 0x prefix.
Advantage over 0x%x can be seen with padding.

A simple test:

  printf(".%#08x.\n", 0);
  printf(".%#8x.\n",  0);
  printf(".%#-8x.\n", 0);

  printf(".%#08x.\n", 1);
  printf(".%#8x.\n",  1);
  printf(".%#-8x.\n", 1);

  printf(".%#08x.\n", 0x123456);
  printf(".%#8x.\n",  0x123456);
  printf(".%#-8x.\n", 0x123456);

  printf(".%#02x.\n", 0);
  printf(".%#2x.\n",  0);
  printf(".%#-2x.\n", 0);

  printf(".%#02x.\n", 1);
  printf(".%#2x.\n",  1);
  printf(".%#-2x.\n", 1);

looks just like glibc:

  .00000000.
  .       0.
  .0       .
  .0x000001.
  .     0x1.
  .0x1     .
  .0x123456.
  .0x123456.
  .0x123456.
  .00.
  . 0.
  .0 .
  .0x1.
  .0x1.
  .0x1.

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

Patch

diff --git a/lib/printf.c b/lib/printf.c
index 944768f3080d..bfe05f573f08 100644
--- a/lib/printf.c
+++ b/lib/printf.c
@@ -106,8 +106,16 @@  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';
+	if (props.pad == '0') {
+	    addchar(ps, '0');
+	    addchar(ps, 'x');
+
+	    if (props.npad > 0)
+		props.npad = MAX(props.npad - 2, 0);
+	} else {
+	    *p++ = 'x';
+	    *p++ = '0';
+	}
     }
 
     for (i = 0; i < (p - buf) / 2; ++i) {
@@ -169,6 +177,9 @@  int vsnprintf(char *buf, int size, const char *fmt, va_list va)
 	case '\0':
 	    --fmt;
 	    break;
+	case '#':
+	    props.alternate = true;
+	    goto morefmt;
 	case '0':
 	    props.pad = '0';
 	    ++fmt;