2 * Copyright (c) 1995 Patrick Powell.
4 * This code is based on code written by Patrick Powell <papowell@astart.com>.
5 * It may be used for any purpose as long as this notice remains intact on all
6 * source code distributions.
10 * Copyright (c) 2008 Holger Weiss.
12 * This version of the code is maintained by Holger Weiss <holger@jhweiss.de>.
13 * My changes to the code may freely be used, modified and/or redistributed for
14 * any purpose. It would be nice if additions and fixes to this file (including
15 * trivial code cleanups) would be sent back in order to let me include them in
16 * the version available at <http://www.jhweiss.de/software/snprintf.html>.
17 * However, this is not a requirement for using or redistributing (possibly
18 * modified) versions of this file, nor is leaving this notice intact mandatory.
24 * 2008-01-20 Holger Weiss <holger@jhweiss.de> for C99-snprintf 1.1:
26 * Fixed the detection of infinite floating point values on IRIX (and
27 * possibly other systems) and applied another few minor cleanups.
29 * 2008-01-06 Holger Weiss <holger@jhweiss.de> for C99-snprintf 1.0:
31 * Added a lot of new features, fixed many bugs, and incorporated various
32 * improvements done by Andrew Tridgell <tridge@samba.org>, Russ Allbery
33 * <rra@stanford.edu>, Hrvoje Niksic <hniksic@xemacs.org>, Damien Miller
34 * <djm@mindrot.org>, and others for the Samba, INN, Wget, and OpenSSH
35 * projects. The additions include: support the "e", "E", "g", "G", and
36 * "F" conversion specifiers (and use conversion style "f" or "F" for the
37 * still unsupported "a" and "A" specifiers); support the "hh", "ll", "j",
38 * "t", and "z" length modifiers; support the "#" flag and the (non-C99)
39 * "'" flag; use localeconv(3) (if available) to get both the current
40 * locale's decimal point character and the separator between groups of
41 * digits; fix the handling of various corner cases of field width and
42 * precision specifications; fix various floating point conversion bugs;
43 * handle infinite and NaN floating point values; don't attempt to write to
44 * the output buffer (which may be NULL) if a size of zero was specified;
45 * check for integer overflow of the field width, precision, and return
46 * values and during the floating point conversion; use the OUTCHAR() macro
47 * instead of a function for better performance; provide asprintf(3) and
48 * vasprintf(3) functions; add new test cases. The replacement functions
49 * have been renamed to use an "rpl_" prefix, the function calls in the
50 * main project (and in this file) must be redefined accordingly for each
51 * replacement function which is needed (by using Autoconf or other means).
52 * Various other minor improvements have been applied and the coding style
53 * was cleaned up for consistency.
55 * 2007-07-23 Holger Weiss <holger@jhweiss.de> for Mutt 1.5.13:
57 * C99 compliant snprintf(3) and vsnprintf(3) functions return the number
58 * of characters that would have been written to a sufficiently sized
59 * buffer (excluding the '\0'). The original code simply returned the
60 * length of the resulting output string, so that's been fixed.
62 * 1998-03-05 Michael Elkins <me@mutt.org> for Mutt 0.90.8:
64 * The original code assumed that both snprintf(3) and vsnprintf(3) were
65 * missing. Some systems only have snprintf(3) but not vsnprintf(3), so
66 * the code is now broken down under HAVE_SNPRINTF and HAVE_VSNPRINTF.
68 * 1998-01-27 Thomas Roessler <roessler@does-not-exist.org> for Mutt 0.89i:
70 * The PGP code was using unsigned hexadecimal formats. Unfortunately,
71 * unsigned formats simply didn't work.
73 * 1997-10-22 Brandon Long <blong@fiction.net> for Mutt 0.87.1:
75 * Ok, added some minimal floating point support, which means this probably
76 * requires libm on most operating systems. Don't yet support the exponent
77 * (e,E) and sigfig (g,G). Also, fmtint() was pretty badly broken, it just
78 * wasn't being exercised in ways which showed it, so that's been fixed.
79 * Also, formatted the code to Mutt conventions, and removed dead code left
80 * over from the original. Also, there is now a builtin-test, run with:
81 * gcc -DTEST_SNPRINTF -o snprintf snprintf.c -lm && ./snprintf
83 * 2996-09-15 Brandon Long <blong@fiction.net> for Mutt 0.43:
85 * This was ugly. It is still ugly. I opted out of floating point
86 * numbers, but the formatter understands just about everything from the
87 * normal C string format, at least as far as I can tell from the Solaris
88 * 2.5 printf(3S) man page.
94 * - Add wide character support.
95 * - Add support for "%a" and "%A" conversions.
96 * - Create test routines which predefine the expected results. Our test cases
97 * usually expose bugs in system implementations rather than in ours :-)
103 * 1) The following preprocessor macros should be defined to 1 if the feature or
104 * file in question is available on the target system (by using Autoconf or
105 * other means), though basic functionality should be available as long as
106 * HAVE_STDARG_H and HAVE_STDLIB_H are defined correctly:
119 * HAVE_LCONV_DECIMAL_POINT
120 * HAVE_LCONV_THOUSANDS_SEP
123 * HAVE_UNSIGNED_LONG_LONG_INT
131 * 2) The calls to the functions which should be replaced must be redefined
132 * throughout the project files (by using Autoconf or other means):
134 * #define vsnprintf rpl_vsnprintf
135 * #define snprintf rpl_snprintf
136 * #define vasprintf rpl_vasprintf
137 * #define asprintf rpl_asprintf
139 * 3) The required replacement functions should be declared in some header file
140 * included throughout the project files:
143 * #include <config.h>
146 * #include <stdarg.h>
147 * #if !HAVE_VSNPRINTF
148 * int rpl_vsnprintf(char *, size_t, const char *, va_list);
151 * int rpl_snprintf(char *, size_t, const char *, ...);
153 * #if !HAVE_VASPRINTF
154 * int rpl_vasprintf(char **, const char *, va_list);
157 * int rpl_asprintf(char **, const char *, ...);
161 * Autoconf macros for handling step 1 and step 2 are available at
162 * <http://www.jhweiss.de/software/snprintf.html>.
165 #include "pipe/p_config.h"
171 #define vsnprintf util_vsnprintf
172 #define snprintf util_snprintf
173 #define HAVE_VSNPRINTF 0
174 #define HAVE_SNPRINTF 0
175 #define HAVE_VASPRINTF 1 /* not needed */
176 #define HAVE_ASPRINTF 1 /* not needed */
177 #define HAVE_STDARG_H 1
178 #define HAVE_STDDEF_H 1
179 #define HAVE_STDINT_H 1
180 #define HAVE_STDLIB_H 1
181 #define HAVE_INTTYPES_H 0
182 #define HAVE_LOCALE_H 0
183 #define HAVE_LOCALECONV 0
184 #define HAVE_LCONV_DECIMAL_POINT 0
185 #define HAVE_LCONV_THOUSANDS_SEP 0
186 #define HAVE_LONG_DOUBLE 0
187 #define HAVE_LONG_LONG_INT 1
188 #define HAVE_UNSIGNED_LONG_LONG_INT 1
189 #define HAVE_INTMAX_T 0
190 #define HAVE_UINTMAX_T 0
191 #define HAVE_UINTPTR_T 1
192 #define HAVE_PTRDIFF_T 1
193 #define HAVE_VA_COPY 0
194 #define HAVE___VA_COPY 0
196 #define HAVE_VSNPRINTF 1
197 #define HAVE_SNPRINTF 1
198 #define HAVE_VASPRINTF 1
199 #define HAVE_ASPRINTF 1
201 #endif /* HAVE_CONFIG_H */
203 #if !HAVE_SNPRINTF || !HAVE_VSNPRINTF || !HAVE_ASPRINTF || !HAVE_VASPRINTF
204 #include <stdio.h> /* For NULL, size_t, vsnprintf(3), and vasprintf(3). */
207 #endif /* defined(VA_START) */
210 #endif /* defined(VA_SHIFT) */
213 #define VA_START(ap, last) va_start(ap, last)
214 #define VA_SHIFT(ap, value, type) /* No-op for ANSI C. */
215 #else /* Assume <varargs.h> is available. */
217 #define VA_START(ap, last) va_start(ap) /* "last" is ignored. */
218 #define VA_SHIFT(ap, value, type) value = va_arg(ap, type)
219 #endif /* HAVE_STDARG_H */
223 #include <stdlib.h> /* For malloc(3). */
224 #endif /* HAVE_STDLIB_H */
227 #endif /* defined(VA_COPY) */
230 #endif /* defined(VA_END_COPY) */
232 #define VA_COPY(dest, src) va_copy(dest, src)
233 #define VA_END_COPY(ap) va_end(ap)
235 #define VA_COPY(dest, src) __va_copy(dest, src)
236 #define VA_END_COPY(ap) va_end(ap)
238 #define VA_COPY(dest, src) (void)mymemcpy(&dest, &src, sizeof(va_list))
239 #define VA_END_COPY(ap) /* No-op. */
240 #define NEED_MYMEMCPY 1
241 static void *mymemcpy(void *, void *, size_t);
242 #endif /* HAVE_VA_COPY */
243 #endif /* !HAVE_VASPRINTF */
246 #include <limits.h> /* For *_MAX. */
248 #include <inttypes.h> /* For intmax_t (if not defined in <stdint.h>). */
249 #endif /* HAVE_INTTYPES_H */
251 #include <locale.h> /* For localeconv(3). */
252 #endif /* HAVE_LOCALE_H */
254 #include <stddef.h> /* For ptrdiff_t. */
255 #endif /* HAVE_STDDEF_H */
257 #include <stdint.h> /* For intmax_t. */
258 #endif /* HAVE_STDINT_H */
260 /* Support for unsigned long long int. We may also need ULLONG_MAX. */
261 #ifndef ULONG_MAX /* We may need ULONG_MAX as a fallback. */
263 #define ULONG_MAX UINT_MAX
265 #define ULONG_MAX INT_MAX
266 #endif /* defined(UINT_MAX) */
267 #endif /* !defined(ULONG_MAX) */
270 #endif /* defined(ULLONG) */
271 #if HAVE_UNSIGNED_LONG_LONG_INT
272 #define ULLONG unsigned long long int
274 #define ULLONG_MAX ULONG_MAX
275 #endif /* !defined(ULLONG_MAX) */
277 #define ULLONG unsigned long int
280 #endif /* defined(ULLONG_MAX) */
281 #define ULLONG_MAX ULONG_MAX
282 #endif /* HAVE_LONG_LONG_INT */
284 /* Support for uintmax_t. We also need UINTMAX_MAX. */
287 #endif /* defined(UINTMAX_T) */
288 #if HAVE_UINTMAX_T || defined(uintmax_t)
289 #define UINTMAX_T uintmax_t
291 #define UINTMAX_MAX ULLONG_MAX
292 #endif /* !defined(UINTMAX_MAX) */
294 #define UINTMAX_T ULLONG
297 #endif /* defined(UINTMAX_MAX) */
298 #define UINTMAX_MAX ULLONG_MAX
299 #endif /* HAVE_UINTMAX_T || defined(uintmax_t) */
301 /* Support for long double. */
304 #define LDOUBLE long double
306 #define LDOUBLE double
307 #endif /* HAVE_LONG_DOUBLE */
308 #endif /* !defined(LDOUBLE) */
310 /* Support for long long int. */
312 #if HAVE_LONG_LONG_INT
313 #define LLONG long long int
315 #define LLONG long int
316 #endif /* HAVE_LONG_LONG_INT */
317 #endif /* !defined(LLONG) */
319 /* Support for intmax_t. */
321 #if HAVE_INTMAX_T || defined(intmax_t)
322 #define INTMAX_T intmax_t
324 #define INTMAX_T LLONG
325 #endif /* HAVE_INTMAX_T || defined(intmax_t) */
326 #endif /* !defined(INTMAX_T) */
328 /* Support for uintptr_t. */
330 #if HAVE_UINTPTR_T || defined(uintptr_t)
331 #define UINTPTR_T uintptr_t
333 #define UINTPTR_T unsigned long int
334 #endif /* HAVE_UINTPTR_T || defined(uintptr_t) */
335 #endif /* !defined(UINTPTR_T) */
337 /* Support for ptrdiff_t. */
339 #if HAVE_PTRDIFF_T || defined(ptrdiff_t)
340 #define PTRDIFF_T ptrdiff_t
342 #define PTRDIFF_T long int
343 #endif /* HAVE_PTRDIFF_T || defined(ptrdiff_t) */
344 #endif /* !defined(PTRDIFF_T) */
347 * We need an unsigned integer type corresponding to ptrdiff_t (cf. C99:
348 * 7.19.6.1, 7). However, we'll simply use PTRDIFF_T and convert it to an
349 * unsigned type if necessary. This should work just fine in practice.
352 #define UPTRDIFF_T PTRDIFF_T
353 #endif /* !defined(UPTRDIFF_T) */
356 * We need a signed integer type corresponding to size_t (cf. C99: 7.19.6.1, 7).
357 * However, we'll simply use size_t and convert it to a signed type if
358 * necessary. This should work just fine in practice.
361 #define SSIZE_T size_t
362 #endif /* !defined(SSIZE_T) */
364 /* Either ERANGE or E2BIG should be available everywhere. */
367 #endif /* !defined(ERANGE) */
369 #define EOVERFLOW ERANGE
370 #endif /* !defined(EOVERFLOW) */
373 * Buffer size to hold the octal string representation of UINT128_MAX without
374 * nul-termination ("3777777777777777777777777777777777777777777").
376 #ifdef MAX_CONVERT_LENGTH
377 #undef MAX_CONVERT_LENGTH
378 #endif /* defined(MAX_CONVERT_LENGTH) */
379 #define MAX_CONVERT_LENGTH 43
381 /* Format read states. */
382 #define PRINT_S_DEFAULT 0
383 #define PRINT_S_FLAGS 1
384 #define PRINT_S_WIDTH 2
385 #define PRINT_S_DOT 3
386 #define PRINT_S_PRECISION 4
387 #define PRINT_S_MOD 5
388 #define PRINT_S_CONV 6
391 #define PRINT_F_MINUS (1 << 0)
392 #define PRINT_F_PLUS (1 << 1)
393 #define PRINT_F_SPACE (1 << 2)
394 #define PRINT_F_NUM (1 << 3)
395 #define PRINT_F_ZERO (1 << 4)
396 #define PRINT_F_QUOTE (1 << 5)
397 #define PRINT_F_UP (1 << 6)
398 #define PRINT_F_UNSIGNED (1 << 7)
399 #define PRINT_F_TYPE_G (1 << 8)
400 #define PRINT_F_TYPE_E (1 << 9)
402 /* Conversion flags. */
403 #define PRINT_C_CHAR 1
404 #define PRINT_C_SHORT 2
405 #define PRINT_C_LONG 3
406 #define PRINT_C_LLONG 4
407 #define PRINT_C_LDOUBLE 5
408 #define PRINT_C_SIZE 6
409 #define PRINT_C_PTRDIFF 7
410 #define PRINT_C_INTMAX 8
413 #define MAX(x, y) ((x >= y) ? x : y)
414 #endif /* !defined(MAX) */
416 #define CHARTOINT(ch) (ch - '0')
417 #endif /* !defined(CHARTOINT) */
419 #define ISDIGIT(ch) ('0' <= (unsigned char)ch && (unsigned char)ch <= '9')
420 #endif /* !defined(ISDIGIT) */
422 #define ISNAN(x) (x != x)
423 #endif /* !defined(ISNAN) */
425 #define ISINF(x) (x != 0.0 && x + x == x)
426 #endif /* !defined(ISINF) */
430 #endif /* defined(OUTCHAR) */
431 #define OUTCHAR(str, len, size, ch) \
433 if (len + 1 < size) \
436 } while (/* CONSTCOND */ 0)
438 static void fmtstr(char *, size_t *, size_t, const char *, int, int, int);
439 static void fmtint(char *, size_t *, size_t, INTMAX_T
, int, int, int, int);
440 static void fmtflt(char *, size_t *, size_t, LDOUBLE
, int, int, int, int *);
441 static void printsep(char *, size_t *, size_t);
442 static int getnumsep(int);
443 static int getexponent(LDOUBLE
);
444 static int convert(UINTMAX_T
, char *, size_t, int, int);
445 static UINTMAX_T
cast(LDOUBLE
);
446 static UINTMAX_T
myround(LDOUBLE
);
447 static LDOUBLE
mypow10(int);
450 util_vsnprintf(char *str
, size_t size
, const char *format
, va_list args
)
454 unsigned char cvalue
;
455 const char *strvalue
;
457 PTRDIFF_T
*ptrdiffptr
;
463 signed char *charptr
;
471 int state
= PRINT_S_DEFAULT
;
475 * C99 says: "If `n' is zero, nothing is written, and `s' may be a null
476 * pointer." (7.19.6.5, 2) We're forgiving and allow a NULL pointer
477 * even if a size larger than zero was specified. At least NetBSD's
478 * snprintf(3) does the same, as well as other versions of this file.
479 * (Though some of these versions will write to a non-NULL buffer even
480 * if a size of zero was specified, which violates the standard.)
482 if (str
== NULL
&& size
!= 0)
487 case PRINT_S_DEFAULT
:
489 state
= PRINT_S_FLAGS
;
491 OUTCHAR(str
, len
, size
, ch
);
497 flags
|= PRINT_F_MINUS
;
501 flags
|= PRINT_F_PLUS
;
505 flags
|= PRINT_F_SPACE
;
509 flags
|= PRINT_F_NUM
;
513 flags
|= PRINT_F_ZERO
;
516 case '\'': /* SUSv2 flag (not in C99). */
517 flags
|= PRINT_F_QUOTE
;
521 state
= PRINT_S_WIDTH
;
528 if (width
> (INT_MAX
- ch
) / 10) {
532 width
= 10 * width
+ ch
;
534 } else if (ch
== '*') {
536 * C99 says: "A negative field width argument is
537 * taken as a `-' flag followed by a positive
538 * field width." (7.19.6.1, 5)
540 if ((width
= va_arg(args
, int)) < 0) {
541 flags
|= PRINT_F_MINUS
;
551 state
= PRINT_S_PRECISION
;
556 case PRINT_S_PRECISION
:
561 if (precision
> (INT_MAX
- ch
) / 10) {
565 precision
= 10 * precision
+ ch
;
567 } else if (ch
== '*') {
569 * C99 says: "A negative precision argument is
570 * taken as if the precision were omitted."
573 if ((precision
= va_arg(args
, int)) < 0)
584 if (ch
== 'h') { /* It's a char. */
586 cflags
= PRINT_C_CHAR
;
588 cflags
= PRINT_C_SHORT
;
592 if (ch
== 'l') { /* It's a long long. */
594 cflags
= PRINT_C_LLONG
;
596 cflags
= PRINT_C_LONG
;
599 cflags
= PRINT_C_LDOUBLE
;
603 cflags
= PRINT_C_INTMAX
;
607 cflags
= PRINT_C_PTRDIFF
;
611 cflags
= PRINT_C_SIZE
;
615 state
= PRINT_S_CONV
;
624 value
= (signed char)va_arg(args
, int);
627 value
= (short int)va_arg(args
, int);
630 value
= va_arg(args
, long int);
633 value
= va_arg(args
, LLONG
);
636 value
= va_arg(args
, SSIZE_T
);
639 value
= va_arg(args
, INTMAX_T
);
641 case PRINT_C_PTRDIFF
:
642 value
= va_arg(args
, PTRDIFF_T
);
645 value
= va_arg(args
, int);
648 fmtint(str
, &len
, size
, value
, 10, width
,
664 flags
|= PRINT_F_UNSIGNED
;
667 value
= (unsigned char)va_arg(args
,
671 value
= (unsigned short int)va_arg(args
,
675 value
= va_arg(args
, unsigned long int);
678 value
= va_arg(args
, ULLONG
);
681 value
= va_arg(args
, size_t);
684 value
= va_arg(args
, UINTMAX_T
);
686 case PRINT_C_PTRDIFF
:
687 value
= va_arg(args
, UPTRDIFF_T
);
690 value
= va_arg(args
, unsigned int);
693 fmtint(str
, &len
, size
, value
, base
, width
,
697 /* Not yet supported, we'll use "%F". */
702 /* Not yet supported, we'll use "%f". */
705 if (cflags
== PRINT_C_LDOUBLE
)
706 fvalue
= va_arg(args
, LDOUBLE
);
708 fvalue
= va_arg(args
, double);
709 fmtflt(str
, &len
, size
, fvalue
, width
,
710 precision
, flags
, &overflow
);
718 flags
|= PRINT_F_TYPE_E
;
719 if (cflags
== PRINT_C_LDOUBLE
)
720 fvalue
= va_arg(args
, LDOUBLE
);
722 fvalue
= va_arg(args
, double);
723 fmtflt(str
, &len
, size
, fvalue
, width
,
724 precision
, flags
, &overflow
);
732 flags
|= PRINT_F_TYPE_G
;
733 if (cflags
== PRINT_C_LDOUBLE
)
734 fvalue
= va_arg(args
, LDOUBLE
);
736 fvalue
= va_arg(args
, double);
738 * If the precision is zero, it is treated as
739 * one (cf. C99: 7.19.6.1, 8).
743 fmtflt(str
, &len
, size
, fvalue
, width
,
744 precision
, flags
, &overflow
);
749 cvalue
= (unsigned char)va_arg(args
, int);
750 OUTCHAR(str
, len
, size
, cvalue
);
753 strvalue
= va_arg(args
, char *);
754 fmtstr(str
, &len
, size
, strvalue
, width
,
759 * C99 says: "The value of the pointer is
760 * converted to a sequence of printing
761 * characters, in an implementation-defined
762 * manner." (C99: 7.19.6.1, 8)
764 if ((strvalue
= va_arg(args
, void *)) == NULL
)
766 * We use the glibc format. BSD prints
769 fmtstr(str
, &len
, size
, "(nil)", width
,
773 * We use the BSD/glibc format. SysV
774 * omits the "0x" prefix (which we emit
775 * using the PRINT_F_NUM flag).
777 flags
|= PRINT_F_NUM
;
778 flags
|= PRINT_F_UNSIGNED
;
779 fmtint(str
, &len
, size
,
780 (UINTPTR_T
)strvalue
, 16, width
,
787 charptr
= va_arg(args
, signed char *);
788 *charptr
= (signed char)len
;
791 shortptr
= va_arg(args
, short int *);
792 *shortptr
= (short int)len
;
795 longptr
= va_arg(args
, long int *);
796 *longptr
= (long int)len
;
799 llongptr
= va_arg(args
, LLONG
*);
800 *llongptr
= (LLONG
)len
;
804 * C99 says that with the "z" length
805 * modifier, "a following `n' conversion
806 * specifier applies to a pointer to a
807 * signed integer type corresponding to
808 * size_t argument." (7.19.6.1, 7)
810 sizeptr
= va_arg(args
, SSIZE_T
*);
814 intmaxptr
= va_arg(args
, INTMAX_T
*);
817 case PRINT_C_PTRDIFF
:
818 ptrdiffptr
= va_arg(args
, PTRDIFF_T
*);
822 intptr
= va_arg(args
, int *);
827 case '%': /* Print a "%" character verbatim. */
828 OUTCHAR(str
, len
, size
, ch
);
830 default: /* Skip other characters. */
834 state
= PRINT_S_DEFAULT
;
835 base
= cflags
= flags
= width
= 0;
843 str
[size
- 1] = '\0';
845 if (overflow
|| len
>= INT_MAX
) {
852 fmtstr(char *str
, size_t *len
, size_t size
, const char *value
, int width
,
853 int precision
, int flags
)
855 int padlen
, strln
; /* Amount to pad. */
856 int noprecision
= (precision
== -1);
858 if (value
== NULL
) /* We're forgiving. */
861 /* If a precision was specified, don't read the string past it. */
862 for (strln
= 0; value
[strln
] != '\0' &&
863 (noprecision
|| strln
< precision
); strln
++)
866 if ((padlen
= width
- strln
) < 0)
868 if (flags
& PRINT_F_MINUS
) /* Left justify. */
871 while (padlen
> 0) { /* Leading spaces. */
872 OUTCHAR(str
, *len
, size
, ' ');
875 while (*value
!= '\0' && (noprecision
|| precision
-- > 0)) {
876 OUTCHAR(str
, *len
, size
, *value
);
879 while (padlen
< 0) { /* Trailing spaces. */
880 OUTCHAR(str
, *len
, size
, ' ');
886 fmtint(char *str
, size_t *len
, size_t size
, INTMAX_T value
, int base
, int width
,
887 int precision
, int flags
)
890 char iconvert
[MAX_CONVERT_LENGTH
];
893 int spadlen
= 0; /* Amount to space pad. */
894 int zpadlen
= 0; /* Amount to zero pad. */
896 int separators
= (flags
& PRINT_F_QUOTE
);
897 int noprecision
= (precision
== -1);
899 if (flags
& PRINT_F_UNSIGNED
)
902 uvalue
= (value
>= 0) ? value
: -value
;
905 else if (flags
& PRINT_F_PLUS
) /* Do a sign. */
907 else if (flags
& PRINT_F_SPACE
)
911 pos
= convert(uvalue
, iconvert
, sizeof(iconvert
), base
,
914 if (flags
& PRINT_F_NUM
&& uvalue
!= 0) {
916 * C99 says: "The result is converted to an `alternative form'.
917 * For `o' conversion, it increases the precision, if and only
918 * if necessary, to force the first digit of the result to be a
919 * zero (if the value and precision are both 0, a single 0 is
920 * printed). For `x' (or `X') conversion, a nonzero result has
921 * `0x' (or `0X') prefixed to it." (7.19.6.1, 6)
925 if (precision
<= pos
)
929 hexprefix
= (flags
& PRINT_F_UP
) ? 'X' : 'x';
934 if (separators
) /* Get the number of group separators we'll print. */
935 separators
= getnumsep(pos
);
937 zpadlen
= precision
- pos
- separators
;
938 spadlen
= width
/* Minimum field width. */
939 - separators
/* Number of separators. */
940 - MAX(precision
, pos
) /* Number of integer digits. */
941 - ((sign
!= 0) ? 1 : 0) /* Will we print a sign? */
942 - ((hexprefix
!= 0) ? 2 : 0); /* Will we print a prefix? */
950 * C99 says: "If the `0' and `-' flags both appear, the `0' flag is
951 * ignored. For `d', `i', `o', `u', `x', and `X' conversions, if a
952 * precision is specified, the `0' flag is ignored." (7.19.6.1, 6)
954 if (flags
& PRINT_F_MINUS
) /* Left justify. */
956 else if (flags
& PRINT_F_ZERO
&& noprecision
) {
960 while (spadlen
> 0) { /* Leading spaces. */
961 OUTCHAR(str
, *len
, size
, ' ');
964 if (sign
!= 0) /* Sign. */
965 OUTCHAR(str
, *len
, size
, sign
);
966 if (hexprefix
!= 0) { /* A "0x" or "0X" prefix. */
967 OUTCHAR(str
, *len
, size
, '0');
968 OUTCHAR(str
, *len
, size
, hexprefix
);
970 while (zpadlen
> 0) { /* Leading zeros. */
971 OUTCHAR(str
, *len
, size
, '0');
974 while (pos
> 0) { /* The actual digits. */
976 OUTCHAR(str
, *len
, size
, iconvert
[pos
]);
977 if (separators
> 0 && pos
> 0 && pos
% 3 == 0)
978 printsep(str
, len
, size
);
980 while (spadlen
< 0) { /* Trailing spaces. */
981 OUTCHAR(str
, *len
, size
, ' ');
987 fmtflt(char *str
, size_t *len
, size_t size
, LDOUBLE fvalue
, int width
,
988 int precision
, int flags
, int *overflow
)
994 const char *infnan
= NULL
;
995 char iconvert
[MAX_CONVERT_LENGTH
];
996 char fconvert
[MAX_CONVERT_LENGTH
];
997 char econvert
[4]; /* "e-12" (without nul-termination). */
1000 int leadfraczeros
= 0;
1009 int separators
= (flags
& PRINT_F_QUOTE
);
1010 int estyle
= (flags
& PRINT_F_TYPE_E
);
1011 #if HAVE_LOCALECONV && HAVE_LCONV_DECIMAL_POINT
1012 struct lconv
*lc
= localeconv();
1013 #endif /* HAVE_LOCALECONV && HAVE_LCONV_DECIMAL_POINT */
1016 * AIX' man page says the default is 0, but C99 and at least Solaris'
1017 * and NetBSD's man pages say the default is 6, and sprintf(3) on AIX
1020 if (precision
== -1)
1025 else if (flags
& PRINT_F_PLUS
) /* Do a sign. */
1027 else if (flags
& PRINT_F_SPACE
)
1031 infnan
= (flags
& PRINT_F_UP
) ? "NAN" : "nan";
1032 else if (ISINF(fvalue
))
1033 infnan
= (flags
& PRINT_F_UP
) ? "INF" : "inf";
1035 if (infnan
!= NULL
) {
1037 iconvert
[ipos
++] = sign
;
1038 while (*infnan
!= '\0')
1039 iconvert
[ipos
++] = *infnan
++;
1040 fmtstr(str
, len
, size
, iconvert
, width
, ipos
, flags
);
1044 /* "%e" (or "%E") or "%g" (or "%G") conversion. */
1045 if (flags
& PRINT_F_TYPE_E
|| flags
& PRINT_F_TYPE_G
) {
1046 if (flags
& PRINT_F_TYPE_G
) {
1048 * For "%g" (and "%G") conversions, the precision
1049 * specifies the number of significant digits, which
1050 * includes the digits in the integer part. The
1051 * conversion will or will not be using "e-style" (like
1052 * "%e" or "%E" conversions) depending on the precision
1053 * and on the exponent. However, the exponent can be
1054 * affected by rounding the converted value, so we'll
1055 * leave this decision for later. Until then, we'll
1056 * assume that we're going to do an "e-style" conversion
1057 * (in order to get the exponent calculated). For
1058 * "e-style", the precision must be decremented by one.
1062 * For "%g" (and "%G") conversions, trailing zeros are
1063 * removed from the fractional portion of the result
1064 * unless the "#" flag was specified.
1066 if (!(flags
& PRINT_F_NUM
))
1069 exponent
= getexponent(fvalue
);
1075 * Sorry, we only support 9, 19, or 38 digits (that is, the number of
1076 * digits of the 32-bit, the 64-bit, or the 128-bit UINTMAX_MAX value
1077 * minus one) past the decimal point due to our conversion method.
1079 switch (sizeof(UINTMAX_T
)) {
1094 ufvalue
= (fvalue
>= 0.0) ? fvalue
: -fvalue
;
1095 if (estyle
) /* We want exactly one integer digit. */
1096 ufvalue
/= mypow10(exponent
);
1098 if ((intpart
= cast(ufvalue
)) == UINTMAX_MAX
) {
1104 * Factor of ten with the number of digits needed for the fractional
1105 * part. For example, if the precision is 3, the mask will be 1000.
1107 mask
= (UINTMAX_T
)mypow10(precision
);
1109 * We "cheat" by converting the fractional part to integer by
1110 * multiplying by a factor of ten.
1112 if ((fracpart
= myround(mask
* (ufvalue
- intpart
))) >= mask
) {
1114 * For example, ufvalue = 2.99962, intpart = 2, and mask = 1000
1115 * (because precision = 3). Now, myround(1000 * 0.99962) will
1116 * return 1000. So, the integer part must be incremented by one
1117 * and the fractional part must be set to zero.
1121 if (estyle
&& intpart
== 10) {
1123 * The value was rounded up to ten, but we only want one
1124 * integer digit if using "e-style". So, the integer
1125 * part must be set to one and the exponent must be
1126 * incremented by one.
1134 * Now that we know the real exponent, we can check whether or not to
1135 * use "e-style" for "%g" (and "%G") conversions. If we don't need
1136 * "e-style", the precision must be adjusted and the integer and
1137 * fractional parts must be recalculated from the original value.
1139 * C99 says: "Let P equal the precision if nonzero, 6 if the precision
1140 * is omitted, or 1 if the precision is zero. Then, if a conversion
1141 * with style `E' would have an exponent of X:
1143 * - if P > X >= -4, the conversion is with style `f' (or `F') and
1144 * precision P - (X + 1).
1146 * - otherwise, the conversion is with style `e' (or `E') and precision
1147 * P - 1." (7.19.6.1, 8)
1149 * Note that we had decremented the precision by one.
1151 if (flags
& PRINT_F_TYPE_G
&& estyle
&&
1152 precision
+ 1 > exponent
&& exponent
>= -4) {
1153 precision
-= exponent
;
1160 exponent
= -exponent
;
1166 * Convert the exponent. The sizeof(econvert) is 4. So, the
1167 * econvert buffer can hold e.g. "e+99" and "e-99". We don't
1168 * support an exponent which contains more than two digits.
1169 * Therefore, the following stores are safe.
1171 epos
= convert(exponent
, econvert
, 2, 10, 0);
1173 * C99 says: "The exponent always contains at least two digits,
1174 * and only as many more digits as necessary to represent the
1175 * exponent." (7.19.6.1, 8)
1178 econvert
[epos
++] = '0';
1179 econvert
[epos
++] = esign
;
1180 econvert
[epos
++] = (flags
& PRINT_F_UP
) ? 'E' : 'e';
1183 /* Convert the integer part and the fractional part. */
1184 ipos
= convert(intpart
, iconvert
, sizeof(iconvert
), 10, 0);
1185 if (fracpart
!= 0) /* convert() would return 1 if fracpart == 0. */
1186 fpos
= convert(fracpart
, fconvert
, sizeof(fconvert
), 10, 0);
1188 leadfraczeros
= precision
- fpos
;
1191 if (fpos
> 0) /* Omit trailing fractional part zeros. */
1192 while (omitcount
< fpos
&& fconvert
[omitcount
] == '0')
1194 else { /* The fractional part is zero, omit it completely. */
1195 omitcount
= precision
;
1198 precision
-= omitcount
;
1202 * Print a decimal point if either the fractional part is non-zero
1203 * and/or the "#" flag was specified.
1205 if (precision
> 0 || flags
& PRINT_F_NUM
)
1207 if (separators
) /* Get the number of group separators we'll print. */
1208 separators
= getnumsep(ipos
);
1210 padlen
= width
/* Minimum field width. */
1211 - ipos
/* Number of integer digits. */
1212 - epos
/* Number of exponent characters. */
1213 - precision
/* Number of fractional digits. */
1214 - separators
/* Number of group separators. */
1215 - (emitpoint
? 1 : 0) /* Will we print a decimal point? */
1216 - ((sign
!= 0) ? 1 : 0); /* Will we print a sign character? */
1222 * C99 says: "If the `0' and `-' flags both appear, the `0' flag is
1223 * ignored." (7.19.6.1, 6)
1225 if (flags
& PRINT_F_MINUS
) /* Left justifty. */
1227 else if (flags
& PRINT_F_ZERO
&& padlen
> 0) {
1228 if (sign
!= 0) { /* Sign. */
1229 OUTCHAR(str
, *len
, size
, sign
);
1232 while (padlen
> 0) { /* Leading zeros. */
1233 OUTCHAR(str
, *len
, size
, '0');
1237 while (padlen
> 0) { /* Leading spaces. */
1238 OUTCHAR(str
, *len
, size
, ' ');
1241 if (sign
!= 0) /* Sign. */
1242 OUTCHAR(str
, *len
, size
, sign
);
1243 while (ipos
> 0) { /* Integer part. */
1245 OUTCHAR(str
, *len
, size
, iconvert
[ipos
]);
1246 if (separators
> 0 && ipos
> 0 && ipos
% 3 == 0)
1247 printsep(str
, len
, size
);
1249 if (emitpoint
) { /* Decimal point. */
1250 #if HAVE_LOCALECONV && HAVE_LCONV_DECIMAL_POINT
1251 if (lc
->decimal_point
!= NULL
&& *lc
->decimal_point
!= '\0')
1252 OUTCHAR(str
, *len
, size
, *lc
->decimal_point
);
1253 else /* We'll always print some decimal point character. */
1254 #endif /* HAVE_LOCALECONV && HAVE_LCONV_DECIMAL_POINT */
1255 OUTCHAR(str
, *len
, size
, '.');
1257 while (leadfraczeros
> 0) { /* Leading fractional part zeros. */
1258 OUTCHAR(str
, *len
, size
, '0');
1261 while (fpos
> omitcount
) { /* The remaining fractional part. */
1263 OUTCHAR(str
, *len
, size
, fconvert
[fpos
]);
1265 while (epos
> 0) { /* Exponent. */
1267 OUTCHAR(str
, *len
, size
, econvert
[epos
]);
1269 while (padlen
< 0) { /* Trailing spaces. */
1270 OUTCHAR(str
, *len
, size
, ' ');
1276 printsep(char *str
, size_t *len
, size_t size
)
1278 #if HAVE_LOCALECONV && HAVE_LCONV_THOUSANDS_SEP
1279 struct lconv
*lc
= localeconv();
1282 if (lc
->thousands_sep
!= NULL
)
1283 for (i
= 0; lc
->thousands_sep
[i
] != '\0'; i
++)
1284 OUTCHAR(str
, *len
, size
, lc
->thousands_sep
[i
]);
1286 #endif /* HAVE_LOCALECONV && HAVE_LCONV_THOUSANDS_SEP */
1287 OUTCHAR(str
, *len
, size
, ',');
1291 getnumsep(int digits
)
1293 int separators
= (digits
- ((digits
% 3 == 0) ? 1 : 0)) / 3;
1294 #if HAVE_LOCALECONV && HAVE_LCONV_THOUSANDS_SEP
1296 struct lconv
*lc
= localeconv();
1298 /* We support an arbitrary separator length (including zero). */
1299 if (lc
->thousands_sep
!= NULL
) {
1300 for (strln
= 0; lc
->thousands_sep
[strln
] != '\0'; strln
++)
1302 separators
*= strln
;
1304 #endif /* HAVE_LOCALECONV && HAVE_LCONV_THOUSANDS_SEP */
1309 getexponent(LDOUBLE value
)
1311 LDOUBLE tmp
= (value
>= 0.0) ? value
: -value
;
1315 * We check for 99 > exponent > -99 in order to work around possible
1316 * endless loops which could happen (at least) in the second loop (at
1317 * least) if we're called with an infinite value. However, we checked
1318 * for infinity before calling this function using our ISINF() macro, so
1319 * this might be somewhat paranoid.
1321 while (tmp
< 1.0 && tmp
> 0.0 && --exponent
> -99)
1323 while (tmp
>= 10.0 && ++exponent
< 99)
1330 convert(UINTMAX_T value
, char *buf
, size_t size
, int base
, int caps
)
1332 const char *digits
= caps
? "0123456789ABCDEF" : "0123456789abcdef";
1335 /* We return an unterminated buffer with the digits in reverse order. */
1337 buf
[pos
++] = digits
[value
% base
];
1339 } while (value
!= 0 && pos
< size
);
1350 * We check for ">=" and not for ">" because if UINTMAX_MAX cannot be
1351 * represented exactly as an LDOUBLE value (but is less than LDBL_MAX),
1352 * it may be increased to the nearest higher representable value for the
1353 * comparison (cf. C99: 6.3.1.4, 2). It might then equal the LDOUBLE
1354 * value although converting the latter to UINTMAX_T would overflow.
1356 if (value
>= UINTMAX_MAX
)
1359 result
= (UINTMAX_T
)value
;
1361 * At least on NetBSD/sparc64 3.0.2 and 4.99.30, casting long double to
1362 * an integer type converts e.g. 1.9 to 2 instead of 1 (which violates
1363 * the standard). Sigh.
1365 return (result
<= value
) ? result
: result
- 1;
1369 myround(LDOUBLE value
)
1371 UINTMAX_T intpart
= cast(value
);
1373 return ((value
-= intpart
) < 0.5) ? intpart
: intpart
+ 1;
1377 mypow10(int exponent
)
1381 while (exponent
> 0) {
1385 while (exponent
< 0) {
1391 #endif /* !HAVE_VSNPRINTF */
1396 mymemcpy(void *dst
, void *src
, size_t len
)
1398 const char *from
= src
;
1401 /* No need for optimization, we use this only to replace va_copy(3). */
1406 #endif /* NEED_MYMEMCPY */
1409 util_vasprintf(char **ret
, const char *format
, va_list ap
)
1416 len
= vsnprintf(NULL
, 0, format
, aq
);
1418 if (len
< 0 || (*ret
= malloc(size
= len
+ 1)) == NULL
)
1420 return vsnprintf(*ret
, size
, format
, ap
);
1422 #endif /* !HAVE_VASPRINTF */
1427 util_snprintf(char *str
, size_t size
, const char *format
, ...)
1430 util_snprintf(va_alist
) va_dcl
1431 #endif /* HAVE_STDARG_H */
1437 #endif /* HAVE_STDARG_H */
1441 VA_START(ap
, format
);
1442 VA_SHIFT(ap
, str
, char *);
1443 VA_SHIFT(ap
, size
, size_t);
1444 VA_SHIFT(ap
, format
, const char *);
1445 len
= vsnprintf(str
, size
, format
, ap
);
1449 #endif /* !HAVE_SNPRINTF */
1454 util_asprintf(char **ret
, const char *format
, ...)
1457 util_asprintf(va_alist
) va_dcl
1458 #endif /* HAVE_STDARG_H */
1463 #endif /* HAVE_STDARG_H */
1467 VA_START(ap
, format
);
1468 VA_SHIFT(ap
, ret
, char **);
1469 VA_SHIFT(ap
, format
, const char *);
1470 len
= vasprintf(ret
, format
, ap
);
1474 #endif /* !HAVE_ASPRINTF */
1475 #else /* Dummy declaration to avoid empty translation unit warnings. */
1477 #endif /* !HAVE_SNPRINTF || !HAVE_VSNPRINTF || !HAVE_ASPRINTF || [...] */
1480 /* vim: set joinspaces textwidth=80: */