1 /* Copyright (c) 2005-2010, 2012-2015. The SimGrid Team.
2 * All rights reserved. */
4 /* This program is free software; you can redistribute it and/or modify it
5 * under the terms of the license (GNU LGPL) which comes with this package. */
8 * snprintf.c - a portable implementation of snprintf
11 * Mark Martinec <mark.martinec@ijs.si>, April 1999.
13 * Copyright 1999, Mark Martinec. All rights reserved.
15 * TERMS AND CONDITIONS
16 * This program is free software; you can redistribute it and/or modify
17 * it under the terms of the "Frontier Artistic License" which comes
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty
22 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
23 * See the Frontier Artistic License for more details.
25 * You should have received a copy of the Frontier Artistic License
26 * with this Kit in the file named LICENSE.txt .
27 * If not, I'll be glad to provide one.
30 * - careful adherence to specs regarding flags, field width and precision;
31 * - good performance for large string handling (large format, large
32 * argument or large paddings). Performance is similar to system's sprintf
33 * and in several cases significantly better (make sure you compile with
34 * optimizations turned on, tell the compiler the code is strict ANSI
35 * if necessary to give it more freedom for optimizations);
36 * - return value semantics per ISO/IEC 9899:1999 ("ISO C99");
37 * - written in standard ISO/ANSI C - requires an ANSI C compiler.
39 * SUPPORTED CONVERSION SPECIFIERS AND DATA TYPES
41 * This snprintf only supports the following conversion specifiers:
42 * s, c, d, u, o, x, X, p (and synonyms: i, D, U, O - see below)
43 * with flags: '-', '+', ' ', '0' and '#'.
44 * An asterisk is supported for field width as well as precision.
46 * Length modifiers 'h' (short int), 'l' (long int),
47 * and 'll' (long long int) are supported.
49 * If macro SNPRINTF_LONGLONG_SUPPORT is not defined (default) the
50 * length modifier 'll' is recognized but treated the same as 'l',
51 * which may cause argument value truncation! Defining
52 * SNPRINTF_LONGLONG_SUPPORT requires that your system's sprintf also
53 * handles length modifier 'll'. long long int is a language extension
54 * which may not be portable.
56 * Conversion of numeric data (conversion specifiers d, u, o, x, X, p)
57 * with length modifiers (none or h, l, ll) is left to the system routine
58 * sprintf, but all handling of flags, field width and precision as well as
59 * c and s conversions is done very carefully by this portable routine.
60 * If a string precision (truncation) is specified (e.g. %.8s) it is
61 * guaranteed the string beyond the specified precision will not be referenced.
63 * Length modifiers h, l and ll are ignored for c and s conversions (data
64 * types wint_t and wchar_t are not supported).
66 * The following common synonyms for conversion characters are supported:
67 * - i is a synonym for d
68 * - D is a synonym for ld, explicit length modifiers are ignored
69 * - U is a synonym for lu, explicit length modifiers are ignored
70 * - O is a synonym for lo, explicit length modifiers are ignored
71 * The D, O and U conversion characters are nonstandard, they are supported
72 * for backward compatibility only, and should not be used for new code.
74 * The following is specifically NOT supported:
75 * - flag ' (thousands' grouping character) is recognized but ignored
76 * - numeric conversion specifiers: f, e, E, g, G and synonym F,
77 * as well as the new a and A conversion specifiers
78 * - length modifier 'L' (long double) and 'q' (quad - use 'll' instead)
79 * - wide character/string conversions: lc, ls, and nonstandard
81 * - writeback of converted string length: conversion character n
82 * - the n$ specification for direct reference to n-th argument
85 * It is permitted for str_m to be zero, and it is permitted to specify NULL
86 * pointer for resulting string argument if str_m is zero (as per ISO C99).
88 * The return value is the number of characters which would be generated
89 * for the given input, excluding the trailing null. If this value
90 * is greater or equal to str_m, not all characters from the result
91 * have been stored in str, output bytes beyond the (str_m-1) -th character
92 * are discarded. If str_m is greater than zero it is guaranteed
93 * the resulting string will be null-terminated.
95 * NOTE that this matches the ISO C99, OpenBSD, and GNU C library 2.1,
96 * but is different from some older and vendor implementations,
97 * and is also different from XPG, XSH5, SUSv2 specifications.
98 * For historical discussion on changes in the semantics and standards
99 * of snprintf see printf(3) man page in the Linux programmers manual.
101 * Routines asprintf and vasprintf return a pointer (in the ptr argument)
102 * to a buffer sufficiently large to hold the resulting string. This pointer
103 * should be passed to free(3) to release the allocated storage when it is
104 * no longer needed. If sufficient space cannot be allocated, these functions
105 * will return -1 and set ptr to be a NULL pointer. These two routines are a
106 * GNU C library extensions (glibc).
108 * Routines asnprintf and vasnprintf are similar to asprintf and vasprintf,
109 * yet, like snprintf and vsnprintf counterparts, will write at most str_m-1
110 * characters into the allocated output string, the last character in the
111 * allocated buffer then gets the terminating null. If the formatted string
112 * length (the return value) is greater than or equal to the str_m argument,
113 * the resulting string was truncated and some of the formatted characters
114 * were discarded. These routines present a handy way to limit the amount
115 * of allocated memory to some sane value.
118 * http://www.ijs.si/software/snprintf/
121 * 1999-04 V0.9 Mark Martinec
122 * - initial version, some modifications after comparing printf
123 * man pages for Digital Unix 4.0, Solaris 2.6 and HPUX 10,
124 * and checking how Perl handles sprintf (differently!);
125 * 1999-04-09 V1.0 Mark Martinec <mark.martinec@ijs.si>
126 * - added main test program, fixed remaining inconsistencies,
127 * added optional (long long int) support;
128 * 1999-04-12 V1.1 Mark Martinec <mark.martinec@ijs.si>
129 * - support the 'p' conversion (pointer to void);
130 * - if a string precision is specified
131 * make sure the string beyond the specified precision
132 * will not be referenced (e.g. by strlen);
133 * 1999-04-13 V1.2 Mark Martinec <mark.martinec@ijs.si>
134 * - support synonyms %D=%ld, %U=%lu, %O=%lo;
135 * - speed up the case of long format string with few conversions;
136 * 1999-06-30 V1.3 Mark Martinec <mark.martinec@ijs.si>
137 * - fixed runaway loop (eventually crashing when str_l wraps
138 * beyond 2^31) while copying format string without
139 * conversion specifiers to a buffer that is too short
140 * (thanks to Edwin Young <edwiny@autonomy.com> for
141 * spotting the problem);
142 * - added macros PORTABLE_SNPRINTF_VERSION_(MAJOR|MINOR)
144 * 2000-02-14 V2.0 (never released) Mark Martinec <mark.martinec@ijs.si>
145 * - relaxed license terms: The Artistic License now applies.
146 * You may still apply the GNU GENERAL PUBLIC LICENSE
147 * as was distributed with previous versions, if you prefer;
148 * - changed REVISION HISTORY dates to use ISO 8601 date format;
149 * - added vsnprintf (patch also independently proposed by
150 * Caolan McNamara 2000-05-04, and Keith M Willenson 2000-06-01)
151 * 2000-06-27 V2.1 Mark Martinec <mark.martinec@ijs.si>
152 * - removed POSIX check for str_m<1; value 0 for str_m is
153 * allowed by ISO C99 (and GNU C library 2.1) - (pointed out
154 * on 2000-05-04 by Caolan McNamara, caolan@ csn dot ul dot ie).
155 * Besides relaxed license this change in standards adherence
156 * is the main reason to bump up the major version number;
157 * - added nonstandard routines asnprintf, vasnprintf, asprintf,
158 * vasprintf that dynamically allocate storage for the
159 * resulting string; these routines are not compiled by default,
160 * see comments where NEED_V?ASN?PRINTF macros are defined;
161 * - autoconf contributed by Caolan McNamara
162 * 2000-10-06 V2.2 Mark Martinec <mark.martinec@ijs.si>
163 * - BUG FIX: the %c conversion used a temporary variable
164 * that was no longer in scope when referenced,
165 * possibly causing incorrect resulting character;
166 * - BUG FIX: make precision and minimal field width unsigned
167 * to handle huge values (2^31 <= n < 2^32) correctly;
168 * also be more careful in the use of signed/unsigned/size_t
169 * internal variables - probably more careful than many
170 * vendor implementations, but there may still be a case
171 * where huge values of str_m, precision or minimal field
172 * could cause incorrect behaviour;
173 * - use separate variables for signed/unsigned arguments,
174 * and for short/int, long, and long long argument lengths
175 * to avoid possible incompatibilities on certain
176 * computer architectures. Also use separate variable
177 * arg_sign to hold sign of a numeric argument,
178 * to make code more transparent;
179 * - some fiddling with zero padding and "0x" to make it
181 * - systematically use macros fast_memcpy and fast_memset
182 * instead of case-by-case hand optimization; determine some
183 * breakeven string lengths for different architectures;
184 * - terminology change: 'format' -> 'conversion specifier',
185 * 'C9x' -> 'ISO/IEC 9899:1999 ("ISO C99")',
186 * 'alternative form' -> 'alternate form',
187 * 'data type modifier' -> 'length modifier';
188 * - several comments rephrased and new ones added;
189 * - make compiler not complain about 'credits' defined but
194 /* Define HAVE_SNPRINTF if your system already has snprintf and vsnprintf.
196 * If HAVE_SNPRINTF is defined this module will not produce code for
197 * snprintf and vsnprintf, unless PREFER_PORTABLE_SNPRINTF is defined as well,
198 * causing this portable version of snprintf to be called portable_snprintf
199 * (and portable_vsnprintf).
201 /* #define HAVE_SNPRINTF */
203 /* Define PREFER_PORTABLE_SNPRINTF if your system does have snprintf and
204 * vsnprintf but you would prefer to use the portable routine(s) instead.
205 * In this case the portable routine is declared as portable_snprintf
206 * (and portable_vsnprintf) and a macro 'snprintf' (and 'vsnprintf')
207 * is defined to expand to 'portable_v?snprintf' - see file snprintf.h .
208 * Defining this macro is only useful if HAVE_SNPRINTF is also defined,
209 * but does does no harm if defined nevertheless.
211 /* #define PREFER_PORTABLE_SNPRINTF */
213 /* Define SNPRINTF_LONGLONG_SUPPORT if you want to support
214 * data type (long long int) and length modifier 'll' (e.g. %lld).
215 * If undefined, 'll' is recognized but treated as a single 'l'.
217 * If the system's sprintf does not handle 'll'
218 * the SNPRINTF_LONGLONG_SUPPORT must not be defined!
220 * This is off by default as (long long int) is a language extension.
222 /* #define SNPRINTF_LONGLONG_SUPPORT */
224 /* Define NEED_SNPRINTF_ONLY if you only need snprintf, and not vsnprintf.
225 * If NEED_SNPRINTF_ONLY is defined, the snprintf will be defined directly,
226 * otherwise both snprintf and vsnprintf routines will be defined
227 * and snprintf will be a simple wrapper around vsnprintf, at the expense
228 * of an extra procedure call.
230 /* #define NEED_SNPRINTF_ONLY */
232 /* Define NEED_V?ASN?PRINTF macros if you need library extension
233 * routines asprintf, vasprintf, asnprintf, vasnprintf respectively,
234 * and your system library does not provide them. They are all small
235 * wrapper routines around portable_vsnprintf. Defining any of the four
236 * NEED_V?ASN?PRINTF macros automatically turns off NEED_SNPRINTF_ONLY
237 * and turns on PREFER_PORTABLE_SNPRINTF.
239 * Watch for name conflicts with the system library if these routines
240 * are already present there.
242 * NOTE: vasprintf and vasnprintf routines need va_copy() from stdarg.h, as
243 * specified by C99, to be able to traverse the same list of arguments twice.
244 * I don't know of any other standard and portable way of achieving the same.
245 * With some versions of gcc you may use __va_copy(). You might even get away
246 * with "ap2 = ap", in this case you must not call va_end(ap2) !
247 * #define va_copy(ap2,ap) ap2 = ap
249 /* #define NEED_ASPRINTF */
250 /* #define NEED_ASNPRINTF */
251 /* #define NEED_VASPRINTF */
252 /* #define NEED_VASNPRINTF */
255 /* Define the following macros if desired:
256 * SOLARIS_COMPATIBLE, SOLARIS_BUG_COMPATIBLE,
257 * HPUX_COMPATIBLE, HPUX_BUG_COMPATIBLE, LINUX_COMPATIBLE,
258 * DIGITAL_UNIX_COMPATIBLE, DIGITAL_UNIX_BUG_COMPATIBLE,
259 * PERL_COMPATIBLE, PERL_BUG_COMPATIBLE,
261 * - For portable applications it is best not to rely on peculiarities
262 * of a given implementation so it may be best not to define any
263 * of the macros that select compatibility and to avoid features
264 * that vary among the systems.
266 * - Selecting compatibility with more than one operating system
267 * is not strictly forbidden but is not recommended.
269 * - 'x'_BUG_COMPATIBLE implies 'x'_COMPATIBLE .
271 * - 'x'_COMPATIBLE refers to (and enables) a behaviour that is
272 * documented in a sprintf man page on a given operating system
273 * and actually adhered to by the system's sprintf (but not on
274 * most other operating systems). It may also refer to and enable
275 * a behaviour that is declared 'undefined' or 'implementation specific'
276 * in the man page but a given implementation behaves predictably
279 * - 'x'_BUG_COMPATIBLE refers to (and enables) a behaviour of system's sprintf
280 * that contradicts the sprintf man page on the same operating system.
282 * - I do not claim that the 'x'_COMPATIBLE and 'x'_BUG_COMPATIBLE
283 * conditionals take into account all idiosyncrasies of a particular
284 * implementation, there may be other incompatibilities.
288 /* ============================================= */
289 /* NO USER SERVICABLE PARTS FOLLOWING THIS POINT */
290 /* ============================================= */
292 #define PORTABLE_SNPRINTF_VERSION_MAJOR 2
293 #define PORTABLE_SNPRINTF_VERSION_MINOR 2
295 #if defined(NEED_ASPRINTF) || defined(NEED_ASNPRINTF) || defined(NEED_VASPRINTF) || defined(NEED_VASNPRINTF)
296 # if defined(NEED_SNPRINTF_ONLY)
297 # undef NEED_SNPRINTF_ONLY
299 # if !defined(PREFER_PORTABLE_SNPRINTF)
300 # define PREFER_PORTABLE_SNPRINTF
304 #if defined(SOLARIS_BUG_COMPATIBLE) && !defined(SOLARIS_COMPATIBLE)
305 #define SOLARIS_COMPATIBLE
308 #if defined(HPUX_BUG_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
309 #define HPUX_COMPATIBLE
312 #if defined(DIGITAL_UNIX_BUG_COMPATIBLE) && !defined(DIGITAL_UNIX_COMPATIBLE)
313 #define DIGITAL_UNIX_COMPATIBLE
316 #if defined(PERL_BUG_COMPATIBLE) && !defined(PERL_COMPATIBLE)
317 #define PERL_COMPATIBLE
320 #if defined(LINUX_BUG_COMPATIBLE) && !defined(LINUX_COMPATIBLE)
321 #define LINUX_COMPATIBLE
324 #include "src/portable.h" /* to get a working stdarg.h */
326 #include <sys/types.h>
339 #define isdigit(c) ((c) >= '0' && (c) <= '9')
341 /* For copying strings longer or equal to 'breakeven_point'
342 * it is more efficient to call memcpy() than to do it inline.
343 * The value depends mostly on the processor architecture,
344 * but also on the compiler and its optimization capabilities.
345 * The value is not critical, some small value greater than zero
346 * will be just fine if you don't care to squeeze every drop
347 * of performance out of the code.
349 * Small values favor memcpy, large values favor inline code.
351 #if defined(__alpha__) || defined(__alpha)
352 # define breakeven_point 2 /* AXP (DEC Alpha) - gcc or cc or egcs */
354 #if defined(__i386__) || defined(__i386)
355 # define breakeven_point 12 /* Intel Pentium/Linux - gcc 2.96 */
358 # define breakeven_point 10 /* HP-PA - gcc */
360 #if defined(__sparc__) || defined(__sparc)
361 # define breakeven_point 33 /* Sun Sparc 5 - gcc 2.8.1 */
364 /* some other values of possible interest: */
365 /* #define breakeven_point 8 *//* VAX 4000 - vaxc */
366 /* #define breakeven_point 19 *//* VAX 4000 - gcc 2.7.0 */
368 #ifndef breakeven_point
369 # define breakeven_point 6 /* some reasonable one-size-fits-all value */
372 #define fast_memcpy(d,s,n) \
373 { size_t nn = (size_t)(n); \
374 if (nn >= breakeven_point) memcpy((d), (s), nn); \
375 else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
376 char *dd; const char *ss; \
377 for (ss=(s), dd=(d); nn>0; nn--) *dd++ = *ss++; } }
379 #define fast_memset(d,c,n) \
380 { size_t nn = (size_t)(n); \
381 if (nn >= breakeven_point) memset((d), (int)(c), nn); \
382 else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
383 char *dd; const int cc=(int)(c); \
384 for (dd=(d); nn>0; nn--) *dd++ = cc; } }
389 #if defined(NEED_ASPRINTF)
390 int asprintf(char **ptr, const char *fmt, /*args */ ...);
392 #if defined(NEED_VASPRINTF)
393 int vasprintf(char **ptr, const char *fmt, va_list ap);
396 #if defined(NEED_ASNPRINTF)
397 int asnprintf(char **ptr, size_t str_m, const char *fmt, /*args */ ...);
399 #if defined(NEED_VASNPRINTF)
400 int vasnprintf(char **ptr, size_t str_m, const char *fmt, va_list ap);
403 #if defined(HAVE_SNPRINTF)
404 /* declare our portable snprintf routine under name portable_snprintf */
405 /* declare our portable vsnprintf routine under name portable_vsnprintf */
406 # if defined(_MSC_VER) && (_MSC_VER >= 1400)
407 # define portable_snprintf _snprintf
408 # define portable_vsnprintf vsnprintf
410 # define portable_snprintf snprintf
411 # define portable_vsnprintf vsnprintf
414 /* declare our portable routines under names snprintf and vsnprintf */
415 #define portable_snprintf snprintf
416 #if !defined(NEED_SNPRINTF_ONLY)
417 #define portable_vsnprintf vsnprintf
421 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
422 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args */
424 #if !defined(NEED_SNPRINTF_ONLY)
425 int portable_vsnprintf(char *str, size_t str_m, const char *fmt,
430 /* FIXME: better place */
431 #include "xbt/sysdep.h"
437 snprintf.c, v2.2: Mark Martinec, <mark.martinec@ijs.si>
438 snprintf.c, v2.2: Copyright 1999, Mark Martinec. Frontier Artistic License applies.
439 snprintf.c, v2.2: http://www.ijs.si/software/snprintf
442 #if defined(NEED_ASPRINTF)
443 int asprintf(char **ptr, const char *fmt, /*args */ ...)
450 va_start(ap, fmt); /* measure the required size */
451 str_l = portable_vsnprintf(NULL, (size_t) 0, fmt, ap);
453 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
454 *ptr = (char *) xbt_malloc(str_m = (size_t) str_l + 1);
461 str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
463 assert(str_l2 == str_l);
469 #if defined(NEED_VASPRINTF)
470 int vasprintf(char **ptr, const char *fmt, va_list ap)
478 va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */
479 str_l = portable_vsnprintf(NULL, (size_t) 0, fmt, ap2); /*get required size */
482 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
483 *ptr = (char *) xbt_malloc(str_m = (size_t) str_l + 1);
488 int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
489 assert(str_l2 == str_l);
495 #if defined(NEED_ASNPRINTF)
496 int asnprintf(char **ptr, size_t str_m, const char *fmt, /*args */ ...)
502 va_start(ap, fmt); /* measure the required size */
503 str_l = portable_vsnprintf(NULL, (size_t) 0, fmt, ap);
505 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
506 if ((size_t) str_l + 1 < str_m)
507 str_m = (size_t) str_l + 1; /* truncate */
508 /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
509 if (str_m == 0) { /* not interested in resulting string, just return size */
511 *ptr = (char *) xbt_malloc(str_m);
518 str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
520 assert(str_l2 == str_l);
527 #if defined(NEED_VASNPRINTF)
528 int vasnprintf(char **ptr, size_t str_m, const char *fmt, va_list ap)
535 va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */
536 str_l = portable_vsnprintf(NULL, (size_t) 0, fmt, ap2); /*get required size */
539 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
540 if ((size_t) str_l + 1 < str_m)
541 str_m = (size_t) str_l + 1; /* truncate */
542 /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
543 if (str_m == 0) { /* not interested in resulting string, just return size */
545 *ptr = (char *) xbt_malloc(str_m);
550 int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
551 assert(str_l2 == str_l);
559 * If the system does have snprintf and the portable routine is not
560 * specifically required, this module produces no code for snprintf/vsnprintf.
562 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
564 #if !defined(NEED_SNPRINTF_ONLY)
565 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args */
572 str_l = portable_vsnprintf(str, str_m, fmt, ap);
578 #if defined(NEED_SNPRINTF_ONLY)
579 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args */
583 int portable_vsnprintf(char *str, size_t str_m, const char *fmt,
588 #if defined(NEED_SNPRINTF_ONLY)
594 /* In contrast with POSIX, the ISO C99 now says
595 * that str can be NULL and str_m can be 0.
596 * This is more useful than the old: if (str_m < 1) return -1; */
598 #if defined(NEED_SNPRINTF_ONLY)
605 /* if (str_l < str_m) str[str_l++] = *p++; -- this would be sufficient */
606 /* but the following code achieves better performance for cases
607 * where format string is long and contains few conversions */
608 const char *q = strchr(p + 1, '%');
609 size_t n = !q ? strlen(p) : (q - p);
611 size_t avail = str_m - str_l;
612 fast_memcpy(str + str_l, p, (n > avail ? avail : n));
617 const char *starting_p;
618 size_t min_field_width = 0, precision = 0;
619 int zero_padding = 0, precision_specified = 0, justify_left = 0;
620 int alternate_form = 0, force_sign = 0;
621 int space_for_positive = 1; /* If both the ' ' and '+' flags appear,
622 the ' ' flag should be ignored. */
623 char length_modifier = '\0'; /* allowed values: \0, h, l, L */
624 char tmp[32]; /* temporary buffer for simple numeric->string conversion */
626 const char *str_arg; /* string address in case of string argument */
627 size_t str_arg_l; /* natural field width of arg without padding
629 unsigned char uchar_arg;
630 /* unsigned char argument value - only defined for c conversion.
631 N.B. standard explicitly states the char argument for
632 the c conversion is unsigned */
634 size_t number_of_zeros_to_pad = 0;
635 /* number of zeros to be inserted for numeric conversions
636 as required by the precision or minimal field width */
638 size_t zero_padding_insertion_ind = 0;
639 /* index into tmp where zero padding is to be inserted */
641 char fmt_spec = '\0';
642 /* current conversion specifier character */
644 str_arg = credits; /* just to make compiler happy (defined but not used) */
649 while (*p == '0' || *p == '-' || *p == '+' ||
650 *p == ' ' || *p == '#' || *p == '\'') {
660 space_for_positive = 0;
664 /* If both the ' ' and '+' flags appear, the ' ' flag should be ignored */
665 #ifdef PERL_COMPATIBLE
666 /* ... but in Perl the last of ' ' and '+' applies */
667 space_for_positive = 1;
678 /* If the '0' and '-' flags both appear, the '0' flag should be ignored. */
680 /* parse field width */
688 min_field_width = -j;
691 } else if (isdigit((int) (*p))) {
692 /* size_t could be wider than unsigned int;
693 make sure we treat argument like common implementations do */
694 unsigned int uj = *p++ - '0';
695 while (isdigit((int) (*p)))
696 uj = 10 * uj + (unsigned int) (*p++ - '0');
697 min_field_width = uj;
699 /* parse precision */
702 precision_specified = 1;
704 int j = va_arg(ap, int);
709 precision_specified = 0;
712 * Solaris 2.6 man page claims that in this case the precision
713 * should be set to 0. Digital Unix 4.0, HPUX 10 and BSD man page
714 * claim that this case should be treated as unspecified precision,
715 * which is what we do here.
718 } else if (isdigit((int) (*p))) {
719 /* size_t could be wider than unsigned int;
720 make sure we treat argument like common implementations do */
721 unsigned int uj = *p++ - '0';
722 while (isdigit((int) (*p)))
723 uj = 10 * uj + (unsigned int) (*p++ - '0');
727 /* parse 'h', 'l' and 'll' length modifiers */
728 if (*p == 'h' || *p == 'l') {
729 length_modifier = *p;
731 if (length_modifier == 'l' && *p == 'l') { /* double l = long long */
732 #ifdef SNPRINTF_LONGLONG_SUPPORT
733 length_modifier = '2'; /* double l encoded as '2' */
735 length_modifier = 'l'; /* treat it as a single 'l' */
741 /* common synonyms: */
748 length_modifier = 'l';
752 length_modifier = 'l';
756 length_modifier = 'l';
761 /* get parameter value, do initial processing */
763 case '%': /* % behaves similar to 's' regarding flags and field widths */
764 case 'c': /* c behaves similar to 's' regarding flags and field widths */
766 length_modifier = '\0'; /* wint_t and wchar_t not supported */
767 /* the result of zero padding flag with non-numeric conversion specifier */
768 /* is undefined. Solaris and HPUX 10 does zero padding in this case, */
769 /* Digital Unix and Linux does not. */
770 #if !defined(SOLARIS_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
771 zero_padding = 0; /* turn zero padding off for string conversions */
779 int j = va_arg(ap, int);
780 uchar_arg = (unsigned char) j; /* standard demands unsigned char */
781 str_arg = (const char *) &uchar_arg;
785 str_arg = va_arg(ap, const char *);
788 /* make sure not to address string beyond the specified precision !!! */
789 else if (!precision_specified)
790 str_arg_l = strlen(str_arg);
791 /* truncate string if necessary as requested by precision */
792 else if (precision == 0)
795 /* memchr on HP does not like n > 2^31 !!! */
796 char *q = (char *) memchr(str_arg, '\0',
798 0x7fffffff ? precision : 0x7fffffff);
799 str_arg_l = !q ? precision : (q - str_arg);
812 /* NOTE: the u, o, x, X and p conversion specifiers imply
813 the value is unsigned; d implies a signed value */
816 /* 0 if numeric argument is zero (or if pointer is NULL for 'p'),
817 +1 if greater than zero (or nonzero for unsigned arguments),
818 -1 if negative (unsigned argument is never negative) */
821 unsigned int uint_arg = 0;
822 /* only defined for length modifier h, or for no length modifiers */
824 long int long_arg = 0;
825 unsigned long int ulong_arg = 0;
826 /* only defined for length modifier l */
828 void *ptr_arg = NULL;
829 /* pointer argument value -only defined for p conversion */
831 #ifdef SNPRINTF_LONGLONG_SUPPORT
832 long long int long_long_arg = 0;
833 unsigned long long int ulong_long_arg = 0;
834 /* only defined for length modifier ll */
836 if (fmt_spec == 'p') {
837 /* HPUX 10: An l, h, ll or L before any other conversion character
838 * (other than d, i, u, o, x, or X) is ignored.
840 * not specified, but seems to behave as HPUX does.
841 * Solaris: If an h, l, or L appears before any other conversion
842 * specifier (other than d, i, u, o, x, or X), the behavior
843 * is undefined. (Actually %hp converts only 16-bits of address
844 * and %llp treats address as 64-bit data which is incompatible
845 * with (void *) argument on a 32-bit system).
847 #ifdef SOLARIS_COMPATIBLE
848 # ifdef SOLARIS_BUG_COMPATIBLE
849 /* keep length modifiers even if it represents 'll' */
851 if (length_modifier == '2')
852 length_modifier = '\0';
855 length_modifier = '\0';
857 ptr_arg = va_arg(ap, void *);
860 } else if (fmt_spec == 'd') { /* signed */
861 switch (length_modifier) {
864 /* It is non-portable to specify a second argument of char or short
865 * to va_arg, because arguments seen by the called function
866 * are not char or short. C converts char and short arguments
867 * to int before passing them to a function.
869 int_arg = va_arg(ap, int);
872 else if (int_arg < 0)
876 long_arg = va_arg(ap, long int);
879 else if (long_arg < 0)
882 #ifdef SNPRINTF_LONGLONG_SUPPORT
884 long_long_arg = va_arg(ap, long long int);
885 if (long_long_arg > 0)
887 else if (long_long_arg < 0)
892 } else { /* unsigned */
893 switch (length_modifier) {
896 uint_arg = va_arg(ap, unsigned int);
901 ulong_arg = va_arg(ap, unsigned long int);
905 #ifdef SNPRINTF_LONGLONG_SUPPORT
907 ulong_long_arg = va_arg(ap, unsigned long long int);
917 * For d, i, u, o, x, and X conversions, if precision is specified,
918 * the '0' flag should be ignored. This is so with Solaris 2.6,
919 * Digital UNIX 4.0, HPUX 10, Linux, FreeBSD, NetBSD; but not with Perl.
921 #ifndef PERL_COMPATIBLE
922 if (precision_specified)
925 if (fmt_spec == 'd') {
926 if (force_sign && arg_sign >= 0)
927 tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
928 /* leave negative numbers for sprintf to handle,
929 to avoid handling tricky cases like (short int)(-32768) */
930 #ifdef LINUX_COMPATIBLE
931 } else if (fmt_spec == 'p' && force_sign && arg_sign > 0) {
932 tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
934 } else if (alternate_form) {
935 if (arg_sign != 0 && (fmt_spec == 'x' || fmt_spec == 'X')) {
936 tmp[str_arg_l++] = '0';
937 tmp[str_arg_l++] = fmt_spec;
939 /* alternate form should have no effect for p conversion, but ... */
940 #ifdef HPUX_COMPATIBLE
941 else if (fmt_spec == 'p'
942 /* HPUX 10: for an alternate form of p conversion,
943 * a nonzero result is prefixed by 0x. */
944 #ifndef HPUX_BUG_COMPATIBLE
945 /* Actually it uses 0x prefix even for a zero value. */
949 tmp[str_arg_l++] = '0';
950 tmp[str_arg_l++] = 'x';
954 zero_padding_insertion_ind = str_arg_l;
955 if (!precision_specified)
956 precision = 1; /* default precision is 1 */
957 if (precision == 0 && arg_sign == 0
958 #if defined(HPUX_BUG_COMPATIBLE) || defined(LINUX_COMPATIBLE)
960 /* HPUX 10 man page claims: With conversion character p the result of
961 * converting a zero value with a precision of zero is a null string.
962 * Actually HP returns all zeroes, and Linux returns "(nil)". */
965 /* converted to null string */
966 /* When zero value is formatted with an explicit precision 0,
967 the resulting formatted string is empty (d, i, u, o, x, X, p). */
971 f[f_l++] = '%'; /* construct a simple format string for sprintf */
972 if (!length_modifier) {
973 } else if (length_modifier == '2') {
977 f[f_l++] = length_modifier;
981 str_arg_l += sprintf(tmp + str_arg_l, f, ptr_arg);
982 else if (fmt_spec == 'd') { /* signed */
983 switch (length_modifier) {
986 str_arg_l += sprintf(tmp + str_arg_l, f, int_arg);
989 str_arg_l += sprintf(tmp + str_arg_l, f, long_arg);
991 #ifdef SNPRINTF_LONGLONG_SUPPORT
993 str_arg_l += sprintf(tmp + str_arg_l, f, long_long_arg);
997 } else { /* unsigned */
998 switch (length_modifier) {
1001 str_arg_l += sprintf(tmp + str_arg_l, f, uint_arg);
1004 str_arg_l += sprintf(tmp + str_arg_l, f, ulong_arg);
1006 #ifdef SNPRINTF_LONGLONG_SUPPORT
1008 str_arg_l += sprintf(tmp + str_arg_l, f, ulong_long_arg);
1013 /* include the optional minus sign and possible "0x"
1014 in the region before the zero padding insertion point */
1015 if (zero_padding_insertion_ind < str_arg_l &&
1016 tmp[zero_padding_insertion_ind] == '-') {
1017 zero_padding_insertion_ind++;
1019 if (zero_padding_insertion_ind + 1 < str_arg_l &&
1020 tmp[zero_padding_insertion_ind] == '0' &&
1021 (tmp[zero_padding_insertion_ind + 1] == 'x' ||
1022 tmp[zero_padding_insertion_ind + 1] == 'X')) {
1023 zero_padding_insertion_ind += 2;
1027 size_t num_of_digits = str_arg_l - zero_padding_insertion_ind;
1028 if (alternate_form && fmt_spec == 'o'
1029 #ifdef HPUX_COMPATIBLE /* ("%#.o",0) -> "" */
1032 #ifdef DIGITAL_UNIX_BUG_COMPATIBLE /* ("%#o",0) -> "00" */
1034 /* unless zero is already the first character */
1035 && !(zero_padding_insertion_ind < str_arg_l
1036 && tmp[zero_padding_insertion_ind] == '0')
1038 ) { /* assure leading zero for alternate-form octal numbers */
1039 if (!precision_specified || precision < num_of_digits + 1) {
1040 /* precision is increased to force the first character to be zero,
1041 except if a zero value is formatted with an explicit precision
1043 precision = num_of_digits + 1;
1044 precision_specified = 1;
1047 /* zero padding to specified precision? */
1048 if (num_of_digits < precision)
1049 number_of_zeros_to_pad = precision - num_of_digits;
1051 /* zero padding to specified minimal field width? */
1052 if (!justify_left && zero_padding) {
1053 int n = min_field_width - (str_arg_l + number_of_zeros_to_pad);
1055 number_of_zeros_to_pad += n;
1059 default: /* unrecognized conversion specifier, keep format string as-is */
1060 zero_padding = 0; /* turn zero padding off for non-numeric convers. */
1061 #ifndef DIGITAL_UNIX_COMPATIBLE
1063 min_field_width = 0; /* reset flags */
1065 #if defined(PERL_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1066 /* keep the entire format string unchanged */
1067 str_arg = starting_p;
1068 str_arg_l = p - starting_p;
1069 /* well, not exactly so for Linux, which does something inbetween,
1070 * and I don't feel an urge to imitate it: "%+++++hy" -> "%+y" */
1072 /* discard the unrecognized conversion, just keep *
1073 * the unrecognized conversion character */
1078 str_arg_l++; /* include invalid conversion specifier unchanged
1079 if not at end-of-string */
1083 p++; /* step over the just processed conversion specifier */
1084 /* insert padding to the left as requested by min_field_width;
1085 this does not include the zero padding in case of numerical conversions */
1086 if (!justify_left) { /* left padding with blank or zero */
1087 int n = min_field_width - (str_arg_l + number_of_zeros_to_pad);
1089 if (str_l < str_m) {
1090 int avail = str_m - str_l;
1091 fast_memset(str + str_l, (zero_padding ? '0' : ' '),
1092 (n > avail ? avail : n));
1097 /* zero padding as requested by the precision or by the minimal field width
1098 * for numeric conversions required? */
1099 if (number_of_zeros_to_pad <= 0) {
1100 /* will not copy first part of numeric right now, *
1101 * force it to be copied later in its entirety */
1102 zero_padding_insertion_ind = 0;
1104 /* insert first part of numerics (sign or '0x') before zero padding */
1105 int n = zero_padding_insertion_ind;
1107 if (str_l < str_m) {
1108 int avail = str_m - str_l;
1109 fast_memcpy(str + str_l, str_arg, (n > avail ? avail : n));
1113 /* insert zero padding as requested by the precision or min field width */
1114 n = number_of_zeros_to_pad;
1116 if (str_l < str_m) {
1117 int avail = str_m - str_l;
1118 fast_memset(str + str_l, '0', (n > avail ? avail : n));
1123 /* insert formatted string
1124 * (or as-is conversion specifier for unknown conversions) */
1126 int n = str_arg_l - zero_padding_insertion_ind;
1128 if (str_l < str_m) {
1129 int avail = str_m - str_l;
1130 fast_memcpy(str + str_l, str_arg + zero_padding_insertion_ind,
1131 (n > avail ? avail : n));
1136 /* insert right padding */
1137 if (justify_left) { /* right blank padding to the field width */
1138 int n = min_field_width - (str_arg_l + number_of_zeros_to_pad);
1140 if (str_l < str_m) {
1141 int avail = str_m - str_l;
1142 fast_memset(str + str_l, ' ', (n > avail ? avail : n));
1149 #if defined(NEED_SNPRINTF_ONLY)
1152 if (str_m > 0) { /* make sure the string is null-terminated
1153 even at the expense of overwriting the last character
1154 (shouldn't happen, but just in case) */
1155 str[str_l <= str_m - 1 ? str_l : str_m - 1] = '\0';
1157 /* Return the number of characters formatted (excluding trailing null
1158 * character), that is, the number of characters that would have been
1159 * written to the buffer if it were large enough.
1161 * The value of str_l should be returned, but str_l is of unsigned type
1162 * size_t, and snprintf is int, possibly leading to an undetected
1163 * integer overflow, resulting in a negative return value, which is illegal.
1164 * Both XSH5 and ISO C99 (at least the draft) are silent on this issue.
1165 * Should errno be set to EOVERFLOW and EOF returned in this case???
1172 char *bvprintf(const char *fmt, va_list ap)
1176 if (vasprintf(&res, fmt, ap) < 0) {
1177 /* Do not want to use xbt_die() here, as it uses the logging
1178 * infrastucture and may fail to allocate memory too. */
1179 fprintf(stderr, "bprintf: vasprintf failed. Aborting.\n");
1185 char *bprintf(const char *fmt, ...)
1191 res = bvprintf(fmt, ap);