2 * Copyright (c) 1990, 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * $FreeBSD: src/lib/libc/stdio/vfwprintf.c,v 1.24 2005/04/16 22:36:51 das Exp $
37 * $NetBSD: vfwprintf.c,v 1.3 2005/06/15 09:31:27 he Exp $
38 * $DragonFly: src/lib/libc/stdio/vfwprintf.c,v 1.2 2005/11/20 11:07:30 swildner Exp $
42 * Actual wprintf innards.
44 * Avoid making gratuitous changes to this source file; it should be kept
45 * as close as possible to vfprintf.c for ease of maintenance.
48 #include "namespace.h"
49 #include <sys/types.h>
65 #include "un-namespace.h"
67 #include "libc_private.h"
69 #include "priv_stdio.h"
76 unsigned long ulongarg;
77 long long longlongarg;
78 unsigned long long ulonglongarg;
85 signed char *pschararg;
90 ptrdiff_t *pptrdiffarg;
93 #ifndef NO_FLOATING_POINT
95 long double longdoublearg;
102 * Type ids for argument type table.
105 T_UNUSED, TP_SHORT, T_INT, T_U_INT, TP_INT,
106 T_LONG, T_U_LONG, TP_LONG, T_LLONG, T_U_LLONG, TP_LLONG,
107 T_PTRDIFFT, TP_PTRDIFFT, T_SIZET, TP_SIZET,
108 T_INTMAXT, T_UINTMAXT, TP_INTMAXT, TP_VOID, TP_CHAR, TP_SCHAR,
109 T_DOUBLE, T_LONG_DOUBLE, T_WINT, TP_WCHAR
112 static int __sbprintf(FILE *, const wchar_t *, va_list);
113 static wint_t __xfputwc(wchar_t, FILE *);
114 static wchar_t *__ujtoa(uintmax_t, wchar_t *, int, int, const char *, int,
116 static wchar_t *__ultoa(u_long, wchar_t *, int, int, const char *, int,
118 static wchar_t *__mbsconv(char *, int);
119 static void __find_arguments(const wchar_t *, va_list, union arg **);
120 static void __grow_type_table(int, enum typeid **, int *);
123 * Helper function for `fprintf to unbuffered unix file': creates a
124 * temporary buffer. We only work on write-only files; this avoids
125 * worries about ungetc buffers and so forth.
128 __sbprintf(FILE *fp, const wchar_t *fmt, va_list ap)
132 unsigned char buf[BUFSIZ];
134 /* copy the important variables */
135 fake.pub._flags = fp->pub._flags & ~__SNBF;
136 fake.pub._fileno = fp->pub._fileno;
137 fake._cookie = fp->_cookie;
138 fake._write = fp->_write;
141 fake.fl_mutex = fp->fl_mutex;
142 fake.fl_owner = fp->fl_owner;
143 fake.fl_count = fp->fl_count;
145 /* set up the buffer */
146 fake._bf._base = fake.pub._p = buf;
147 fake._bf._size = fake.pub._w = sizeof(buf);
148 fake.pub._lbfsize = 0; /* not actually used, but Just In Case */
150 /* do the work, then copy any error status */
151 ret = __vfwprintf_unlocked(&fake, fmt, ap);
152 if (ret >= 0 && __fflush(&fake))
154 if (fake.pub._flags & __SERR)
155 fp->pub._flags |= __SERR;
160 * Like __fputwc, but handles fake string (__SSTR) files properly.
161 * File must already be locked.
164 __xfputwc(wchar_t wc, FILE *fp)
166 static const mbstate_t initial;
168 char buf[MB_LEN_MAX];
173 if ((fp->pub._flags & __SSTR) == 0)
174 return (__fputwc_unlock(wc, fp));
177 if ((len = wcrtomb(buf, wc, &mbs)) == (size_t)-1) {
178 fp->pub._flags |= __SERR;
186 return (__sfvwrite(fp, &uio) != EOF ? (wint_t)wc : WEOF);
190 * Macros for converting digits to letters and vice versa
192 #define to_digit(c) ((c) - '0')
193 #define is_digit(c) ((unsigned)to_digit(c) <= 9)
194 #define to_char(n) (wchar_t)((n) + '0')
197 * Convert an unsigned long to ASCII for printf purposes, returning
198 * a pointer to the first character of the string representation.
199 * Octal numbers can be forced to have a leading zero; hex numbers
200 * use the given digits.
203 __ultoa(u_long val, wchar_t *endp, int base, int octzero, const char *xdigs,
204 int needgrp, char thousep, const char *grp)
211 * Handle the three cases separately, in the hope of getting
212 * better/faster code.
216 if (val < 10) { /* many numbers are 1 digit */
217 *--cp = to_char(val);
222 * On many machines, unsigned arithmetic is harder than
223 * signed arithmetic, so we do at most one unsigned mod and
224 * divide; this is sufficient to reduce the range of
225 * the incoming value to where signed arithmetic works.
227 if (val > LONG_MAX) {
228 *--cp = to_char(val % 10);
234 *--cp = to_char(sval % 10);
237 * If (*grp == CHAR_MAX) then no more grouping
238 * should be performed.
240 if (needgrp && ndig == *grp && *grp != CHAR_MAX &&
245 * If (*(grp+1) == '\0') then we have to
246 * use *grp character (last grouping rule)
249 if (*(grp+1) != '\0')
258 *--cp = to_char(val & 7);
261 if (octzero && *cp != '0')
267 *--cp = xdigs[(size_t)val & 15];
278 /* Identical to __ultoa, but for intmax_t. */
280 __ujtoa(uintmax_t val, wchar_t *endp, int base, int octzero,
281 const char *xdigs, int needgrp, char thousep, const char *grp)
287 /* quick test for small values; __ultoa is typically much faster */
288 /* (perhaps instead we should run until small, then call __ultoa?) */
289 if (val <= ULONG_MAX)
290 return (__ultoa((u_long)val, endp, base, octzero, xdigs,
291 needgrp, thousep, grp));
295 *--cp = to_char(val % 10);
299 if (val > INTMAX_MAX) {
300 *--cp = to_char(val % 10);
306 *--cp = to_char(sval % 10);
309 * If (*grp == CHAR_MAX) then no more grouping
310 * should be performed.
312 if (needgrp && *grp != CHAR_MAX && ndig == *grp &&
317 * If (*(grp+1) == '\0') then we have to
318 * use *grp character (last grouping rule)
321 if (*(grp+1) != '\0')
330 *--cp = to_char(val & 7);
333 if (octzero && *cp != '0')
339 *--cp = xdigs[(size_t)val & 15];
351 * Convert a multibyte character string argument for the %s format to a wide
352 * string representation. ``prec'' specifies the maximum number of bytes
353 * to output. If ``prec'' is greater than or equal to zero, we can't assume
354 * that the multibyte char. string ends in a null character.
357 __mbsconv(char *mbsarg, int prec)
359 static const mbstate_t initial;
361 wchar_t *convbuf, *wcp;
363 size_t insize, nchars, nconv;
369 * Supplied argument is a multibyte string; convert it to wide
374 * String is not guaranteed to be NUL-terminated. Find the
375 * number of characters to print.
378 insize = nchars = nconv = 0;
380 while (nchars != (size_t)prec) {
381 nconv = mbrlen(p, MB_CUR_MAX, &mbs);
382 if (nconv == 0 || nconv == (size_t)-1 ||
389 if (nconv == (size_t)-1 || nconv == (size_t)-2)
392 insize = strlen(mbsarg);
395 * Allocate buffer for the result and perform the conversion,
396 * converting at most `size' bytes of the input multibyte string to
397 * wide characters for printing.
399 convbuf = malloc((insize + 1) * sizeof(*convbuf));
406 while (insize != 0) {
407 nconv = mbrtowc(wcp, p, insize, &mbs);
408 if (nconv == 0 || nconv == (size_t)-1 || nconv == (size_t)-2)
414 if (nconv == (size_t)-1 || nconv == (size_t)-2) {
427 vfwprintf(FILE * __restrict fp, const wchar_t * __restrict fmt0, va_list ap)
432 ret = __vfwprintf_unlocked(fp, fmt0, ap);
437 #ifndef NO_FLOATING_POINT
440 #define freedtoa __freedtoa
448 static int exponent(wchar_t *, int, wchar_t);
449 static wchar_t *cvt(double, int, int, char *, int *, int, int *, char **);
451 #endif /* !NO_FLOATING_POINT */
454 * The size of the buffer we use as scratch space for integer
455 * conversions, among other things. Technically, we would need the
456 * most space for base 10 conversions with thousands' grouping
457 * characters between each pair of digits. 100 bytes is a
458 * conservative overestimate even for a 128-bit uintmax_t.
462 #define STATIC_ARG_TBL_SIZE 8 /* Size of static argument table. */
465 * Flags used during conversion.
467 #define ALT 0x001 /* alternate form */
468 #define LADJUST 0x004 /* left adjustment */
469 #define LONGDBL 0x008 /* long double */
470 #define LONGINT 0x010 /* long integer */
471 #define LLONGINT 0x020 /* quad_t integer */
472 #define SHORTINT 0x040 /* short integer */
473 #define ZEROPAD 0x080 /* zero (as opposed to blank) pad */
474 #define FPT 0x100 /* Floating point number */
475 #define GROUPING 0x200 /* use grouping ("'" flag) */
476 /* C99 additional size modifiers: */
477 #define SIZET 0x400 /* size_t */
478 #define PTRDIFFT 0x800 /* ptrdiff_t */
479 #define INTMAXT 0x1000 /* intmax_t */
480 #define CHARINT 0x2000 /* print char using int format */
483 * Non-MT-safe version
486 __vfwprintf_unlocked(FILE *fp, const wchar_t *fmt0, va_list ap)
488 wchar_t *fmt; /* format string */
489 wchar_t ch; /* character from fmt */
490 int n, n2, n3; /* handy integer (short term usage) */
491 wchar_t *cp; /* handy char pointer (short term usage) */
492 int flags; /* flags as above */
493 int ret; /* return value accumulator */
494 int width; /* width from format (%8d), or 0 */
495 int prec; /* precision from format; <0 for N/A */
496 wchar_t sign; /* sign prefix (' ', '+', '-', or \0) */
497 char thousands_sep; /* locale specific thousands separator */
498 const char *grouping; /* locale specific numeric grouping rules */
499 #ifndef NO_FLOATING_POINT
501 * We can decompose the printed representation of floating
502 * point numbers into several parts, some of which may be empty:
504 * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ
507 * A: 'sign' holds this value if present; '\0' otherwise
508 * B: ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal
509 * C: cp points to the string MMMNNN. Leading and trailing
510 * zeros are not in the string and must be added.
511 * D: expchar holds this character; '\0' if no exponent, e.g. %f
512 * F: at least two digits for decimal, at least one digit for hex
514 const char *decimal_point; /* locale specific decimal point */
516 int signflag; /* true if float is negative */
517 union { /* floating point arguments %[aAeEfFgG] */
521 char *dtoaend; /* pointer to end of converted digits */
523 double _double; /* double precision arguments %[eEfgG] */
524 char softsign; /* temporary negative sign for floats */
526 int expt; /* integer value of exponent */
527 char expchar; /* exponent character: [eEpP\0] */
528 int expsize; /* character count for expstr */
529 char *dtoaresult; /* buffer allocated by dtoa */
530 int lead; /* sig figs before decimal or group sep */
531 int ndig; /* actual number of digits returned by dtoa */
532 wchar_t expstr[MAXEXPDIG+2]; /* buffer for exponent string: e+ZZZ */
533 int nseps; /* number of group separators with ' */
534 int nrepeats; /* number of repeats of the last group */
536 u_long ulval; /* integer arguments %[diouxX] */
537 uintmax_t ujval; /* %j, %ll, %q, %t, %z integers */
538 int base; /* base for [diouxX] conversion */
539 int dprec; /* a copy of prec if [diouxX], 0 otherwise */
540 int realsz; /* field size expanded by dprec, sign, etc */
541 int size; /* size of converted field or string */
542 int prsize; /* max size of printed field */
543 const char *xdigs; /* digits for [xX] conversion */
544 wchar_t buf[BUF]; /* buffer with space for digits of uintmax_t */
545 wchar_t ox[2]; /* space for 0x hex-prefix */
546 union arg *argtable; /* args, built due to positional arg */
547 union arg statargtable [STATIC_ARG_TBL_SIZE];
548 int nextarg; /* 1-based argument index */
549 va_list orgap; /* original argument pointer */
550 wchar_t *convbuf; /* multibyte to wide conversion result */
553 * Choose PADSIZE to trade efficiency vs. size. If larger printf
554 * fields occur frequently, increase PADSIZE and make the initialisers
557 #define PADSIZE 16 /* pad chunk size */
558 static wchar_t blanks[PADSIZE] =
559 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
560 static wchar_t zeroes[PADSIZE] =
561 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
563 static const char xdigs_lower[16] = "0123456789abcdef";
564 static const char xdigs_upper[16] = "0123456789ABCDEF";
567 * BEWARE, these `goto error' on error, PRINT uses `n2' and
570 #define PRINT(ptr, len) do { \
571 for (n3 = 0; n3 < (len); n3++) \
572 __xfputwc((ptr)[n3], fp); \
573 } while (/*CONSTCOND*/0)
574 #define PAD(howmany, with) do { \
575 if ((n = (howmany)) > 0) { \
576 while (n > PADSIZE) { \
577 PRINT(with, PADSIZE); \
582 } while (/*CONSTCOND*/0)
583 #define PRINTANDPAD(p, ep, len, with) do { \
589 PAD((len) - (n2 > 0 ? n2 : 0), (with)); \
590 } while(/*CONSTCOND*/0)
593 * Get the argument indexed by nextarg. If the argument table is
594 * built, use it to get the argument. If its not, get the next
595 * argument (and arguments must be gotten sequentially).
597 #define GETARG(type) \
598 ((/*CONSTCOND*/argtable != NULL) ? *((type*)(void*)(&argtable[nextarg++])) : \
599 (nextarg++, va_arg(ap, type)))
602 * To extend shorts properly, we need both signed and unsigned
603 * argument extraction methods.
606 (flags&LONGINT ? GETARG(long) : \
607 flags&SHORTINT ? (long)(short)GETARG(int) : \
608 flags&CHARINT ? (long)(signed char)GETARG(int) : \
611 (flags&LONGINT ? GETARG(u_long) : \
612 flags&SHORTINT ? (u_long)(u_short)GETARG(int) : \
613 flags&CHARINT ? (u_long)(u_char)GETARG(int) : \
614 (u_long)GETARG(u_int))
615 #define INTMAX_SIZE (INTMAXT|SIZET|PTRDIFFT|LLONGINT)
617 (flags&INTMAXT ? GETARG(intmax_t) : \
618 flags&SIZET ? (intmax_t)GETARG(size_t) : \
619 flags&PTRDIFFT ? (intmax_t)GETARG(ptrdiff_t) : \
620 (intmax_t)GETARG(quad_t))
622 (flags&INTMAXT ? GETARG(uintmax_t) : \
623 flags&SIZET ? (uintmax_t)GETARG(size_t) : \
624 flags&PTRDIFFT ? (uintmax_t)GETARG(ptrdiff_t) : \
625 (uintmax_t)GETARG(u_quad_t))
628 * Get * arguments, including the form *nn$. Preserve the nextarg
629 * that the argument can be gotten once the type is determined.
631 #define GETASTER(val) \
634 while (is_digit(*cp)) { \
635 n2 = 10 * n2 + to_digit(*cp); \
639 int hold = nextarg; \
640 if (argtable == NULL) { \
641 argtable = statargtable; \
642 __find_arguments (fmt0, orgap, &argtable); \
645 val = GETARG (int); \
649 val = GETARG (int); \
653 thousands_sep = '\0';
655 #ifndef NO_FLOATING_POINT
657 decimal_point = localeconv()->decimal_point;
658 expsize = 0; /* XXXGCC -Wuninitialized [sh3,m68000] */
661 /* sorry, fwprintf(read_only_file, L"") returns WEOF, not 0 */
667 /* optimise fprintf(stderr) (and other unbuffered Unix files) */
668 if ((fp->pub._flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
669 fp->pub._fileno >= 0)
670 return (__sbprintf(fp, fmt0, ap));
672 fmt = __DECONST(wchar_t *, fmt0);
679 * Scan the format for conversions (`%' character).
682 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
684 if ((n = fmt - cp) != 0) {
685 if ((unsigned)ret + n > INT_MAX) {
694 fmt++; /* skip over '%' */
704 nseps = nrepeats = 0;
710 reswitch: switch (ch) {
713 * ``If the space and + flags both appear, the space
714 * flag will be ignored.''
725 * ``A negative field width argument is taken as a
726 * - flag followed by a positive field width.''
728 * They don't exclude field widths read from args.
743 thousands_sep = *(localeconv()->thousands_sep);
744 grouping = localeconv()->grouping;
747 if ((ch = *fmt++) == '*') {
752 while (is_digit(ch)) {
753 prec = 10 * prec + to_digit(ch);
759 * ``Note that 0 is taken as a flag, not as the
760 * beginning of a field width.''
765 case '1': case '2': case '3': case '4':
766 case '5': case '6': case '7': case '8': case '9':
769 n = 10 * n + to_digit(ch);
771 } while (is_digit(ch));
774 if (argtable == NULL) {
775 argtable = statargtable;
776 __find_arguments (fmt0, orgap,
783 #ifndef NO_FLOATING_POINT
789 if (flags & SHORTINT) {
799 if (flags & LONGINT) {
806 flags |= LLONGINT; /* not necessarily */
819 *(cp = buf) = (wchar_t)GETARG(wint_t);
821 *(cp = buf) = (wchar_t)btowc(GETARG(int));
830 if (flags & INTMAX_SIZE) {
832 if ((intmax_t)ujval < 0) {
838 if ((long)ulval < 0) {
845 #ifndef NO_FLOATING_POINT
860 if (flags & LONGDBL) {
861 fparg.ldbl = GETARG(long double);
863 __hldtoa(fparg.ldbl, xdigs, prec,
864 &expt, &signflag, &dtoaend);
866 fparg.dbl = GETARG(double);
868 __hdtoa(fparg.dbl, xdigs, prec,
869 &expt, &signflag, &dtoaend);
873 prec = dtoaend - dtoaresult;
878 ndig = dtoaend - dtoaresult;
879 cp = convbuf = __mbsconv(dtoaresult, -1);
880 freedtoa(dtoaresult);
885 if (prec < 0) /* account for digit before decpt */
896 expchar = ch - ('g' - 'e');
904 if (flags & LONGDBL) {
905 fparg.ldbl = GETARG(long double);
907 __ldtoa(&fparg.ldbl, expchar ? 2 : 3, prec,
908 &expt, &signflag, &dtoaend);
910 fparg.dbl = GETARG(double);
912 dtoa(fparg.dbl, expchar ? 2 : 3, prec,
913 &expt, &signflag, &dtoaend);
917 ndig = dtoaend - dtoaresult;
918 cp = convbuf = __mbsconv(dtoaresult, -1);
919 freedtoa(dtoaresult);
923 if (expt == INT_MAX) { /* inf or nan */
925 cp = (ch >= 'a') ? L"nan" : L"NAN";
928 cp = (ch >= 'a') ? L"inf" : L"INF";
941 } else if ((ch == 'g' || ch == 'G') && prec == 0) {
945 if (flags & LONGDBL) {
946 _double = (double) GETARG(long double);
948 _double = GETARG(double);
951 /* do this before tricky precision changes */
952 if (isinf(_double)) {
955 if (ch == 'E' || ch == 'F' || ch == 'G')
962 if (isnan(_double)) {
963 if (ch == 'E' || ch == 'F' || ch == 'G')
972 if (dtoaresult != NULL) {
976 cp = cvt(_double, prec, flags, &softsign,
977 &expt, ch, &ndig, &dtoaresult);
982 if (ch == 'g' || ch == 'G') {
983 if (expt > -4 && expt <= prec) {
984 /* Make %[gG] smell like %[fF] */
994 * Make %[gG] smell like %[eE], but
995 * trim trailing zeroes if no # flag.
1002 expsize = exponent(expstr, expt - 1, expchar);
1003 size = expsize + prec;
1004 if (prec > 1 || flags & ALT)
1007 /* space for digits before decimal point */
1012 /* space for decimal pt and following digits */
1013 if (prec || flags & ALT)
1015 if (grouping && expt > 0) {
1016 /* space for thousands' grouping */
1017 nseps = nrepeats = 0;
1019 while (*grouping != CHAR_MAX) {
1020 if (lead <= *grouping)
1023 if (*(grouping+1)) {
1029 size += nseps + nrepeats;
1034 #endif /* !NO_FLOATING_POINT */
1037 * Assignment-like behavior is specified if the
1038 * value overflows or is otherwise unrepresentable.
1039 * C99 says to use `signed char' for %hhn conversions.
1041 if (flags & LLONGINT)
1042 *GETARG(quad_t *) = ret;
1043 else if (flags & SIZET)
1044 *GETARG(ssize_t *) = (ssize_t)ret;
1045 else if (flags & PTRDIFFT)
1046 *GETARG(ptrdiff_t *) = ret;
1047 else if (flags & INTMAXT)
1048 *GETARG(intmax_t *) = ret;
1049 else if (flags & LONGINT)
1050 *GETARG(long *) = ret;
1051 else if (flags & SHORTINT)
1052 *GETARG(short *) = ret;
1053 else if (flags & CHARINT)
1054 *GETARG(signed char *) = ret;
1056 *GETARG(int *) = ret;
1057 continue; /* no output */
1062 if (flags & INTMAX_SIZE)
1070 * ``The argument shall be a pointer to void. The
1071 * value of the pointer is converted to a sequence
1072 * of printable characters, in an implementation-
1076 ujval = (uintmax_t)(uintptr_t)GETARG(void *);
1078 xdigs = xdigs_lower;
1079 flags = flags | INTMAXT;
1086 if (flags & LONGINT) {
1087 if ((cp = GETARG(wchar_t *)) == NULL)
1092 if (convbuf != NULL)
1094 if ((mbp = GETARG(char *)) == NULL)
1097 convbuf = __mbsconv(mbp, prec);
1098 if (convbuf == NULL) {
1099 fp->pub._flags |= __SERR;
1108 * can't use wcslen; can only look for the
1109 * NUL in the first `prec' characters, and
1110 * wcslen() will go further.
1112 wchar_t *p = wmemchr(cp, 0, (size_t)prec);
1128 if (flags & INTMAX_SIZE)
1135 xdigs = xdigs_upper;
1138 xdigs = xdigs_lower;
1140 if (flags & INTMAX_SIZE)
1145 /* leading 0x/X only if non-zero */
1147 (flags & INTMAX_SIZE ? ujval != 0 : ulval != 0))
1151 /* unsigned conversions */
1152 nosign: sign = '\0';
1154 * ``... diouXx conversions ... if a precision is
1155 * specified, the 0 flag will be ignored.''
1158 number: if ((dprec = prec) >= 0)
1162 * ``The result of converting a zero value with an
1163 * explicit precision of zero is no characters.''
1166 * ``The C Standard is clear enough as is. The call
1167 * printf("%#.0o", 0) should print 0.''
1168 * -- Defect Report #151
1171 if (flags & INTMAX_SIZE) {
1172 if (ujval != 0 || prec != 0 ||
1173 (flags & ALT && base == 8))
1174 cp = __ujtoa(ujval, cp, base,
1176 flags & GROUPING, thousands_sep,
1179 if (ulval != 0 || prec != 0 ||
1180 (flags & ALT && base == 8))
1181 cp = __ultoa(ulval, cp, base,
1183 flags & GROUPING, thousands_sep,
1186 size = buf + BUF - cp;
1187 if (size > BUF) /* should never happen */
1190 default: /* "%?" prints ?, unless ? is NUL */
1193 /* pretend it was %c with argument ch */
1202 * All reasonable formats wind up here. At this point, `cp'
1203 * points to a string which (if not flags&LADJUST) should be
1204 * padded out to `width' places. If flags&ZEROPAD, it should
1205 * first be prefixed by any sign or other prefix; otherwise,
1206 * it should be blank padded before the prefix is emitted.
1207 * After any left-hand padding and prefixing, emit zeroes
1208 * required by a decimal [diouxX] precision, then print the
1209 * string proper, then emit zeroes required by any leftover
1210 * floating precision; finally, if LADJUST, pad with blanks.
1212 * Compute actual size, so we know how much to pad.
1213 * size excludes decimal prec; realsz includes it.
1215 realsz = dprec > size ? dprec : size;
1221 prsize = width > realsz ? width : realsz;
1222 if ((unsigned)ret + prsize > INT_MAX) {
1227 /* right-adjusting blank padding */
1228 if ((flags & (LADJUST|ZEROPAD)) == 0)
1229 PAD(width - realsz, blanks);
1235 if (ox[1]) { /* ox[1] is either x, X, or \0 */
1240 /* right-adjusting zero padding */
1241 if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
1242 PAD(width - realsz, zeroes);
1244 /* leading zeroes from decimal precision */
1245 PAD(dprec - size, zeroes);
1247 /* the string or number proper */
1248 #ifndef NO_FLOATING_POINT
1249 if ((flags & FPT) == 0) {
1251 } else { /* glue together f_p fragments */
1252 if (!expchar) { /* %[fF] or sufficiently short %[gG] */
1255 if (prec || flags & ALT)
1256 PRINT(decimal_point, 1);
1258 /* already handled initial 0's */
1261 PRINTANDPAD(cp, convbuf + ndig, lead, zeroes);
1264 while (nseps>0 || nrepeats>0) {
1271 PRINT(&thousands_sep,
1278 if (cp > convbuf + ndig)
1279 cp = convbuf + ndig;
1281 if (prec || flags & ALT) {
1282 buf[0] = *decimal_point;
1286 PRINTANDPAD(cp, convbuf + ndig, prec, zeroes);
1287 } else { /* %[eE] or sufficiently long %[gG] */
1288 if (prec > 1 || flags & ALT) {
1290 buf[1] = *decimal_point;
1293 PAD(prec - ndig, zeroes);
1296 PRINT(expstr, expsize);
1302 /* left-adjusting padding (always blank) */
1303 if (flags & LADJUST)
1304 PAD(width - realsz, blanks);
1306 /* finally, adjust ret */
1311 #ifndef NO_FLOATING_POINT
1312 if (dtoaresult != NULL)
1316 if (convbuf != NULL)
1320 if ((argtable != NULL) && (argtable != statargtable))
1327 * Find all arguments when a positional parameter is encountered. Returns a
1328 * table, indexed by argument number, of pointers to each arguments. The
1329 * initial argument table should be an array of STATIC_ARG_TBL_SIZE entries.
1330 * It will be replaces with a malloc-ed one if it overflows.
1333 __find_arguments (const wchar_t *fmt0, va_list ap, union arg **argtable)
1335 wchar_t *fmt; /* format string */
1336 wchar_t ch; /* character from fmt */
1337 int n, n2; /* handy integer (short term usage) */
1338 wchar_t *cp; /* handy char pointer (short term usage) */
1339 int flags; /* flags as above */
1340 enum typeid *typetable; /* table of types */
1341 enum typeid stattypetable [STATIC_ARG_TBL_SIZE];
1342 int tablesize; /* current size of type table */
1343 int tablemax; /* largest used index in table */
1344 int nextarg; /* 1-based argument index */
1347 * Add an argument type to the table, expanding if necessary.
1349 #define ADDTYPE(type) \
1350 /*LINTED null effect*/ \
1351 (void)((nextarg >= tablesize) ? \
1352 __grow_type_table(nextarg, &typetable, &tablesize) : (void)0, \
1353 (nextarg > tablemax) ? tablemax = nextarg : 0, \
1354 typetable[nextarg++] = type)
1357 (void)((flags&INTMAXT) ? ADDTYPE(T_INTMAXT) : \
1358 ((flags&SIZET) ? ADDTYPE(T_SIZET) : \
1359 ((flags&PTRDIFFT) ? ADDTYPE(T_PTRDIFFT) : \
1360 ((flags&LLONGINT) ? ADDTYPE(T_LLONG) : \
1361 ((flags&LONGINT) ? ADDTYPE(T_LONG) : ADDTYPE(T_INT))))))
1364 (void)((flags&INTMAXT) ? ADDTYPE(T_UINTMAXT) : \
1365 ((flags&SIZET) ? ADDTYPE(T_SIZET) : \
1366 ((flags&PTRDIFFT) ? ADDTYPE(T_PTRDIFFT) : \
1367 ((flags&LLONGINT) ? ADDTYPE(T_U_LLONG) : \
1368 ((flags&LONGINT) ? ADDTYPE(T_U_LONG) : ADDTYPE(T_U_INT))))))
1371 * Add * arguments to the type array.
1373 #define ADDASTER() \
1376 while (is_digit(*cp)) { \
1377 n2 = 10 * n2 + to_digit(*cp); \
1381 int hold = nextarg; \
1389 fmt = __DECONST(wchar_t *, fmt0);
1390 typetable = stattypetable;
1391 tablesize = STATIC_ARG_TBL_SIZE;
1394 for (n = 0; n < STATIC_ARG_TBL_SIZE; n++)
1395 typetable[n] = T_UNUSED;
1398 * Scan the format for conversions (`%' character).
1401 for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
1405 fmt++; /* skip over '%' */
1410 reswitch: switch (ch) {
1422 if ((ch = *fmt++) == '*') {
1426 while (is_digit(ch)) {
1432 case '1': case '2': case '3': case '4':
1433 case '5': case '6': case '7': case '8': case '9':
1436 n = 10 * n + to_digit(ch);
1438 } while (is_digit(ch));
1444 #ifndef NO_FLOATING_POINT
1450 if (flags & SHORTINT) {
1460 if (flags & LONGINT) {
1467 flags |= LLONGINT; /* not necessarily */
1479 if (flags & LONGINT)
1491 #ifndef NO_FLOATING_POINT
1499 if (flags & LONGDBL)
1500 ADDTYPE(T_LONG_DOUBLE);
1504 #endif /* !NO_FLOATING_POINT */
1506 if (flags & INTMAXT)
1507 ADDTYPE(TP_INTMAXT);
1508 else if (flags & PTRDIFFT)
1509 ADDTYPE(TP_PTRDIFFT);
1510 else if (flags & SIZET)
1512 else if (flags & LLONGINT)
1514 else if (flags & LONGINT)
1516 else if (flags & SHORTINT)
1518 else if (flags & CHARINT)
1522 continue; /* no output */
1536 if (flags & LONGINT)
1549 default: /* "%?" prints ?, unless ? is NUL */
1557 * Build the argument table.
1559 if (tablemax >= STATIC_ARG_TBL_SIZE) {
1560 *argtable = (union arg *)
1561 malloc (sizeof (union arg) * (tablemax + 1));
1564 (*argtable) [0].intarg = 0;
1565 for (n = 1; n <= tablemax; n++) {
1566 switch (typetable [n]) {
1567 case T_UNUSED: /* whoops! */
1568 (*argtable) [n].intarg = va_arg (ap, int);
1571 (*argtable) [n].pschararg = va_arg (ap, signed char *);
1574 (*argtable) [n].pshortarg = va_arg (ap, short *);
1577 (*argtable) [n].intarg = va_arg (ap, int);
1580 (*argtable) [n].uintarg = va_arg (ap, unsigned int);
1583 (*argtable) [n].pintarg = va_arg (ap, int *);
1586 (*argtable) [n].longarg = va_arg (ap, long);
1589 (*argtable) [n].ulongarg = va_arg (ap, unsigned long);
1592 (*argtable) [n].plongarg = va_arg (ap, long *);
1595 (*argtable) [n].longlongarg = va_arg (ap, quad_t);
1598 (*argtable) [n].ulonglongarg = va_arg (ap, u_quad_t);
1601 (*argtable) [n].plonglongarg = va_arg (ap, quad_t *);
1604 (*argtable) [n].ptrdiffarg = va_arg (ap, ptrdiff_t);
1607 (*argtable) [n].pptrdiffarg = va_arg (ap, ptrdiff_t *);
1610 (*argtable) [n].sizearg = va_arg (ap, size_t);
1613 (*argtable) [n].psizearg = va_arg (ap, size_t *);
1616 (*argtable) [n].intmaxarg = va_arg (ap, intmax_t);
1619 (*argtable) [n].uintmaxarg = va_arg (ap, uintmax_t);
1622 (*argtable) [n].pintmaxarg = va_arg (ap, intmax_t *);
1624 #ifndef NO_FLOATING_POINT
1626 (*argtable) [n].doublearg = va_arg (ap, double);
1629 (*argtable) [n].longdoublearg = va_arg (ap, long double);
1633 (*argtable) [n].pchararg = va_arg (ap, char *);
1636 (*argtable) [n].pvoidarg = va_arg (ap, void *);
1639 (*argtable) [n].wintarg = va_arg (ap, wint_t);
1642 (*argtable) [n].pwchararg = va_arg (ap, wchar_t *);
1647 if ((typetable != NULL) && (typetable != stattypetable))
1652 * Increase the size of the type table.
1655 __grow_type_table (int nextarg, enum typeid **typetable, int *tablesize)
1657 enum typeid *const oldtable = *typetable;
1658 const int oldsize = *tablesize;
1659 enum typeid *newtable;
1660 int n, newsize = oldsize * 2;
1662 if (newsize < nextarg + 1)
1663 newsize = nextarg + 1;
1664 if (oldsize == STATIC_ARG_TBL_SIZE) {
1665 if ((newtable = malloc(newsize * sizeof(enum typeid))) == NULL)
1666 abort(); /* XXX handle better */
1667 bcopy(oldtable, newtable, oldsize * sizeof(enum typeid));
1669 newtable = realloc(oldtable, newsize * sizeof(enum typeid));
1670 if (newtable == NULL)
1671 abort(); /* XXX handle better */
1673 for (n = oldsize; n < newsize; n++)
1674 newtable[n] = T_UNUSED;
1676 *typetable = newtable;
1677 *tablesize = newsize;
1681 #ifndef NO_FLOATING_POINT
1682 extern char *__dtoa (double, int, int, int *, int *, char **, char **);
1685 cvt(double value, int ndigits, int flags, char *sign, int *decpt, int ch,
1686 int *length, char **dtoaresult)
1689 char *digits, *bp, *rve;
1690 static wchar_t buf[512];
1692 _DIAGASSERT(decpt != NULL);
1693 _DIAGASSERT(length != NULL);
1694 _DIAGASSERT(sign != NULL);
1697 mode = 3; /* ndigits after the decimal point */
1699 /* To obtain ndigits after the decimal point for the 'e'
1700 * and 'E' formats, round to ndigits + 1 significant
1703 if (ch == 'e' || ch == 'E') {
1706 mode = 2; /* ndigits significant digits */
1709 digits = __dtoa(value, mode, ndigits, decpt, &dsgn, &rve, dtoaresult);
1715 if ((ch != 'g' && ch != 'G') || flags & ALT) { /* Print trailing zeros */
1716 bp = digits + ndigits;
1718 if (*digits == '0' && value)
1719 *decpt = -ndigits + 1;
1722 if (value == 0) /* kludge for __dtoa irregularity */
1727 *length = rve - digits;
1728 mbstowcs(buf, digits, sizeof(buf)/sizeof(buf[0]));
1732 exponent(wchar_t *p0, int expo, wchar_t fmtch)
1735 wchar_t expbuf[MAXEXPDIG];
1745 t = expbuf + MAXEXPDIG;
1748 *--t = to_char(expo % 10);
1749 } while ((expo /= 10) > 9);
1750 *--t = to_char(expo);
1751 for (; t < expbuf + MAXEXPDIG; *p++ = *t++);
1755 * Exponents for decimal floating point conversions
1756 * (%[eEgG]) must be at least two characters long,
1757 * whereas exponents for hexadecimal conversions can
1758 * be only one character long.
1760 if (fmtch == 'e' || fmtch == 'E')
1762 *p++ = to_char(expo);
1766 #endif /* !NO_FLOATING_POINT */