2 * Copyright (c) 1999-2005, 2008, 2010-2011
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 #include <sys/types.h>
45 #include <sys/param.h>
55 #endif /* STDC_HEADERS */
60 # if defined(HAVE_MEMORY_H) && !defined(STDC_HEADERS)
64 #endif /* HAVE_STRING_H */
67 #endif /* HAVE_STRINGS_H */
68 #if defined(HAVE_MALLOC_H) && !defined(STDC_HEADERS)
70 #endif /* HAVE_MALLOC_H && !STDC_HEADERS */
76 static int xxxprintf(char **, size_t, int, const char *, va_list);
79 * Some systems may not have these defined in <limits.h>
82 # define ULONG_MAX ((unsigned long)-1)
85 # define LONG_MAX (ULONG_MAX / 2)
87 #ifdef HAVE_LONG_LONG_INT
90 # define ULLONG_MAX UQUAD_MAX
92 # define ULLONG_MAX ((unsigned long long)-1)
97 # define LLONG_MAX QUAD_MAX
99 # define LLONG_MAX (ULLONG_MAX / 2)
102 #endif /* HAVE_LONG_LONG_INT */
105 * Macros for converting digits to letters and vice versa
107 #define to_digit(c) ((c) - '0')
108 #define is_digit(c) ((unsigned int)to_digit(c) <= 9)
109 #define to_char(n) ((n) + '0')
112 * Flags used during conversion.
114 #define ALT 0x001 /* alternate form */
115 #define HEXPREFIX 0x002 /* add 0x or 0X prefix */
116 #define LADJUST 0x004 /* left adjustment */
117 #define LONGDBL 0x008 /* long double; unimplemented */
118 #define LONGINT 0x010 /* long integer */
119 #define QUADINT 0x020 /* quad integer */
120 #define SHORTINT 0x040 /* short integer */
121 #define ZEROPAD 0x080 /* zero (as opposed to blank) pad */
126 * Convert an unsigned long to ASCII for printf purposes, returning
127 * a pointer to the first character of the string representation.
128 * Octal numbers can be forced to have a leading zero; hex numbers
129 * use the given digits.
132 __ultoa(unsigned long val, char *endp, int base, int octzero, char *xdigs)
138 * Handle the three cases separately, in the hope of getting
139 * better/faster code.
143 if (val < 10) { /* many numbers are 1 digit */
144 *--cp = to_char(val);
148 * On many machines, unsigned arithmetic is harder than
149 * signed arithmetic, so we do at most one unsigned mod and
150 * divide; this is sufficient to reduce the range of
151 * the incoming value to where signed arithmetic works.
153 if (val > LONG_MAX) {
154 *--cp = to_char(val % 10);
159 *--cp = to_char(sval % 10);
166 *--cp = to_char(val & 7);
169 if (octzero && *cp != '0')
175 *--cp = xdigs[val & 15];
186 /* Identical to __ultoa, but for quads. */
187 #ifdef HAVE_LONG_LONG_INT
188 # if SIZEOF_LONG_INT == 8
189 # define __uqtoa(v, e, b, o, x) __ultoa((unsigned long)(v), (e), (b), (o), (x))
192 __uqtoa(unsigned long long val, char *endp, int base, int octzero, char *xdigs)
197 /* quick test for small values; __ultoa is typically much faster */
198 /* (perhaps instead we should run until small, then call __ultoa?) */
199 if (val <= (unsigned long long)ULONG_MAX)
200 return __ultoa((unsigned long)val, endp, base, octzero, xdigs);
204 *--cp = to_char(val % 10);
207 if (val > LLONG_MAX) {
208 *--cp = to_char(val % 10);
213 *--cp = to_char(sval % 10);
220 *--cp = to_char(val & 7);
223 if (octzero && *cp != '0')
229 *--cp = xdigs[val & 15];
239 # endif /* !SIZEOF_LONG_INT */
240 #endif /* HAVE_LONG_LONG_INT */
243 * Actual printf innards.
246 xxxprintf(char **strp, size_t strsize, int alloc, const char *fmt0, va_list ap)
248 char *fmt; /* format string */
249 int ch; /* character from fmt */
250 int n; /* handy integer (short term usage) */
251 char *cp; /* handy char pointer (short term usage) */
252 int flags; /* flags as above */
253 int ret; /* return value accumulator */
254 int width; /* width from format (%8d), or 0 */
255 int prec; /* precision from format (%.3d), or -1 */
256 char sign; /* sign prefix (' ', '+', '-', or \0) */
257 unsigned long ulval = 0; /* integer arguments %[diouxX] */
258 #ifdef HAVE_LONG_LONG_INT
259 unsigned long long uqval = 0; /* %q (quad) integers */
261 int base; /* base for [diouxX] conversion */
262 int dprec; /* a copy of prec if [diouxX], 0 otherwise */
263 int fieldsz; /* field size expanded by sign, etc */
264 int realsz; /* field size expanded by dprec */
265 int size; /* size of converted field or string */
266 char *xdigs = ""; /* digits for [xX] conversion */
267 char buf[BUF]; /* space for %c, %[diouxX], %[eEfgG] */
268 char ox[2]; /* space for 0x hex-prefix */
269 char *str; /* pointer to string to fill */
270 char *estr; /* pointer to last char in str */
273 * Choose PADSIZE to trade efficiency vs. size. If larger printf
274 * fields occur frequently, increase PADSIZE and make the initialisers
277 #define PADSIZE 16 /* pad chunk size */
278 static char blanks[PADSIZE] =
279 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
280 static char zeroes[PADSIZE] =
281 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
283 /* Print chars to "str", (allocate as needed if alloc is set). */
284 #define PRINT(ptr, len) do { \
285 const char *p = ptr; \
286 const char *endp = ptr + len; \
287 while (p < endp && (str < estr || alloc)) { \
288 if (alloc && str >= estr) { \
290 strsize = (strsize << 1) + 1; \
291 if (!(t = (char *)realloc(*strp, strsize))) { \
297 str = t + (str - *strp); \
298 estr = t + strsize - 1; \
305 /* BEWARE, PAD uses `n'. */
306 #define PAD(plen, pstr) do { \
307 if ((n = (plen)) > 0) { \
308 while (n > PADSIZE) { \
309 PRINT(pstr, PADSIZE); \
317 * To extend shorts properly, we need both signed and unsigned
318 * argument extraction methods.
321 (flags&LONGINT ? va_arg(ap, long) : \
322 flags&SHORTINT ? (long)(short)va_arg(ap, int) : \
323 (long)va_arg(ap, int))
325 (flags&LONGINT ? va_arg(ap, unsigned long) : \
326 flags&SHORTINT ? (unsigned long)(unsigned short)va_arg(ap, int) : \
327 (unsigned long)va_arg(ap, unsigned int))
334 *strp = str = (char *)malloc(strsize);
343 estr = str + strsize - 1;
349 * Scan the format for conversions (`%' character).
352 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
354 if ((n = fmt - cp) != 0) {
360 fmt++; /* skip over '%' */
369 reswitch: switch (ch) {
372 * ``If the space and + flags both appear, the space
373 * flag will be ignored.''
384 * ``A negative field width argument is taken as a
385 * - flag followed by a positive field width.''
387 * They don't exclude field widths read from args.
389 if ((width = va_arg(ap, int)) >= 0)
400 if ((ch = *fmt++) == '*') {
402 prec = n < 0 ? -1 : n;
406 while (is_digit(ch)) {
407 n = 10 * n + to_digit(ch);
410 prec = n < 0 ? -1 : n;
414 * ``Note that 0 is taken as a flag, not as the
415 * beginning of a field width.''
420 case '1': case '2': case '3': case '4':
421 case '5': case '6': case '7': case '8': case '9':
424 n = 10 * n + to_digit(ch);
426 } while (is_digit(ch));
435 #ifdef HAVE_LONG_LONG_INT
439 #endif /* HAVE_LONG_LONG_INT */
441 *(cp = buf) = va_arg(ap, int);
450 #ifdef HAVE_LONG_LONG_INT
451 if (flags & QUADINT) {
452 uqval = va_arg(ap, long long);
453 if ((long long)uqval < 0) {
459 #endif /* HAVE_LONG_LONG_INT */
462 if ((long)ulval < 0) {
470 #ifdef HAVE_LONG_LONG_INT
472 *va_arg(ap, long long *) = ret;
474 #endif /* HAVE_LONG_LONG_INT */
476 *va_arg(ap, long *) = ret;
477 else if (flags & SHORTINT)
478 *va_arg(ap, short *) = ret;
480 *va_arg(ap, int *) = ret;
481 continue; /* no output */
486 #ifdef HAVE_LONG_LONG_INT
488 uqval = va_arg(ap, unsigned long long);
490 #endif /* HAVE_LONG_LONG_INT */
496 * ``The argument shall be a pointer to void. The
497 * value of the pointer is converted to a sequence
498 * of printable characters, in an implementation-
502 ulval = (unsigned long)va_arg(ap, void *);
504 xdigs = "0123456789abcdef";
505 flags = (flags & ~QUADINT) | HEXPREFIX;
509 if ((cp = va_arg(ap, char *)) == NULL)
513 * can't use strlen; can only look for the
514 * NUL in the first `prec' characters, and
515 * strlen() will go further.
517 char *p = memchr(cp, 0, prec);
533 #ifdef HAVE_LONG_LONG_INT
535 uqval = va_arg(ap, unsigned long long);
537 #endif /* HAVE_LONG_LONG_INT */
542 xdigs = "0123456789ABCDEF";
545 xdigs = "0123456789abcdef";
547 #ifdef HAVE_LONG_LONG_INT
549 uqval = va_arg(ap, unsigned long long);
551 #endif /* HAVE_LONG_LONG_INT */
554 /* leading 0x/X only if non-zero */
556 #ifdef HAVE_LONG_LONG_INT
557 (flags & QUADINT ? uqval != 0 : ulval != 0))
560 #endif /* HAVE_LONG_LONG_INT */
563 /* unsigned conversions */
566 * ``... diouXx conversions ... if a precision is
567 * specified, the 0 flag will be ignored.''
570 number: if ((dprec = prec) >= 0)
574 * ``The result of converting a zero value with an
575 * explicit precision of zero is no characters.''
579 #ifdef HAVE_LONG_LONG_INT
580 if (flags & QUADINT) {
581 if (uqval != 0 || prec != 0)
582 cp = __uqtoa(uqval, cp, base,
586 #endif /* HAVE_LONG_LONG_INT */
588 if (ulval != 0 || prec != 0)
589 cp = __ultoa(ulval, cp, base,
592 size = buf + BUF - cp;
594 default: /* "%?" prints ?, unless ? is NUL */
597 /* pretend it was %c with argument ch */
606 * All reasonable formats wind up here. At this point, `cp'
607 * points to a string which (if not flags&LADJUST) should be
608 * padded out to `width' places. If flags&ZEROPAD, it should
609 * first be prefixed by any sign or other prefix; otherwise,
610 * it should be blank padded before the prefix is emitted.
611 * After any left-hand padding and prefixing, emit zeroes
612 * required by a decimal [diouxX] precision, then print the
613 * string proper, then emit zeroes required by any leftover
614 * floating precision; finally, if LADJUST, pad with blanks.
616 * Compute actual size, so we know how much to pad.
617 * fieldsz excludes decimal prec; realsz includes it.
622 else if (flags & HEXPREFIX)
624 realsz = dprec > fieldsz ? dprec : fieldsz;
626 /* right-adjusting blank padding */
627 if ((flags & (LADJUST|ZEROPAD)) == 0)
628 PAD(width - realsz, blanks);
633 } else if (flags & HEXPREFIX) {
639 /* right-adjusting zero padding */
640 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
641 PAD(width - realsz, zeroes);
643 /* leading zeroes from decimal precision */
644 PAD(dprec - fieldsz, zeroes);
646 /* the string or number proper */
649 /* left-adjusting padding (always blank) */
651 PAD(width - realsz, blanks);
653 /* finally, adjust ret */
654 ret += width > realsz ? width : realsz;
663 #ifndef HAVE_VSNPRINTF
665 vsnprintf(char *str, size_t n, const char *fmt, va_list ap)
668 return xxxprintf(&str, n, 0, fmt, ap);
670 #endif /* HAVE_VSNPRINTF */
672 #ifndef HAVE_SNPRINTF
674 snprintf(char *str, size_t n, char const *fmt, ...)
680 ret = xxxprintf(&str, n, 0, fmt, ap);
684 #endif /* HAVE_SNPRINTF */
686 #ifndef HAVE_VASPRINTF
688 vasprintf(char **str, const char *fmt, va_list ap)
691 return xxxprintf(str, 0, 1, fmt, ap);
693 #endif /* HAVE_VASPRINTF */
695 #ifndef HAVE_ASPRINTF
697 asprintf(char **str, char const *fmt, ...)
703 ret = xxxprintf(str, 0, 1, fmt, ap);
707 #endif /* HAVE_ASPRINTF */