2 * Copyright (c) 1999-2005, 2008, 2010-2013
3 * Todd C. Miller <Todd.Miller@courtesan.com>
4 * Copyright (c) 1990, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * From: @(#)vfprintf.c 8.1 (Berkeley) 6/4/93
38 * v?snprintf/v?asprintf based on 4.4BSD stdio.
39 * NOTE: does not support floating point.
44 #if !defined(HAVE_VSNPRINTF) || !defined(HAVE_SNPRINTF) || !defined(HAVE_VASPRINTF) || !defined(HAVE_ASPRINTF)
46 #include <sys/types.h>
56 #endif /* STDC_HEADERS */
57 #if defined(HAVE_STDINT_H)
59 #elif defined(HAVE_INTTYPES_H)
60 # include <inttypes.h>
63 # if defined(HAVE_MEMORY_H) && !defined(STDC_HEADERS)
67 #endif /* HAVE_STRING_H */
70 #endif /* HAVE_STRINGS_H */
71 #if defined(HAVE_MALLOC_H) && !defined(STDC_HEADERS)
73 #endif /* HAVE_MALLOC_H && !STDC_HEADERS */
79 static int xxxprintf(char **, size_t, int, const char *, va_list);
82 * Some systems may not have these defined in <limits.h>
85 # define ULONG_MAX ((unsigned long)-1)
88 # define LONG_MAX (ULONG_MAX / 2)
90 #ifdef HAVE_LONG_LONG_INT
93 # define ULLONG_MAX UQUAD_MAX
95 # define ULLONG_MAX ((unsigned long long)-1)
100 # define LLONG_MAX QUAD_MAX
102 # define LLONG_MAX (ULLONG_MAX / 2)
105 #endif /* HAVE_LONG_LONG_INT */
108 * Macros for converting digits to letters and vice versa
110 #define to_digit(c) ((c) - '0')
111 #define is_digit(c) ((unsigned int)to_digit(c) <= 9)
112 #define to_char(n) ((n) + '0')
115 * Flags used during conversion.
117 #define ALT 0x001 /* alternate form */
118 #define HEXPREFIX 0x002 /* add 0x or 0X prefix */
119 #define LADJUST 0x004 /* left adjustment */
120 #define LONGDBL 0x008 /* long double; unimplemented */
121 #define LONGINT 0x010 /* long integer */
122 #define LLONGINT 0x020 /* quad integer */
123 #define SHORTINT 0x040 /* short integer */
124 #define ZEROPAD 0x080 /* zero (as opposed to blank) pad */
129 * Convert an unsigned long to ASCII for printf purposes, returning
130 * a pointer to the first character of the string representation.
131 * Octal numbers can be forced to have a leading zero; hex numbers
132 * use the given digits.
135 __ultoa(unsigned long val, char *endp, int base, int octzero, char *xdigs)
141 * Handle the three cases separately, in the hope of getting
142 * better/faster code.
146 if (val < 10) { /* many numbers are 1 digit */
147 *--cp = to_char(val);
151 * On many machines, unsigned arithmetic is harder than
152 * signed arithmetic, so we do at most one unsigned mod and
153 * divide; this is sufficient to reduce the range of
154 * the incoming value to where signed arithmetic works.
156 if (val > LONG_MAX) {
157 *--cp = to_char(val % 10);
162 *--cp = to_char(sval % 10);
169 *--cp = to_char(val & 7);
172 if (octzero && *cp != '0')
178 *--cp = xdigs[val & 15];
189 /* Identical to __ultoa, but for quads. */
190 #ifdef HAVE_LONG_LONG_INT
191 # if SIZEOF_LONG_INT == 8
192 # define __uqtoa(v, e, b, o, x) __ultoa((unsigned long)(v), (e), (b), (o), (x))
195 __uqtoa(unsigned long long val, char *endp, int base, int octzero, char *xdigs)
200 /* quick test for small values; __ultoa is typically much faster */
201 /* (perhaps instead we should run until small, then call __ultoa?) */
202 if (val <= (unsigned long long)ULONG_MAX)
203 return __ultoa((unsigned long)val, endp, base, octzero, xdigs);
207 *--cp = to_char(val % 10);
210 if (val > LLONG_MAX) {
211 *--cp = to_char(val % 10);
216 *--cp = to_char(sval % 10);
223 *--cp = to_char(val & 7);
226 if (octzero && *cp != '0')
232 *--cp = xdigs[val & 15];
242 # endif /* !SIZEOF_LONG_INT */
243 #endif /* HAVE_LONG_LONG_INT */
246 * Actual printf innards.
249 xxxprintf(char **strp, size_t strsize, int alloc, const char *fmt0, va_list ap)
251 char *fmt; /* format string */
252 int ch; /* character from fmt */
253 int n; /* handy integer (short term usage) */
254 char *cp; /* handy char pointer (short term usage) */
255 int flags; /* flags as above */
256 int ret; /* return value accumulator */
257 int width; /* width from format (%8d), or 0 */
258 int prec; /* precision from format (%.3d), or -1 */
259 char sign; /* sign prefix (' ', '+', '-', or \0) */
260 unsigned long ulval = 0; /* integer arguments %[diouxX] */
261 #ifdef HAVE_LONG_LONG_INT
262 unsigned long long uqval = 0; /* %q (quad) integers */
264 int base; /* base for [diouxX] conversion */
265 int dprec; /* a copy of prec if [diouxX], 0 otherwise */
266 int fieldsz; /* field size expanded by sign, etc */
267 int realsz; /* field size expanded by dprec */
268 int size; /* size of converted field or string */
269 char *xdigs = ""; /* digits for [xX] conversion */
270 char buf[BUF]; /* space for %c, %[diouxX], %[eEfgG] */
271 char ox[2]; /* space for 0x hex-prefix */
272 char *str; /* pointer to string to fill */
273 char *estr; /* pointer to last char in str */
276 * Choose PADSIZE to trade efficiency vs. size. If larger printf
277 * fields occur frequently, increase PADSIZE and make the initialisers
280 #define PADSIZE 16 /* pad chunk size */
281 static char blanks[PADSIZE] =
282 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
283 static char zeroes[PADSIZE] =
284 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
286 /* Print chars to "str", (allocate as needed if alloc is set). */
287 #define PRINT(ptr, len) do { \
288 const char *p = ptr; \
289 const char *endp = ptr + len; \
290 while (p < endp && (str < estr || alloc)) { \
291 if (alloc && str >= estr) { \
293 strsize = (strsize << 1) + 1; \
294 if (!(t = (char *)realloc(*strp, strsize))) { \
300 str = t + (str - *strp); \
301 estr = t + strsize - 1; \
308 /* BEWARE, PAD uses `n'. */
309 #define PAD(plen, pstr) do { \
310 if ((n = (plen)) > 0) { \
311 while (n > PADSIZE) { \
312 PRINT(pstr, PADSIZE); \
320 * To extend shorts properly, we need both signed and unsigned
321 * argument extraction methods.
324 (flags&LONGINT ? va_arg(ap, long) : \
325 flags&SHORTINT ? (long)(short)va_arg(ap, int) : \
326 (long)va_arg(ap, int))
328 (flags&LONGINT ? va_arg(ap, unsigned long) : \
329 flags&SHORTINT ? (unsigned long)(unsigned short)va_arg(ap, int) : \
330 (unsigned long)va_arg(ap, unsigned int))
337 *strp = str = (char *)malloc(strsize);
346 estr = str + strsize - 1;
352 * Scan the format for conversions (`%' character).
355 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
357 if ((n = fmt - cp) != 0) {
363 fmt++; /* skip over '%' */
372 reswitch: switch (ch) {
375 * ``If the space and + flags both appear, the space
376 * flag will be ignored.''
387 * ``A negative field width argument is taken as a
388 * - flag followed by a positive field width.''
390 * They don't exclude field widths read from args.
392 if ((width = va_arg(ap, int)) >= 0)
403 if ((ch = *fmt++) == '*') {
405 prec = n < 0 ? -1 : n;
409 while (is_digit(ch)) {
410 n = 10 * n + to_digit(ch);
413 prec = n < 0 ? -1 : n;
417 * ``Note that 0 is taken as a flag, not as the
418 * beginning of a field width.''
423 case '1': case '2': case '3': case '4':
424 case '5': case '6': case '7': case '8': case '9':
427 n = 10 * n + to_digit(ch);
429 } while (is_digit(ch));
443 #ifdef HAVE_LONG_LONG_INT
447 #endif /* HAVE_LONG_LONG_INT */
449 *(cp = buf) = va_arg(ap, int);
458 #ifdef HAVE_LONG_LONG_INT
459 if (flags & LLONGINT) {
460 uqval = va_arg(ap, long long);
461 if ((long long)uqval < 0) {
467 #endif /* HAVE_LONG_LONG_INT */
470 if ((long)ulval < 0) {
478 #ifdef HAVE_LONG_LONG_INT
479 if (flags & LLONGINT)
480 *va_arg(ap, long long *) = ret;
482 #endif /* HAVE_LONG_LONG_INT */
484 *va_arg(ap, long *) = ret;
485 else if (flags & SHORTINT)
486 *va_arg(ap, short *) = ret;
488 *va_arg(ap, int *) = ret;
489 continue; /* no output */
494 #ifdef HAVE_LONG_LONG_INT
495 if (flags & LLONGINT)
496 uqval = va_arg(ap, unsigned long long);
498 #endif /* HAVE_LONG_LONG_INT */
504 * ``The argument shall be a pointer to void. The
505 * value of the pointer is converted to a sequence
506 * of printable characters, in an implementation-
510 ulval = (unsigned long)va_arg(ap, void *);
512 xdigs = "0123456789abcdef";
513 flags = (flags & ~LLONGINT) | HEXPREFIX;
517 if ((cp = va_arg(ap, char *)) == NULL)
521 * can't use strlen; can only look for the
522 * NUL in the first `prec' characters, and
523 * strlen() will go further.
525 char *p = memchr(cp, 0, prec);
541 #ifdef HAVE_LONG_LONG_INT
542 if (flags & LLONGINT)
543 uqval = va_arg(ap, unsigned long long);
545 #endif /* HAVE_LONG_LONG_INT */
550 xdigs = "0123456789ABCDEF";
553 xdigs = "0123456789abcdef";
555 #ifdef HAVE_LONG_LONG_INT
556 if (flags & LLONGINT)
557 uqval = va_arg(ap, unsigned long long);
559 #endif /* HAVE_LONG_LONG_INT */
562 /* leading 0x/X only if non-zero */
564 #ifdef HAVE_LONG_LONG_INT
565 (flags & LLONGINT ? uqval != 0 : ulval != 0))
568 #endif /* HAVE_LONG_LONG_INT */
571 /* unsigned conversions */
574 * ``... diouXx conversions ... if a precision is
575 * specified, the 0 flag will be ignored.''
578 number: if ((dprec = prec) >= 0)
582 * ``The result of converting a zero value with an
583 * explicit precision of zero is no characters.''
587 #ifdef HAVE_LONG_LONG_INT
588 if (flags & LLONGINT) {
589 if (uqval != 0 || prec != 0)
590 cp = __uqtoa(uqval, cp, base,
594 #endif /* HAVE_LONG_LONG_INT */
596 if (ulval != 0 || prec != 0)
597 cp = __ultoa(ulval, cp, base,
600 size = buf + BUF - cp;
602 default: /* "%?" prints ?, unless ? is NUL */
605 /* pretend it was %c with argument ch */
614 * All reasonable formats wind up here. At this point, `cp'
615 * points to a string which (if not flags&LADJUST) should be
616 * padded out to `width' places. If flags&ZEROPAD, it should
617 * first be prefixed by any sign or other prefix; otherwise,
618 * it should be blank padded before the prefix is emitted.
619 * After any left-hand padding and prefixing, emit zeroes
620 * required by a decimal [diouxX] precision, then print the
621 * string proper, then emit zeroes required by any leftover
622 * floating precision; finally, if LADJUST, pad with blanks.
624 * Compute actual size, so we know how much to pad.
625 * fieldsz excludes decimal prec; realsz includes it.
630 else if (flags & HEXPREFIX)
632 realsz = dprec > fieldsz ? dprec : fieldsz;
634 /* right-adjusting blank padding */
635 if ((flags & (LADJUST|ZEROPAD)) == 0)
636 PAD(width - realsz, blanks);
641 } else if (flags & HEXPREFIX) {
647 /* right-adjusting zero padding */
648 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
649 PAD(width - realsz, zeroes);
651 /* leading zeroes from decimal precision */
652 PAD(dprec - fieldsz, zeroes);
654 /* the string or number proper */
657 /* left-adjusting padding (always blank) */
659 PAD(width - realsz, blanks);
661 /* finally, adjust ret */
662 ret += width > realsz ? width : realsz;
671 #ifndef HAVE_VSNPRINTF
673 vsnprintf(char *str, size_t n, const char *fmt, va_list ap)
676 return xxxprintf(&str, n, 0, fmt, ap);
678 #endif /* HAVE_VSNPRINTF */
680 #ifndef HAVE_SNPRINTF
682 snprintf(char *str, size_t n, char const *fmt, ...)
688 ret = xxxprintf(&str, n, 0, fmt, ap);
692 #endif /* HAVE_SNPRINTF */
694 #ifndef HAVE_VASPRINTF
696 vasprintf(char **str, const char *fmt, va_list ap)
699 return xxxprintf(str, 0, 1, fmt, ap);
701 #endif /* HAVE_VASPRINTF */
703 #ifndef HAVE_ASPRINTF
705 asprintf(char **str, char const *fmt, ...)
711 ret = xxxprintf(str, 0, 1, fmt, ap);
715 #endif /* HAVE_ASPRINTF */
717 #endif /* !HAVE_VSNPRINTF || !HAVE_SNPRINTF || !HAVE_VASPRINTF || !HAVE_ASPRINTF */