2 * Copyright (c) 1999-2005, 2008, 2010
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 */
81 static int xxxprintf __P((char **, size_t, int, const char *, va_list));
84 * Some systems may not have these defined in <limits.h>
87 # define ULONG_MAX ((unsigned long)-1)
90 # define LONG_MAX (ULONG_MAX / 2)
92 #ifdef HAVE_LONG_LONG_INT
95 # define ULLONG_MAX UQUAD_MAX
97 # define ULLONG_MAX ((unsigned long long)-1)
102 # define LLONG_MAX QUAD_MAX
104 # define LLONG_MAX (ULLONG_MAX / 2)
107 #endif /* HAVE_LONG_LONG_INT */
110 * Macros for converting digits to letters and vice versa
112 #define to_digit(c) ((c) - '0')
113 #define is_digit(c) ((unsigned int)to_digit(c) <= 9)
114 #define to_char(n) ((n) + '0')
117 * Flags used during conversion.
119 #define ALT 0x001 /* alternate form */
120 #define HEXPREFIX 0x002 /* add 0x or 0X prefix */
121 #define LADJUST 0x004 /* left adjustment */
122 #define LONGDBL 0x008 /* long double; unimplemented */
123 #define LONGINT 0x010 /* long integer */
124 #define QUADINT 0x020 /* quad integer */
125 #define SHORTINT 0x040 /* short integer */
126 #define ZEROPAD 0x080 /* zero (as opposed to blank) pad */
138 const unsigned char *p = s;
142 return ((void *)(p - 1));
147 #endif /* !HAVE_MEMCHR */
150 * Convert an unsigned long to ASCII for printf purposes, returning
151 * a pointer to the first character of the string representation.
152 * Octal numbers can be forced to have a leading zero; hex numbers
153 * use the given digits.
156 __ultoa(val, endp, base, octzero, xdigs)
166 * Handle the three cases separately, in the hope of getting
167 * better/faster code.
171 if (val < 10) { /* many numbers are 1 digit */
172 *--cp = to_char(val);
176 * On many machines, unsigned arithmetic is harder than
177 * signed arithmetic, so we do at most one unsigned mod and
178 * divide; this is sufficient to reduce the range of
179 * the incoming value to where signed arithmetic works.
181 if (val > LONG_MAX) {
182 *--cp = to_char(val % 10);
187 *--cp = to_char(sval % 10);
194 *--cp = to_char(val & 7);
197 if (octzero && *cp != '0')
203 *--cp = xdigs[val & 15];
214 /* Identical to __ultoa, but for quads. */
215 #ifdef HAVE_LONG_LONG_INT
216 # if SIZEOF_LONG_INT == 8
217 # define __uqtoa(v, e, b, o, x) __ultoa((unsigned long)(v), (e), (b), (o), (x))
220 __uqtoa(val, endp, base, octzero, xdigs)
221 unsigned long long val;
229 /* quick test for small values; __ultoa is typically much faster */
230 /* (perhaps instead we should run until small, then call __ultoa?) */
231 if (val <= (unsigned long long)ULONG_MAX)
232 return (__ultoa((unsigned long)val, endp, base, octzero, xdigs));
236 *--cp = to_char(val % 10);
239 if (val > LLONG_MAX) {
240 *--cp = to_char(val % 10);
245 *--cp = to_char(sval % 10);
252 *--cp = to_char(val & 7);
255 if (octzero && *cp != '0')
261 *--cp = xdigs[val & 15];
271 # endif /* !SIZEOF_LONG_INT */
272 #endif /* HAVE_LONG_LONG_INT */
275 * Actual printf innards.
278 xxxprintf(strp, strsize, alloc, fmt0, ap)
285 char *fmt; /* format string */
286 int ch; /* character from fmt */
287 int n; /* handy integer (short term usage) */
288 char *cp; /* handy char pointer (short term usage) */
289 int flags; /* flags as above */
290 int ret; /* return value accumulator */
291 int width; /* width from format (%8d), or 0 */
292 int prec; /* precision from format (%.3d), or -1 */
293 char sign; /* sign prefix (' ', '+', '-', or \0) */
294 unsigned long ulval; /* integer arguments %[diouxX] */
295 #ifdef HAVE_LONG_LONG_INT
296 unsigned long long uqval; /* %q (quad) integers */
298 int base; /* base for [diouxX] conversion */
299 int dprec; /* a copy of prec if [diouxX], 0 otherwise */
300 int fieldsz; /* field size expanded by sign, etc */
301 int realsz; /* field size expanded by dprec */
302 int size; /* size of converted field or string */
303 char *xdigs; /* digits for [xX] conversion */
304 char buf[BUF]; /* space for %c, %[diouxX], %[eEfgG] */
305 char ox[2]; /* space for 0x hex-prefix */
306 char *str; /* pointer to string to fill */
307 char *estr; /* pointer to last char in str */
310 * Choose PADSIZE to trade efficiency vs. size. If larger printf
311 * fields occur frequently, increase PADSIZE and make the initialisers
314 #define PADSIZE 16 /* pad chunk size */
315 static char blanks[PADSIZE] =
316 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
317 static char zeroes[PADSIZE] =
318 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
320 /* Print chars to "str", (allocate as needed if alloc is set). */
321 #define PRINT(ptr, len) do { \
322 const char *p = ptr; \
323 const char *endp = ptr + len; \
324 while (p < endp && (str < estr || alloc)) { \
325 if (alloc && str >= estr) { \
327 strsize = (strsize << 1) + 1; \
328 if (!(t = (char *)realloc(*strp, strsize))) { \
334 str = t + (str - *strp); \
335 estr = t + strsize - 1; \
342 /* BEWARE, PAD uses `n'. */
343 #define PAD(howmany, with) do { \
344 if ((n = (howmany)) > 0) { \
345 while (n > PADSIZE) { \
346 PRINT(with, PADSIZE); \
354 * To extend shorts properly, we need both signed and unsigned
355 * argument extraction methods.
358 (flags&LONGINT ? va_arg(ap, long) : \
359 flags&SHORTINT ? (long)(short)va_arg(ap, int) : \
360 (long)va_arg(ap, int))
362 (flags&LONGINT ? va_arg(ap, unsigned long) : \
363 flags&SHORTINT ? (unsigned long)(unsigned short)va_arg(ap, int) : \
364 (unsigned long)va_arg(ap, unsigned int))
371 *strp = str = (char *)malloc(strsize);
380 estr = str + strsize - 1;
386 * Scan the format for conversions (`%' character).
389 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
391 if ((n = fmt - cp) != 0) {
397 fmt++; /* skip over '%' */
406 reswitch: switch (ch) {
409 * ``If the space and + flags both appear, the space
410 * flag will be ignored.''
421 * ``A negative field width argument is taken as a
422 * - flag followed by a positive field width.''
424 * They don't exclude field widths read from args.
426 if ((width = va_arg(ap, int)) >= 0)
437 if ((ch = *fmt++) == '*') {
439 prec = n < 0 ? -1 : n;
443 while (is_digit(ch)) {
444 n = 10 * n + to_digit(ch);
447 prec = n < 0 ? -1 : n;
451 * ``Note that 0 is taken as a flag, not as the
452 * beginning of a field width.''
457 case '1': case '2': case '3': case '4':
458 case '5': case '6': case '7': case '8': case '9':
461 n = 10 * n + to_digit(ch);
463 } while (is_digit(ch));
472 #ifdef HAVE_LONG_LONG_INT
476 #endif /* HAVE_LONG_LONG_INT */
478 *(cp = buf) = va_arg(ap, int);
487 #ifdef HAVE_LONG_LONG_INT
488 if (flags & QUADINT) {
489 uqval = va_arg(ap, long long);
490 if ((long long)uqval < 0) {
496 #endif /* HAVE_LONG_LONG_INT */
499 if ((long)ulval < 0) {
507 #ifdef HAVE_LONG_LONG_INT
509 *va_arg(ap, long long *) = ret;
511 #endif /* HAVE_LONG_LONG_INT */
513 *va_arg(ap, long *) = ret;
514 else if (flags & SHORTINT)
515 *va_arg(ap, short *) = ret;
517 *va_arg(ap, int *) = ret;
518 continue; /* no output */
523 #ifdef HAVE_LONG_LONG_INT
525 uqval = va_arg(ap, unsigned long long);
527 #endif /* HAVE_LONG_LONG_INT */
533 * ``The argument shall be a pointer to void. The
534 * value of the pointer is converted to a sequence
535 * of printable characters, in an implementation-
539 ulval = (unsigned long)va_arg(ap, void *);
541 xdigs = "0123456789abcdef";
542 flags = (flags & ~QUADINT) | HEXPREFIX;
546 if ((cp = va_arg(ap, char *)) == NULL)
550 * can't use strlen; can only look for the
551 * NUL in the first `prec' characters, and
552 * strlen() will go further.
554 char *p = memchr(cp, 0, prec);
570 #ifdef HAVE_LONG_LONG_INT
572 uqval = va_arg(ap, unsigned long long);
574 #endif /* HAVE_LONG_LONG_INT */
579 xdigs = "0123456789ABCDEF";
582 xdigs = "0123456789abcdef";
584 #ifdef HAVE_LONG_LONG_INT
586 uqval = va_arg(ap, unsigned long long);
588 #endif /* HAVE_LONG_LONG_INT */
591 /* leading 0x/X only if non-zero */
593 #ifdef HAVE_LONG_LONG_INT
594 (flags & QUADINT ? uqval != 0 : ulval != 0))
597 #endif /* HAVE_LONG_LONG_INT */
600 /* unsigned conversions */
603 * ``... diouXx conversions ... if a precision is
604 * specified, the 0 flag will be ignored.''
607 number: if ((dprec = prec) >= 0)
611 * ``The result of converting a zero value with an
612 * explicit precision of zero is no characters.''
616 #ifdef HAVE_LONG_LONG_INT
617 if (flags & QUADINT) {
618 if (uqval != 0 || prec != 0)
619 cp = __uqtoa(uqval, cp, base,
623 #endif /* HAVE_LONG_LONG_INT */
625 if (ulval != 0 || prec != 0)
626 cp = __ultoa(ulval, cp, base,
629 size = buf + BUF - cp;
631 default: /* "%?" prints ?, unless ? is NUL */
634 /* pretend it was %c with argument ch */
643 * All reasonable formats wind up here. At this point, `cp'
644 * points to a string which (if not flags&LADJUST) should be
645 * padded out to `width' places. If flags&ZEROPAD, it should
646 * first be prefixed by any sign or other prefix; otherwise,
647 * it should be blank padded before the prefix is emitted.
648 * After any left-hand padding and prefixing, emit zeroes
649 * required by a decimal [diouxX] precision, then print the
650 * string proper, then emit zeroes required by any leftover
651 * floating precision; finally, if LADJUST, pad with blanks.
653 * Compute actual size, so we know how much to pad.
654 * fieldsz excludes decimal prec; realsz includes it.
659 else if (flags & HEXPREFIX)
661 realsz = dprec > fieldsz ? dprec : fieldsz;
663 /* right-adjusting blank padding */
664 if ((flags & (LADJUST|ZEROPAD)) == 0)
665 PAD(width - realsz, blanks);
670 } else if (flags & HEXPREFIX) {
676 /* right-adjusting zero padding */
677 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
678 PAD(width - realsz, zeroes);
680 /* leading zeroes from decimal precision */
681 PAD(dprec - fieldsz, zeroes);
683 /* the string or number proper */
686 /* left-adjusting padding (always blank) */
688 PAD(width - realsz, blanks);
690 /* finally, adjust ret */
691 ret += width > realsz ? width : realsz;
700 #ifndef HAVE_VSNPRINTF
702 vsnprintf(str, n, fmt, ap)
709 return (xxxprintf(&str, n, 0, fmt, ap));
711 #endif /* HAVE_VSNPRINTF */
713 #ifndef HAVE_SNPRINTF
716 snprintf(char *str, size_t n, char const *fmt, ...)
718 snprintf(str, n, fmt, va_alist)
733 ret = xxxprintf(&str, n, 0, fmt, ap);
737 #endif /* HAVE_SNPRINTF */
739 #ifndef HAVE_VASPRINTF
741 vasprintf(str, fmt, ap)
747 return (xxxprintf(str, 0, 1, fmt, ap));
749 #endif /* HAVE_VASPRINTF */
751 #ifndef HAVE_ASPRINTF
754 asprintf(char **str, char const *fmt, ...)
756 asprintf(str, fmt, va_alist)
770 ret = xxxprintf(str, 0, 1, fmt, ap);
774 #endif /* HAVE_ASPRINTF */