1 /* $Id: snprintf.c,v 1.1 2009/04/10 13:39:23 broeker Exp $ */
4 * Copyright (c) 1995 Patrick Powell.
6 * This code is based on code written by Patrick Powell <papowell@astart.com>.
7 * It may be used for any purpose as long as this notice remains intact on all
8 * source code distributions.
12 * Copyright (c) 2008 Holger Weiss.
14 * This version of the code is maintained by Holger Weiss <holger@jhweiss.de>.
15 * My changes to the code may freely be used, modified and/or redistributed for
16 * any purpose. It would be nice if additions and fixes to this file (including
17 * trivial code cleanups) would be sent back in order to let me include them in
18 * the version available at <http://www.jhweiss.de/software/snprintf.html>.
19 * However, this is not a requirement for using or redistributing (possibly
20 * modified) versions of this file, nor is leaving this notice intact mandatory.
26 * 2008-01-20 Holger Weiss <holger@jhweiss.de> for C99-snprintf 1.1:
28 * Fixed the detection of infinite floating point values on IRIX (and
29 * possibly other systems) and applied another few minor cleanups.
31 * 2008-01-06 Holger Weiss <holger@jhweiss.de> for C99-snprintf 1.0:
33 * Added a lot of new features, fixed many bugs, and incorporated various
34 * improvements done by Andrew Tridgell <tridge@samba.org>, Russ Allbery
35 * <rra@stanford.edu>, Hrvoje Niksic <hniksic@xemacs.org>, Damien Miller
36 * <djm@mindrot.org>, and others for the Samba, INN, Wget, and OpenSSH
37 * projects. The additions include: support the "e", "E", "g", "G", and
38 * "F" conversion specifiers (and use conversion style "f" or "F" for the
39 * still unsupported "a" and "A" specifiers); support the "hh", "ll", "j",
40 * "t", and "z" length modifiers; support the "#" flag and the (non-C99)
41 * "'" flag; use localeconv(3) (if available) to get both the current
42 * locale's decimal point character and the separator between groups of
43 * digits; fix the handling of various corner cases of field width and
44 * precision specifications; fix various floating point conversion bugs;
45 * handle infinite and NaN floating point values; don't attempt to write to
46 * the output buffer (which may be NULL) if a size of zero was specified;
47 * check for integer overflow of the field width, precision, and return
48 * values and during the floating point conversion; use the OUTCHAR() macro
49 * instead of a function for better performance; provide asprintf(3) and
50 * vasprintf(3) functions; add new test cases. The replacement functions
51 * have been renamed to use an "rpl_" prefix, the function calls in the
52 * main project (and in this file) must be redefined accordingly for each
53 * replacement function which is needed (by using Autoconf or other means).
54 * Various other minor improvements have been applied and the coding style
55 * was cleaned up for consistency.
57 * 2007-07-23 Holger Weiss <holger@jhweiss.de> for Mutt 1.5.13:
59 * C99 compliant snprintf(3) and vsnprintf(3) functions return the number
60 * of characters that would have been written to a sufficiently sized
61 * buffer (excluding the '\0'). The original code simply returned the
62 * length of the resulting output string, so that's been fixed.
64 * 1998-03-05 Michael Elkins <me@mutt.org> for Mutt 0.90.8:
66 * The original code assumed that both snprintf(3) and vsnprintf(3) were
67 * missing. Some systems only have snprintf(3) but not vsnprintf(3), so
68 * the code is now broken down under HAVE_SNPRINTF and HAVE_VSNPRINTF.
70 * 1998-01-27 Thomas Roessler <roessler@does-not-exist.org> for Mutt 0.89i:
72 * The PGP code was using unsigned hexadecimal formats. Unfortunately,
73 * unsigned formats simply didn't work.
75 * 1997-10-22 Brandon Long <blong@fiction.net> for Mutt 0.87.1:
77 * Ok, added some minimal floating point support, which means this probably
78 * requires libm on most operating systems. Don't yet support the exponent
79 * (e,E) and sigfig (g,G). Also, fmtint() was pretty badly broken, it just
80 * wasn't being exercised in ways which showed it, so that's been fixed.
81 * Also, formatted the code to Mutt conventions, and removed dead code left
82 * over from the original. Also, there is now a builtin-test, run with:
83 * gcc -DTEST_SNPRINTF -o snprintf snprintf.c -lm && ./snprintf
85 * 2996-09-15 Brandon Long <blong@fiction.net> for Mutt 0.43:
87 * This was ugly. It is still ugly. I opted out of floating point
88 * numbers, but the formatter understands just about everything from the
89 * normal C string format, at least as far as I can tell from the Solaris
90 * 2.5 printf(3S) man page.
96 * - Add wide character support.
97 * - Add support for "%a" and "%A" conversions.
98 * - Create test routines which predefine the expected results. Our test cases
99 * usually expose bugs in system implementations rather than in ours :-)
105 * 1) The following preprocessor macros should be defined to 1 if the feature or
106 * file in question is available on the target system (by using Autoconf or
107 * other means), though basic functionality should be available as long as
108 * HAVE_STDARG_H and HAVE_STDLIB_H are defined correctly:
121 * HAVE_LCONV_DECIMAL_POINT
122 * HAVE_LCONV_THOUSANDS_SEP
125 * HAVE_UNSIGNED_LONG_LONG_INT
133 * 2) The calls to the functions which should be replaced must be redefined
134 * throughout the project files (by using Autoconf or other means):
136 * #define vsnprintf rpl_vsnprintf
137 * #define snprintf rpl_snprintf
138 * #define vasprintf rpl_vasprintf
139 * #define asprintf rpl_asprintf
141 * 3) The required replacement functions should be declared in some header file
142 * included throughout the project files:
145 * #include <config.h>
148 * #include <stdarg.h>
149 * #if !HAVE_VSNPRINTF
150 * int rpl_vsnprintf(char *, size_t, const char *, va_list);
153 * int rpl_snprintf(char *, size_t, const char *, ...);
155 * #if !HAVE_VASPRINTF
156 * int rpl_vasprintf(char **, const char *, va_list);
159 * int rpl_asprintf(char **, const char *, ...);
163 * Autoconf macros for handling step 1 and step 2 are available at
164 * <http://www.jhweiss.de/software/snprintf.html>.
169 #endif /* HAVE_CONFIG_H */
172 #include <math.h> /* For pow(3), NAN, and INFINITY. */
173 #include <string.h> /* For strcmp(3). */
174 #if defined(__NetBSD__) || \
175 defined(__FreeBSD__) || \
176 defined(__OpenBSD__) || \
177 defined(__NeXT__) || \
180 #elif defined(sgi) || defined(__sgi)
182 #define __c99 /* Force C99 mode to get <stdint.h> included on IRIX 6.5.30. */
183 #endif /* !defined(__c99) */
186 #elif defined(__svr4__)
188 #elif defined(__linux__)
190 #endif /* defined(__NetBSD__) || defined(__FreeBSD__) || [...] */
191 #if HAVE_CONFIG_H /* Undefine definitions possibly done in config.h. */
194 #endif /* defined(HAVE_SNPRINTF) */
195 #ifdef HAVE_VSNPRINTF
196 #undef HAVE_VSNPRINTF
197 #endif /* defined(HAVE_VSNPRINTF) */
200 #endif /* defined(HAVE_ASPRINTF) */
201 #ifdef HAVE_VASPRINTF
202 #undef HAVE_VASPRINTF
203 #endif /* defined(HAVE_VASPRINTF) */
206 #endif /* defined(snprintf) */
209 #endif /* defined(vsnprintf) */
212 #endif /* defined(asprintf) */
215 #endif /* defined(vasprintf) */
216 #else /* By default, we assume a modern system for testing. */
217 #ifndef HAVE_STDARG_H
218 #define HAVE_STDARG_H 1
219 #endif /* HAVE_STDARG_H */
220 #ifndef HAVE_STDDEF_H
221 #define HAVE_STDDEF_H 1
222 #endif /* HAVE_STDDEF_H */
223 #ifndef HAVE_STDINT_H
224 #define HAVE_STDINT_H 1
225 #endif /* HAVE_STDINT_H */
226 #ifndef HAVE_STDLIB_H
227 #define HAVE_STDLIB_H 1
228 #endif /* HAVE_STDLIB_H */
229 #ifndef HAVE_INTTYPES_H
230 #define HAVE_INTTYPES_H 1
231 #endif /* HAVE_INTTYPES_H */
232 #ifndef HAVE_LOCALE_H
233 #define HAVE_LOCALE_H 1
234 #endif /* HAVE_LOCALE_H */
235 #ifndef HAVE_LOCALECONV
236 #define HAVE_LOCALECONV 1
237 #endif /* !defined(HAVE_LOCALECONV) */
238 #ifndef HAVE_LCONV_DECIMAL_POINT
239 #define HAVE_LCONV_DECIMAL_POINT 1
240 #endif /* HAVE_LCONV_DECIMAL_POINT */
241 #ifndef HAVE_LCONV_THOUSANDS_SEP
242 #define HAVE_LCONV_THOUSANDS_SEP 1
243 #endif /* HAVE_LCONV_THOUSANDS_SEP */
244 #ifndef HAVE_LONG_DOUBLE
245 #define HAVE_LONG_DOUBLE 1
246 #endif /* !defined(HAVE_LONG_DOUBLE) */
247 #ifndef HAVE_LONG_LONG_INT
248 #define HAVE_LONG_LONG_INT 1
249 #endif /* !defined(HAVE_LONG_LONG_INT) */
250 #ifndef HAVE_UNSIGNED_LONG_LONG_INT
251 #define HAVE_UNSIGNED_LONG_LONG_INT 1
252 #endif /* !defined(HAVE_UNSIGNED_LONG_LONG_INT) */
253 #ifndef HAVE_INTMAX_T
254 #define HAVE_INTMAX_T 1
255 #endif /* !defined(HAVE_INTMAX_T) */
256 #ifndef HAVE_UINTMAX_T
257 #define HAVE_UINTMAX_T 1
258 #endif /* !defined(HAVE_UINTMAX_T) */
259 #ifndef HAVE_UINTPTR_T
260 #define HAVE_UINTPTR_T 1
261 #endif /* !defined(HAVE_UINTPTR_T) */
262 #ifndef HAVE_PTRDIFF_T
263 #define HAVE_PTRDIFF_T 1
264 #endif /* !defined(HAVE_PTRDIFF_T) */
266 #define HAVE_VA_COPY 1
267 #endif /* !defined(HAVE_VA_COPY) */
268 #ifndef HAVE___VA_COPY
269 #define HAVE___VA_COPY 1
270 #endif /* !defined(HAVE___VA_COPY) */
271 #endif /* HAVE_CONFIG_H */
272 #define snprintf rpl_snprintf
273 #define vsnprintf rpl_vsnprintf
274 #define asprintf rpl_asprintf
275 #define vasprintf rpl_vasprintf
276 #endif /* TEST_SNPRINTF */
278 #if !HAVE_SNPRINTF || !HAVE_VSNPRINTF || !HAVE_ASPRINTF || !HAVE_VASPRINTF
279 #include <stdio.h> /* For NULL, size_t, vsnprintf(3), and vasprintf(3). */
282 #endif /* defined(VA_START) */
285 #endif /* defined(VA_SHIFT) */
288 #define VA_START(ap, last) va_start(ap, last)
289 #define VA_SHIFT(ap, value, type) /* No-op for ANSI C. */
290 #else /* Assume <varargs.h> is available. */
292 #define VA_START(ap, last) va_start(ap) /* "last" is ignored. */
293 #define VA_SHIFT(ap, value, type) value = va_arg(ap, type)
294 #endif /* HAVE_STDARG_H */
298 #include <stdlib.h> /* For malloc(3). */
299 #endif /* HAVE_STDLIB_H */
302 #endif /* defined(VA_COPY) */
305 #endif /* defined(VA_END_COPY) */
307 #define VA_COPY(dest, src) va_copy(dest, src)
308 #define VA_END_COPY(ap) va_end(ap)
310 #define VA_COPY(dest, src) __va_copy(dest, src)
311 #define VA_END_COPY(ap) va_end(ap)
313 #define VA_COPY(dest, src) (void)mymemcpy(&dest, &src, sizeof(va_list))
314 #define VA_END_COPY(ap) /* No-op. */
315 #define NEED_MYMEMCPY 1
316 static void *mymemcpy(void *, void *, size_t);
317 #endif /* HAVE_VA_COPY */
318 #endif /* !HAVE_VASPRINTF */
321 #include <errno.h> /* For ERANGE and errno. */
322 #include <limits.h> /* For *_MAX. */
324 #include <inttypes.h> /* For intmax_t (if not defined in <stdint.h>). */
325 #endif /* HAVE_INTTYPES_H */
327 #include <locale.h> /* For localeconv(3). */
328 #endif /* HAVE_LOCALE_H */
330 #include <stddef.h> /* For ptrdiff_t. */
331 #endif /* HAVE_STDDEF_H */
333 #include <stdint.h> /* For intmax_t. */
334 #endif /* HAVE_STDINT_H */
336 /* Support for unsigned long long int. We may also need ULLONG_MAX. */
337 #ifndef ULONG_MAX /* We may need ULONG_MAX as a fallback. */
339 #define ULONG_MAX UINT_MAX
341 #define ULONG_MAX INT_MAX
342 #endif /* defined(UINT_MAX) */
343 #endif /* !defined(ULONG_MAX) */
346 #endif /* defined(ULLONG) */
347 #if HAVE_UNSIGNED_LONG_LONG_INT
348 #define ULLONG unsigned long long int
350 #define ULLONG_MAX ULONG_MAX
351 #endif /* !defined(ULLONG_MAX) */
353 #define ULLONG unsigned long int
356 #endif /* defined(ULLONG_MAX) */
357 #define ULLONG_MAX ULONG_MAX
358 #endif /* HAVE_LONG_LONG_INT */
360 /* Support for uintmax_t. We also need UINTMAX_MAX. */
363 #endif /* defined(UINTMAX_T) */
364 #if HAVE_UINTMAX_T || defined(uintmax_t)
365 #define UINTMAX_T uintmax_t
367 #define UINTMAX_MAX ULLONG_MAX
368 #endif /* !defined(UINTMAX_MAX) */
370 #define UINTMAX_T ULLONG
373 #endif /* defined(UINTMAX_MAX) */
374 #define UINTMAX_MAX ULLONG_MAX
375 #endif /* HAVE_UINTMAX_T || defined(uintmax_t) */
377 /* Support for long double. */
380 #define LDOUBLE long double
382 #define LDOUBLE double
383 #endif /* HAVE_LONG_DOUBLE */
384 #endif /* !defined(LDOUBLE) */
386 /* Support for long long int. */
388 #if HAVE_LONG_LONG_INT
389 #define LLONG long long int
391 #define LLONG long int
392 #endif /* HAVE_LONG_LONG_INT */
393 #endif /* !defined(LLONG) */
395 /* Support for intmax_t. */
397 #if HAVE_INTMAX_T || defined(intmax_t)
398 #define INTMAX_T intmax_t
400 #define INTMAX_T LLONG
401 #endif /* HAVE_INTMAX_T || defined(intmax_t) */
402 #endif /* !defined(INTMAX_T) */
404 /* Support for uintptr_t. */
406 #if HAVE_UINTPTR_T || defined(uintptr_t)
407 #define UINTPTR_T uintptr_t
409 #define UINTPTR_T unsigned long int
410 #endif /* HAVE_UINTPTR_T || defined(uintptr_t) */
411 #endif /* !defined(UINTPTR_T) */
413 /* Support for ptrdiff_t. */
415 #if HAVE_PTRDIFF_T || defined(ptrdiff_t)
416 #define PTRDIFF_T ptrdiff_t
418 #define PTRDIFF_T long int
419 #endif /* HAVE_PTRDIFF_T || defined(ptrdiff_t) */
420 #endif /* !defined(PTRDIFF_T) */
423 * We need an unsigned integer type corresponding to ptrdiff_t (cf. C99:
424 * 7.19.6.1, 7). However, we'll simply use PTRDIFF_T and convert it to an
425 * unsigned type if necessary. This should work just fine in practice.
428 #define UPTRDIFF_T PTRDIFF_T
429 #endif /* !defined(UPTRDIFF_T) */
432 * We need a signed integer type corresponding to size_t (cf. C99: 7.19.6.1, 7).
433 * However, we'll simply use size_t and convert it to a signed type if
434 * necessary. This should work just fine in practice.
437 #define SSIZE_T size_t
438 #endif /* !defined(SSIZE_T) */
440 /* Either ERANGE or E2BIG should be available everywhere. */
443 #endif /* !defined(ERANGE) */
445 #define EOVERFLOW ERANGE
446 #endif /* !defined(EOVERFLOW) */
449 * Buffer size to hold the octal string representation of UINT128_MAX without
450 * nul-termination ("3777777777777777777777777777777777777777777").
452 #ifdef MAX_CONVERT_LENGTH
453 #undef MAX_CONVERT_LENGTH
454 #endif /* defined(MAX_CONVERT_LENGTH) */
455 #define MAX_CONVERT_LENGTH 43
457 /* Format read states. */
458 #define PRINT_S_DEFAULT 0
459 #define PRINT_S_FLAGS 1
460 #define PRINT_S_WIDTH 2
461 #define PRINT_S_DOT 3
462 #define PRINT_S_PRECISION 4
463 #define PRINT_S_MOD 5
464 #define PRINT_S_CONV 6
467 #define PRINT_F_MINUS (1 << 0)
468 #define PRINT_F_PLUS (1 << 1)
469 #define PRINT_F_SPACE (1 << 2)
470 #define PRINT_F_NUM (1 << 3)
471 #define PRINT_F_ZERO (1 << 4)
472 #define PRINT_F_QUOTE (1 << 5)
473 #define PRINT_F_UP (1 << 6)
474 #define PRINT_F_UNSIGNED (1 << 7)
475 #define PRINT_F_TYPE_G (1 << 8)
476 #define PRINT_F_TYPE_E (1 << 9)
478 /* Conversion flags. */
479 #define PRINT_C_CHAR 1
480 #define PRINT_C_SHORT 2
481 #define PRINT_C_LONG 3
482 #define PRINT_C_LLONG 4
483 #define PRINT_C_LDOUBLE 5
484 #define PRINT_C_SIZE 6
485 #define PRINT_C_PTRDIFF 7
486 #define PRINT_C_INTMAX 8
489 #define MAX(x, y) ((x >= y) ? x : y)
490 #endif /* !defined(MAX) */
492 #define CHARTOINT(ch) (ch - '0')
493 #endif /* !defined(CHARTOINT) */
495 #define ISDIGIT(ch) ('0' <= (unsigned char)ch && (unsigned char)ch <= '9')
496 #endif /* !defined(ISDIGIT) */
498 #define ISNAN(x) (x != x)
499 #endif /* !defined(ISNAN) */
501 #define ISINF(x) (x != 0.0 && x + x == x)
502 #endif /* !defined(ISINF) */
506 #endif /* defined(OUTCHAR) */
507 #define OUTCHAR(str, len, size, ch) \
509 if (len + 1 < size) \
512 } while (/* CONSTCOND */ 0)
514 static void fmtstr(char *, size_t *, size_t, const char *, int, int, int);
515 static void fmtint(char *, size_t *, size_t, INTMAX_T, int, int, int, int);
516 static void fmtflt(char *, size_t *, size_t, LDOUBLE, int, int, int, int *);
517 static void printsep(char *, size_t *, size_t);
518 static int getnumsep(int);
519 static int getexponent(LDOUBLE);
520 static int convert(UINTMAX_T, char *, size_t, int, int);
521 static UINTMAX_T cast(LDOUBLE);
522 static UINTMAX_T myround(LDOUBLE);
523 static LDOUBLE mypow10(int);
528 rpl_vsnprintf(char *str, size_t size, const char *format, va_list args)
532 unsigned char cvalue;
533 const char *strvalue;
535 PTRDIFF_T *ptrdiffptr;
541 signed char *charptr;
549 int state = PRINT_S_DEFAULT;
553 * C99 says: "If `n' is zero, nothing is written, and `s' may be a null
554 * pointer." (7.19.6.5, 2) We're forgiving and allow a NULL pointer
555 * even if a size larger than zero was specified. At least NetBSD's
556 * snprintf(3) does the same, as well as other versions of this file.
557 * (Though some of these versions will write to a non-NULL buffer even
558 * if a size of zero was specified, which violates the standard.)
560 if (str == NULL && size != 0)
565 case PRINT_S_DEFAULT:
567 state = PRINT_S_FLAGS;
569 OUTCHAR(str, len, size, ch);
575 flags |= PRINT_F_MINUS;
579 flags |= PRINT_F_PLUS;
583 flags |= PRINT_F_SPACE;
587 flags |= PRINT_F_NUM;
591 flags |= PRINT_F_ZERO;
594 case '\'': /* SUSv2 flag (not in C99). */
595 flags |= PRINT_F_QUOTE;
599 state = PRINT_S_WIDTH;
606 if (width > (INT_MAX - ch) / 10) {
610 width = 10 * width + ch;
612 } else if (ch == '*') {
614 * C99 says: "A negative field width argument is
615 * taken as a `-' flag followed by a positive
616 * field width." (7.19.6.1, 5)
618 if ((width = va_arg(args, int)) < 0) {
619 flags |= PRINT_F_MINUS;
629 state = PRINT_S_PRECISION;
634 case PRINT_S_PRECISION:
639 if (precision > (INT_MAX - ch) / 10) {
643 precision = 10 * precision + ch;
645 } else if (ch == '*') {
647 * C99 says: "A negative precision argument is
648 * taken as if the precision were omitted."
651 if ((precision = va_arg(args, int)) < 0)
662 if (ch == 'h') { /* It's a char. */
664 cflags = PRINT_C_CHAR;
666 cflags = PRINT_C_SHORT;
670 if (ch == 'l') { /* It's a long long. */
672 cflags = PRINT_C_LLONG;
674 cflags = PRINT_C_LONG;
677 cflags = PRINT_C_LDOUBLE;
681 cflags = PRINT_C_INTMAX;
685 cflags = PRINT_C_PTRDIFF;
689 cflags = PRINT_C_SIZE;
693 state = PRINT_S_CONV;
702 value = (signed char)va_arg(args, int);
705 value = (short int)va_arg(args, int);
708 value = va_arg(args, long int);
711 value = va_arg(args, LLONG);
714 value = va_arg(args, SSIZE_T);
717 value = va_arg(args, INTMAX_T);
719 case PRINT_C_PTRDIFF:
720 value = va_arg(args, PTRDIFF_T);
723 value = va_arg(args, int);
726 fmtint(str, &len, size, value, 10, width,
742 flags |= PRINT_F_UNSIGNED;
745 value = (unsigned char)va_arg(args,
749 value = (unsigned short int)va_arg(args,
753 value = va_arg(args, unsigned long int);
756 value = va_arg(args, ULLONG);
759 value = va_arg(args, size_t);
762 value = va_arg(args, UINTMAX_T);
764 case PRINT_C_PTRDIFF:
765 value = va_arg(args, UPTRDIFF_T);
768 value = va_arg(args, unsigned int);
771 fmtint(str, &len, size, value, base, width,
775 /* Not yet supported, we'll use "%F". */
780 /* Not yet supported, we'll use "%f". */
783 if (cflags == PRINT_C_LDOUBLE)
784 fvalue = va_arg(args, LDOUBLE);
786 fvalue = va_arg(args, double);
787 fmtflt(str, &len, size, fvalue, width,
788 precision, flags, &overflow);
796 flags |= PRINT_F_TYPE_E;
797 if (cflags == PRINT_C_LDOUBLE)
798 fvalue = va_arg(args, LDOUBLE);
800 fvalue = va_arg(args, double);
801 fmtflt(str, &len, size, fvalue, width,
802 precision, flags, &overflow);
810 flags |= PRINT_F_TYPE_G;
811 if (cflags == PRINT_C_LDOUBLE)
812 fvalue = va_arg(args, LDOUBLE);
814 fvalue = va_arg(args, double);
816 * If the precision is zero, it is treated as
817 * one (cf. C99: 7.19.6.1, 8).
821 fmtflt(str, &len, size, fvalue, width,
822 precision, flags, &overflow);
827 cvalue = va_arg(args, int);
828 OUTCHAR(str, len, size, cvalue);
831 strvalue = va_arg(args, char *);
832 fmtstr(str, &len, size, strvalue, width,
837 * C99 says: "The value of the pointer is
838 * converted to a sequence of printing
839 * characters, in an implementation-defined
840 * manner." (C99: 7.19.6.1, 8)
842 if ((strvalue = va_arg(args, void *)) == NULL)
844 * We use the glibc format. BSD prints
847 fmtstr(str, &len, size, "(nil)", width,
851 * We use the BSD/glibc format. SysV
852 * omits the "0x" prefix (which we emit
853 * using the PRINT_F_NUM flag).
855 flags |= PRINT_F_NUM;
856 flags |= PRINT_F_UNSIGNED;
857 fmtint(str, &len, size,
858 (UINTPTR_T)strvalue, 16, width,
865 charptr = va_arg(args, signed char *);
869 shortptr = va_arg(args, short int *);
873 longptr = va_arg(args, long int *);
877 llongptr = va_arg(args, LLONG *);
882 * C99 says that with the "z" length
883 * modifier, "a following `n' conversion
884 * specifier applies to a pointer to a
885 * signed integer type corresponding to
886 * size_t argument." (7.19.6.1, 7)
888 sizeptr = va_arg(args, SSIZE_T *);
892 intmaxptr = va_arg(args, INTMAX_T *);
895 case PRINT_C_PTRDIFF:
896 ptrdiffptr = va_arg(args, PTRDIFF_T *);
900 intptr = va_arg(args, int *);
905 case '%': /* Print a "%" character verbatim. */
906 OUTCHAR(str, len, size, ch);
908 default: /* Skip other characters. */
912 state = PRINT_S_DEFAULT;
913 base = cflags = flags = width = 0;
921 str[size - 1] = '\0';
923 if (overflow || len >= INT_MAX) {
924 errno = overflow ? EOVERFLOW : ERANGE;
931 fmtstr(char *str, size_t *len, size_t size, const char *value, int width,
932 int precision, int flags)
934 int padlen, strln; /* Amount to pad. */
935 int noprecision = (precision == -1);
937 if (value == NULL) /* We're forgiving. */
940 /* If a precision was specified, don't read the string past it. */
941 for (strln = 0; value[strln] != '\0' &&
942 (noprecision || strln < precision); strln++)
945 if ((padlen = width - strln) < 0)
947 if (flags & PRINT_F_MINUS) /* Left justify. */
950 while (padlen > 0) { /* Leading spaces. */
951 OUTCHAR(str, *len, size, ' ');
954 while (*value != '\0' && (noprecision || precision-- > 0)) {
955 OUTCHAR(str, *len, size, *value);
958 while (padlen < 0) { /* Trailing spaces. */
959 OUTCHAR(str, *len, size, ' ');
965 fmtint(char *str, size_t *len, size_t size, INTMAX_T value, int base, int width,
966 int precision, int flags)
969 char iconvert[MAX_CONVERT_LENGTH];
972 int spadlen = 0; /* Amount to space pad. */
973 int zpadlen = 0; /* Amount to zero pad. */
975 int separators = (flags & PRINT_F_QUOTE);
976 int noprecision = (precision == -1);
978 if (flags & PRINT_F_UNSIGNED)
981 uvalue = (value >= 0) ? value : -value;
984 else if (flags & PRINT_F_PLUS) /* Do a sign. */
986 else if (flags & PRINT_F_SPACE)
990 pos = convert(uvalue, iconvert, sizeof(iconvert), base,
993 if (flags & PRINT_F_NUM && uvalue != 0) {
995 * C99 says: "The result is converted to an `alternative form'.
996 * For `o' conversion, it increases the precision, if and only
997 * if necessary, to force the first digit of the result to be a
998 * zero (if the value and precision are both 0, a single 0 is
999 * printed). For `x' (or `X') conversion, a nonzero result has
1000 * `0x' (or `0X') prefixed to it." (7.19.6.1, 6)
1004 if (precision <= pos)
1005 precision = pos + 1;
1008 hexprefix = (flags & PRINT_F_UP) ? 'X' : 'x';
1013 if (separators) /* Get the number of group separators we'll print. */
1014 separators = getnumsep(pos);
1016 zpadlen = precision - pos - separators;
1017 spadlen = width /* Minimum field width. */
1018 - separators /* Number of separators. */
1019 - MAX(precision, pos) /* Number of integer digits. */
1020 - ((sign != 0) ? 1 : 0) /* Will we print a sign? */
1021 - ((hexprefix != 0) ? 2 : 0); /* Will we print a prefix? */
1029 * C99 says: "If the `0' and `-' flags both appear, the `0' flag is
1030 * ignored. For `d', `i', `o', `u', `x', and `X' conversions, if a
1031 * precision is specified, the `0' flag is ignored." (7.19.6.1, 6)
1033 if (flags & PRINT_F_MINUS) /* Left justify. */
1035 else if (flags & PRINT_F_ZERO && noprecision) {
1039 while (spadlen > 0) { /* Leading spaces. */
1040 OUTCHAR(str, *len, size, ' ');
1043 if (sign != 0) /* Sign. */
1044 OUTCHAR(str, *len, size, sign);
1045 if (hexprefix != 0) { /* A "0x" or "0X" prefix. */
1046 OUTCHAR(str, *len, size, '0');
1047 OUTCHAR(str, *len, size, hexprefix);
1049 while (zpadlen > 0) { /* Leading zeros. */
1050 OUTCHAR(str, *len, size, '0');
1053 while (pos > 0) { /* The actual digits. */
1055 OUTCHAR(str, *len, size, iconvert[pos]);
1056 if (separators > 0 && pos > 0 && pos % 3 == 0)
1057 printsep(str, len, size);
1059 while (spadlen < 0) { /* Trailing spaces. */
1060 OUTCHAR(str, *len, size, ' ');
1066 fmtflt(char *str, size_t *len, size_t size, LDOUBLE fvalue, int width,
1067 int precision, int flags, int *overflow)
1073 const char *infnan = NULL;
1074 char iconvert[MAX_CONVERT_LENGTH];
1075 char fconvert[MAX_CONVERT_LENGTH];
1076 char econvert[4]; /* "e-12" (without nul-termination). */
1079 int leadfraczeros = 0;
1088 int separators = (flags & PRINT_F_QUOTE);
1089 int estyle = (flags & PRINT_F_TYPE_E);
1090 #if HAVE_LOCALECONV && HAVE_LCONV_DECIMAL_POINT
1091 struct lconv *lc = localeconv();
1092 #endif /* HAVE_LOCALECONV && HAVE_LCONV_DECIMAL_POINT */
1095 * AIX' man page says the default is 0, but C99 and at least Solaris'
1096 * and NetBSD's man pages say the default is 6, and sprintf(3) on AIX
1099 if (precision == -1)
1104 else if (flags & PRINT_F_PLUS) /* Do a sign. */
1106 else if (flags & PRINT_F_SPACE)
1110 infnan = (flags & PRINT_F_UP) ? "NAN" : "nan";
1111 else if (ISINF(fvalue))
1112 infnan = (flags & PRINT_F_UP) ? "INF" : "inf";
1114 if (infnan != NULL) {
1116 iconvert[ipos++] = sign;
1117 while (*infnan != '\0')
1118 iconvert[ipos++] = *infnan++;
1119 fmtstr(str, len, size, iconvert, width, ipos, flags);
1123 /* "%e" (or "%E") or "%g" (or "%G") conversion. */
1124 if (flags & PRINT_F_TYPE_E || flags & PRINT_F_TYPE_G) {
1125 if (flags & PRINT_F_TYPE_G) {
1127 * For "%g" (and "%G") conversions, the precision
1128 * specifies the number of significant digits, which
1129 * includes the digits in the integer part. The
1130 * conversion will or will not be using "e-style" (like
1131 * "%e" or "%E" conversions) depending on the precision
1132 * and on the exponent. However, the exponent can be
1133 * affected by rounding the converted value, so we'll
1134 * leave this decision for later. Until then, we'll
1135 * assume that we're going to do an "e-style" conversion
1136 * (in order to get the exponent calculated). For
1137 * "e-style", the precision must be decremented by one.
1141 * For "%g" (and "%G") conversions, trailing zeros are
1142 * removed from the fractional portion of the result
1143 * unless the "#" flag was specified.
1145 if (!(flags & PRINT_F_NUM))
1148 exponent = getexponent(fvalue);
1154 * Sorry, we only support 9, 19, or 38 digits (that is, the number of
1155 * digits of the 32-bit, the 64-bit, or the 128-bit UINTMAX_MAX value
1156 * minus one) past the decimal point due to our conversion method.
1158 switch (sizeof(UINTMAX_T)) {
1173 ufvalue = (fvalue >= 0.0) ? fvalue : -fvalue;
1174 if (estyle) /* We want exactly one integer digit. */
1175 ufvalue /= mypow10(exponent);
1177 if ((intpart = cast(ufvalue)) == UINTMAX_MAX) {
1183 * Factor of ten with the number of digits needed for the fractional
1184 * part. For example, if the precision is 3, the mask will be 1000.
1186 mask = mypow10(precision);
1188 * We "cheat" by converting the fractional part to integer by
1189 * multiplying by a factor of ten.
1191 if ((fracpart = myround(mask * (ufvalue - intpart))) >= mask) {
1193 * For example, ufvalue = 2.99962, intpart = 2, and mask = 1000
1194 * (because precision = 3). Now, myround(1000 * 0.99962) will
1195 * return 1000. So, the integer part must be incremented by one
1196 * and the fractional part must be set to zero.
1200 if (estyle && intpart == 10) {
1202 * The value was rounded up to ten, but we only want one
1203 * integer digit if using "e-style". So, the integer
1204 * part must be set to one and the exponent must be
1205 * incremented by one.
1213 * Now that we know the real exponent, we can check whether or not to
1214 * use "e-style" for "%g" (and "%G") conversions. If we don't need
1215 * "e-style", the precision must be adjusted and the integer and
1216 * fractional parts must be recalculated from the original value.
1218 * C99 says: "Let P equal the precision if nonzero, 6 if the precision
1219 * is omitted, or 1 if the precision is zero. Then, if a conversion
1220 * with style `E' would have an exponent of X:
1222 * - if P > X >= -4, the conversion is with style `f' (or `F') and
1223 * precision P - (X + 1).
1225 * - otherwise, the conversion is with style `e' (or `E') and precision
1226 * P - 1." (7.19.6.1, 8)
1228 * Note that we had decremented the precision by one.
1230 if (flags & PRINT_F_TYPE_G && estyle &&
1231 precision + 1 > exponent && exponent >= -4) {
1232 precision -= exponent;
1239 exponent = -exponent;
1245 * Convert the exponent. The sizeof(econvert) is 4. So, the
1246 * econvert buffer can hold e.g. "e+99" and "e-99". We don't
1247 * support an exponent which contains more than two digits.
1248 * Therefore, the following stores are safe.
1250 epos = convert(exponent, econvert, 2, 10, 0);
1252 * C99 says: "The exponent always contains at least two digits,
1253 * and only as many more digits as necessary to represent the
1254 * exponent." (7.19.6.1, 8)
1257 econvert[epos++] = '0';
1258 econvert[epos++] = esign;
1259 econvert[epos++] = (flags & PRINT_F_UP) ? 'E' : 'e';
1262 /* Convert the integer part and the fractional part. */
1263 ipos = convert(intpart, iconvert, sizeof(iconvert), 10, 0);
1264 if (fracpart != 0) /* convert() would return 1 if fracpart == 0. */
1265 fpos = convert(fracpart, fconvert, sizeof(fconvert), 10, 0);
1267 leadfraczeros = precision - fpos;
1270 if (fpos > 0) /* Omit trailing fractional part zeros. */
1271 while (omitcount < fpos && fconvert[omitcount] == '0')
1273 else { /* The fractional part is zero, omit it completely. */
1274 omitcount = precision;
1277 precision -= omitcount;
1281 * Print a decimal point if either the fractional part is non-zero
1282 * and/or the "#" flag was specified.
1284 if (precision > 0 || flags & PRINT_F_NUM)
1286 if (separators) /* Get the number of group separators we'll print. */
1287 separators = getnumsep(ipos);
1289 padlen = width /* Minimum field width. */
1290 - ipos /* Number of integer digits. */
1291 - epos /* Number of exponent characters. */
1292 - precision /* Number of fractional digits. */
1293 - separators /* Number of group separators. */
1294 - (emitpoint ? 1 : 0) /* Will we print a decimal point? */
1295 - ((sign != 0) ? 1 : 0); /* Will we print a sign character? */
1301 * C99 says: "If the `0' and `-' flags both appear, the `0' flag is
1302 * ignored." (7.19.6.1, 6)
1304 if (flags & PRINT_F_MINUS) /* Left justifty. */
1306 else if (flags & PRINT_F_ZERO && padlen > 0) {
1307 if (sign != 0) { /* Sign. */
1308 OUTCHAR(str, *len, size, sign);
1311 while (padlen > 0) { /* Leading zeros. */
1312 OUTCHAR(str, *len, size, '0');
1316 while (padlen > 0) { /* Leading spaces. */
1317 OUTCHAR(str, *len, size, ' ');
1320 if (sign != 0) /* Sign. */
1321 OUTCHAR(str, *len, size, sign);
1322 while (ipos > 0) { /* Integer part. */
1324 OUTCHAR(str, *len, size, iconvert[ipos]);
1325 if (separators > 0 && ipos > 0 && ipos % 3 == 0)
1326 printsep(str, len, size);
1328 if (emitpoint) { /* Decimal point. */
1329 #if HAVE_LOCALECONV && HAVE_LCONV_DECIMAL_POINT
1330 if (lc->decimal_point != NULL && *lc->decimal_point != '\0')
1331 OUTCHAR(str, *len, size, *lc->decimal_point);
1332 else /* We'll always print some decimal point character. */
1333 #endif /* HAVE_LOCALECONV && HAVE_LCONV_DECIMAL_POINT */
1334 OUTCHAR(str, *len, size, '.');
1336 while (leadfraczeros > 0) { /* Leading fractional part zeros. */
1337 OUTCHAR(str, *len, size, '0');
1340 while (fpos > omitcount) { /* The remaining fractional part. */
1342 OUTCHAR(str, *len, size, fconvert[fpos]);
1344 while (epos > 0) { /* Exponent. */
1346 OUTCHAR(str, *len, size, econvert[epos]);
1348 while (padlen < 0) { /* Trailing spaces. */
1349 OUTCHAR(str, *len, size, ' ');
1355 printsep(char *str, size_t *len, size_t size)
1357 #if HAVE_LOCALECONV && HAVE_LCONV_THOUSANDS_SEP
1358 struct lconv *lc = localeconv();
1361 if (lc->thousands_sep != NULL)
1362 for (i = 0; lc->thousands_sep[i] != '\0'; i++)
1363 OUTCHAR(str, *len, size, lc->thousands_sep[i]);
1365 #endif /* HAVE_LOCALECONV && HAVE_LCONV_THOUSANDS_SEP */
1366 OUTCHAR(str, *len, size, ',');
1370 getnumsep(int digits)
1372 int separators = (digits - ((digits % 3 == 0) ? 1 : 0)) / 3;
1373 #if HAVE_LOCALECONV && HAVE_LCONV_THOUSANDS_SEP
1375 struct lconv *lc = localeconv();
1377 /* We support an arbitrary separator length (including zero). */
1378 if (lc->thousands_sep != NULL) {
1379 for (strln = 0; lc->thousands_sep[strln] != '\0'; strln++)
1381 separators *= strln;
1383 #endif /* HAVE_LOCALECONV && HAVE_LCONV_THOUSANDS_SEP */
1388 getexponent(LDOUBLE value)
1390 LDOUBLE tmp = (value >= 0.0) ? value : -value;
1394 * We check for 99 > exponent > -99 in order to work around possible
1395 * endless loops which could happen (at least) in the second loop (at
1396 * least) if we're called with an infinite value. However, we checked
1397 * for infinity before calling this function using our ISINF() macro, so
1398 * this might be somewhat paranoid.
1400 while (tmp < 1.0 && tmp > 0.0 && --exponent > -99)
1402 while (tmp >= 10.0 && ++exponent < 99)
1409 convert(UINTMAX_T value, char *buf, size_t size, int base, int caps)
1411 const char *digits = caps ? "0123456789ABCDEF" : "0123456789abcdef";
1414 /* We return an unterminated buffer with the digits in reverse order. */
1416 buf[pos++] = digits[value % base];
1418 } while (value != 0 && pos < size);
1429 * We check for ">=" and not for ">" because if UINTMAX_MAX cannot be
1430 * represented exactly as an LDOUBLE value (but is less than LDBL_MAX),
1431 * it may be increased to the nearest higher representable value for the
1432 * comparison (cf. C99: 6.3.1.4, 2). It might then equal the LDOUBLE
1433 * value although converting the latter to UINTMAX_T would overflow.
1435 if (value >= UINTMAX_MAX)
1440 * At least on NetBSD/sparc64 3.0.2 and 4.99.30, casting long double to
1441 * an integer type converts e.g. 1.9 to 2 instead of 1 (which violates
1442 * the standard). Sigh.
1444 return (result <= value) ? result : result - 1;
1448 myround(LDOUBLE value)
1450 UINTMAX_T intpart = cast(value);
1452 return ((value -= intpart) < 0.5) ? intpart : intpart + 1;
1456 mypow10(int exponent)
1460 while (exponent > 0) {
1464 while (exponent < 0) {
1470 #endif /* !HAVE_VSNPRINTF */
1475 mymemcpy(void *dst, void *src, size_t len)
1477 const char *from = src;
1480 /* No need for optimization, we use this only to replace va_copy(3). */
1485 #endif /* NEED_MYMEMCPY */
1488 rpl_vasprintf(char **ret, const char *format, va_list ap)
1495 len = vsnprintf(NULL, 0, format, aq);
1497 if (len < 0 || (*ret = malloc(size = len + 1)) == NULL)
1499 return vsnprintf(*ret, size, format, ap);
1501 #endif /* !HAVE_VASPRINTF */
1506 rpl_snprintf(char *str, size_t size, const char *format, ...)
1509 rpl_snprintf(va_alist) va_dcl
1510 #endif /* HAVE_STDARG_H */
1516 #endif /* HAVE_STDARG_H */
1520 VA_START(ap, format);
1521 VA_SHIFT(ap, str, char *);
1522 VA_SHIFT(ap, size, size_t);
1523 VA_SHIFT(ap, format, const char *);
1524 len = vsnprintf(str, size, format, ap);
1528 #endif /* !HAVE_SNPRINTF */
1533 rpl_asprintf(char **ret, const char *format, ...)
1536 rpl_asprintf(va_alist) va_dcl
1537 #endif /* HAVE_STDARG_H */
1542 #endif /* HAVE_STDARG_H */
1546 VA_START(ap, format);
1547 VA_SHIFT(ap, ret, char **);
1548 VA_SHIFT(ap, format, const char *);
1549 len = vasprintf(ret, format, ap);
1553 #endif /* !HAVE_ASPRINTF */
1554 #else /* Dummy declaration to avoid empty translation unit warnings. */
1556 #endif /* !HAVE_SNPRINTF || !HAVE_VSNPRINTF || !HAVE_ASPRINTF || [...] */
1562 const char *float_fmt[] = {
1563 /* "%E" and "%e" formats. */
1564 #if HAVE_LONG_LONG_INT && !OS_BSD && !OS_IRIX
1570 #endif /* HAVE_LONG_LONG_INT && !OS_BSD && !OS_IRIX */
1571 "foo|%#+0123.9E|bar",
1583 #if !OS_LINUX /* glibc sometimes gets these wrong. */
1610 #endif /* !OS_LINUX */
1611 /* "%F" and "%f" formats. */
1612 #if !OS_BSD && !OS_IRIX
1617 #if HAVE_LONG_LONG_INT
1623 #endif /* HAVE_LONG_LONG_INT */
1624 #endif /* !OS_BSD && !OS_IRIX */
1625 "foo|%#+0123.9F|bar",
1663 /* "%G" and "%g" formats. */
1664 #if !OS_BSD && !OS_IRIX && !OS_LINUX
1669 #if HAVE_LONG_LONG_INT
1675 #endif /* HAVE_LONG_LONG_INT */
1676 #endif /* !OS_BSD && !OS_IRIX && !OS_LINUX */
1677 "foo|%#+0123.9G|bar",
1689 #if !OS_LINUX /* glibc sometimes gets these wrong. */
1716 #endif /* !OS_LINUX */
1719 double float_val[] = {
1775 #if !OS_BSD /* BSD sometimes gets these wrong. */
1779 #endif /* defined(INFINITY) */
1782 #endif /* defined(NAN) */
1783 #endif /* !OS_BSD */
1786 const char *long_fmt[] = {
1793 #endif /* !OS_IRiX */
1834 long int long_val[] = {
1837 #endif /* LONG_MAX */
1840 #endif /* LONG_MIN */
1850 const char *ulong_fmt[] = {
1858 #endif /* !OS_IRiX */
1906 /* "%X" and "%x" formats. */
1942 unsigned long int ulong_val[] = {
1945 #endif /* ULONG_MAX */
1953 const char *llong_fmt[] = {
1972 LLONG llong_val[] = {
1975 #endif /* LLONG_MAX */
1978 #endif /* LLONG_MIN */
1988 const char *string_fmt[] = {
2008 const char *string_val[] = {
2011 "Sound check: One, two, three.",
2012 "This string is a little longer than the other strings.",
2017 #if !OS_SYSV /* SysV uses a different format than we do. */
2018 const char *pointer_fmt[] = {
2024 const char *pointer_val[] = {
2030 #endif /* !OS_SYSV */
2031 char buf1[1024], buf2[1024];
2032 double value, digits = 9.123456789012345678901234567890123456789;
2033 int i, j, r1, r2, failed = 0, num = 0;
2036 * Use -DTEST_NILS in order to also test the conversion of nil values. Might
2037 * segfault on systems which don't support converting a NULL pointer with "%s"
2038 * and lets some test cases fail against BSD and glibc due to bugs in their
2046 #endif /* !defined(TEST_NILS) */
2049 #endif /* defined(TEST) */
2050 #define TEST(fmt, val) \
2052 for (i = 0; fmt[i] != NULL; i++) \
2053 for (j = 0; j == 0 || val[j - TEST_NILS] != 0; j++) { \
2054 r1 = sprintf(buf1, fmt[i], val[j]); \
2055 r2 = snprintf(buf2, sizeof(buf2), fmt[i], val[j]); \
2056 if (strcmp(buf1, buf2) != 0 || r1 != r2) { \
2057 (void)printf("Results don't match, " \
2058 "format string: %s\n" \
2059 "\t sprintf(3): [%s] (%d)\n" \
2060 "\tsnprintf(3): [%s] (%d)\n", \
2061 fmt[i], buf1, r1, buf2, r2); \
2066 } while (/* CONSTCOND */ 0)
2069 (void)setlocale(LC_ALL, "");
2070 #endif /* HAVE_LOCALE_H */
2072 (void)puts("Testing our snprintf(3) against your system's sprintf(3).");
2073 TEST(float_fmt, float_val);
2074 TEST(long_fmt, long_val);
2075 TEST(ulong_fmt, ulong_val);
2076 TEST(llong_fmt, llong_val);
2077 TEST(string_fmt, string_val);
2078 #if !OS_SYSV /* SysV uses a different format than we do. */
2079 TEST(pointer_fmt, pointer_val);
2080 #endif /* !OS_SYSV */
2081 (void)printf("Result: %d out of %d tests failed.\n", failed, num);
2083 (void)fputs("Checking how many digits we support: ", stdout);
2084 for (i = 0; i < 100; i++) {
2085 value = pow(10, i) * digits;
2086 (void)sprintf(buf1, "%.1f", value);
2087 (void)snprintf(buf2, sizeof(buf2), "%.1f", value);
2088 if (strcmp(buf1, buf2) != 0) {
2089 (void)printf("apparently %d.\n", i);
2093 return (failed == 0) ? 0 : 1;
2095 #endif /* TEST_SNPRINTF */
2097 /* vim: set joinspaces textwidth=80: */