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"
435 /* MPOQUET FIXME: the __foo__ function generates a warning on clang 3.7.0
436 MPOQUET FIXME: the credits is unused if __foo__ is commented*/
440 snprintf.c, v2.2: Mark Martinec, <mark.martinec@ijs.si>
441 snprintf.c, v2.2: Copyright 1999, Mark Martinec. Frontier Artistic License applies.
442 snprintf.c, v2.2: http://www.ijs.si/software/snprintf
445 #if defined(NEED_ASPRINTF)
446 int asprintf(char **ptr, const char *fmt, /*args */ ...)
453 va_start(ap, fmt); /* measure the required size */
454 str_l = portable_vsnprintf(NULL, (size_t) 0, fmt, ap);
456 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
457 *ptr = (char *) xbt_malloc(str_m = (size_t) str_l + 1);
464 str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
466 assert(str_l2 == str_l);
472 #if defined(NEED_VASPRINTF)
473 int vasprintf(char **ptr, const char *fmt, va_list ap)
481 va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */
482 str_l = portable_vsnprintf(NULL, (size_t) 0, fmt, ap2); /*get required size */
485 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
486 *ptr = (char *) xbt_malloc(str_m = (size_t) str_l + 1);
491 int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
492 assert(str_l2 == str_l);
498 #if defined(NEED_ASNPRINTF)
499 int asnprintf(char **ptr, size_t str_m, const char *fmt, /*args */ ...)
505 va_start(ap, fmt); /* measure the required size */
506 str_l = portable_vsnprintf(NULL, (size_t) 0, fmt, ap);
508 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
509 if ((size_t) str_l + 1 < str_m)
510 str_m = (size_t) str_l + 1; /* truncate */
511 /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
512 if (str_m == 0) { /* not interested in resulting string, just return size */
514 *ptr = (char *) xbt_malloc(str_m);
521 str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
523 assert(str_l2 == str_l);
530 #if defined(NEED_VASNPRINTF)
531 int vasnprintf(char **ptr, size_t str_m, const char *fmt, va_list ap)
538 va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */
539 str_l = portable_vsnprintf(NULL, (size_t) 0, fmt, ap2); /*get required size */
542 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
543 if ((size_t) str_l + 1 < str_m)
544 str_m = (size_t) str_l + 1; /* truncate */
545 /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
546 if (str_m == 0) { /* not interested in resulting string, just return size */
548 *ptr = (char *) xbt_malloc(str_m);
553 int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
554 assert(str_l2 == str_l);
562 * If the system does have snprintf and the portable routine is not
563 * specifically required, this module produces no code for snprintf/vsnprintf.
565 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
567 #if !defined(NEED_SNPRINTF_ONLY)
568 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args */
575 str_l = portable_vsnprintf(str, str_m, fmt, ap);
581 #if defined(NEED_SNPRINTF_ONLY)
582 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args */
586 int portable_vsnprintf(char *str, size_t str_m, const char *fmt,
591 #if defined(NEED_SNPRINTF_ONLY)
597 /* In contrast with POSIX, the ISO C99 now says
598 * that str can be NULL and str_m can be 0.
599 * This is more useful than the old: if (str_m < 1) return -1; */
601 #if defined(NEED_SNPRINTF_ONLY)
608 /* if (str_l < str_m) str[str_l++] = *p++; -- this would be sufficient */
609 /* but the following code achieves better performance for cases
610 * where format string is long and contains few conversions */
611 const char *q = strchr(p + 1, '%');
612 size_t n = !q ? strlen(p) : (q - p);
614 size_t avail = str_m - str_l;
615 fast_memcpy(str + str_l, p, (n > avail ? avail : n));
620 const char *starting_p;
621 size_t min_field_width = 0, precision = 0;
622 int zero_padding = 0, precision_specified = 0, justify_left = 0;
623 int alternate_form = 0, force_sign = 0;
624 int space_for_positive = 1; /* If both the ' ' and '+' flags appear,
625 the ' ' flag should be ignored. */
626 char length_modifier = '\0'; /* allowed values: \0, h, l, L */
627 char tmp[32]; /* temporary buffer for simple numeric->string conversion */
629 const char *str_arg; /* string address in case of string argument */
630 size_t str_arg_l; /* natural field width of arg without padding
632 unsigned char uchar_arg;
633 /* unsigned char argument value - only defined for c conversion.
634 N.B. standard explicitly states the char argument for
635 the c conversion is unsigned */
637 size_t number_of_zeros_to_pad = 0;
638 /* number of zeros to be inserted for numeric conversions
639 as required by the precision or minimal field width */
641 size_t zero_padding_insertion_ind = 0;
642 /* index into tmp where zero padding is to be inserted */
644 char fmt_spec = '\0';
645 /* current conversion specifier character */
647 str_arg = credits; /* just to make compiler happy (defined but not used) */
652 while (*p == '0' || *p == '-' || *p == '+' ||
653 *p == ' ' || *p == '#' || *p == '\'') {
663 space_for_positive = 0;
667 /* If both the ' ' and '+' flags appear, the ' ' flag should be ignored */
668 #ifdef PERL_COMPATIBLE
669 /* ... but in Perl the last of ' ' and '+' applies */
670 space_for_positive = 1;
681 /* If the '0' and '-' flags both appear, the '0' flag should be ignored. */
683 /* parse field width */
691 min_field_width = -j;
694 } else if (isdigit((int) (*p))) {
695 /* size_t could be wider than unsigned int;
696 make sure we treat argument like common implementations do */
697 unsigned int uj = *p++ - '0';
698 while (isdigit((int) (*p)))
699 uj = 10 * uj + (unsigned int) (*p++ - '0');
700 min_field_width = uj;
702 /* parse precision */
705 precision_specified = 1;
707 int j = va_arg(ap, int);
712 precision_specified = 0;
715 * Solaris 2.6 man page claims that in this case the precision
716 * should be set to 0. Digital Unix 4.0, HPUX 10 and BSD man page
717 * claim that this case should be treated as unspecified precision,
718 * which is what we do here.
721 } else if (isdigit((int) (*p))) {
722 /* size_t could be wider than unsigned int;
723 make sure we treat argument like common implementations do */
724 unsigned int uj = *p++ - '0';
725 while (isdigit((int) (*p)))
726 uj = 10 * uj + (unsigned int) (*p++ - '0');
730 /* parse 'h', 'l' and 'll' length modifiers */
731 if (*p == 'h' || *p == 'l') {
732 length_modifier = *p;
734 if (length_modifier == 'l' && *p == 'l') { /* double l = long long */
735 #ifdef SNPRINTF_LONGLONG_SUPPORT
736 length_modifier = '2'; /* double l encoded as '2' */
738 length_modifier = 'l'; /* treat it as a single 'l' */
744 /* common synonyms: */
751 length_modifier = 'l';
755 length_modifier = 'l';
759 length_modifier = 'l';
764 /* get parameter value, do initial processing */
766 case '%': /* % behaves similar to 's' regarding flags and field widths */
767 case 'c': /* c behaves similar to 's' regarding flags and field widths */
769 length_modifier = '\0'; /* wint_t and wchar_t not supported */
770 /* the result of zero padding flag with non-numeric conversion specifier */
771 /* is undefined. Solaris and HPUX 10 does zero padding in this case, */
772 /* Digital Unix and Linux does not. */
773 #if !defined(SOLARIS_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
774 zero_padding = 0; /* turn zero padding off for string conversions */
782 int j = va_arg(ap, int);
783 uchar_arg = (unsigned char) j; /* standard demands unsigned char */
784 str_arg = (const char *) &uchar_arg;
788 str_arg = va_arg(ap, const char *);
791 /* make sure not to address string beyond the specified precision !!! */
792 else if (!precision_specified)
793 str_arg_l = strlen(str_arg);
794 /* truncate string if necessary as requested by precision */
795 else if (precision == 0)
798 /* memchr on HP does not like n > 2^31 !!! */
799 char *q = (char *) memchr(str_arg, '\0',
801 0x7fffffff ? precision : 0x7fffffff);
802 str_arg_l = !q ? precision : (q - str_arg);
815 /* NOTE: the u, o, x, X and p conversion specifiers imply
816 the value is unsigned; d implies a signed value */
819 /* 0 if numeric argument is zero (or if pointer is NULL for 'p'),
820 +1 if greater than zero (or nonzero for unsigned arguments),
821 -1 if negative (unsigned argument is never negative) */
824 unsigned int uint_arg = 0;
825 /* only defined for length modifier h, or for no length modifiers */
827 long int long_arg = 0;
828 unsigned long int ulong_arg = 0;
829 /* only defined for length modifier l */
831 void *ptr_arg = NULL;
832 /* pointer argument value -only defined for p conversion */
834 #ifdef SNPRINTF_LONGLONG_SUPPORT
835 long long int long_long_arg = 0;
836 unsigned long long int ulong_long_arg = 0;
837 /* only defined for length modifier ll */
839 if (fmt_spec == 'p') {
840 /* HPUX 10: An l, h, ll or L before any other conversion character
841 * (other than d, i, u, o, x, or X) is ignored.
843 * not specified, but seems to behave as HPUX does.
844 * Solaris: If an h, l, or L appears before any other conversion
845 * specifier (other than d, i, u, o, x, or X), the behavior
846 * is undefined. (Actually %hp converts only 16-bits of address
847 * and %llp treats address as 64-bit data which is incompatible
848 * with (void *) argument on a 32-bit system).
850 #ifdef SOLARIS_COMPATIBLE
851 # ifdef SOLARIS_BUG_COMPATIBLE
852 /* keep length modifiers even if it represents 'll' */
854 if (length_modifier == '2')
855 length_modifier = '\0';
858 length_modifier = '\0';
860 ptr_arg = va_arg(ap, void *);
863 } else if (fmt_spec == 'd') { /* signed */
864 switch (length_modifier) {
867 /* It is non-portable to specify a second argument of char or short
868 * to va_arg, because arguments seen by the called function
869 * are not char or short. C converts char and short arguments
870 * to int before passing them to a function.
872 int_arg = va_arg(ap, int);
875 else if (int_arg < 0)
879 long_arg = va_arg(ap, long int);
882 else if (long_arg < 0)
885 #ifdef SNPRINTF_LONGLONG_SUPPORT
887 long_long_arg = va_arg(ap, long long int);
888 if (long_long_arg > 0)
890 else if (long_long_arg < 0)
895 } else { /* unsigned */
896 switch (length_modifier) {
899 uint_arg = va_arg(ap, unsigned int);
904 ulong_arg = va_arg(ap, unsigned long int);
908 #ifdef SNPRINTF_LONGLONG_SUPPORT
910 ulong_long_arg = va_arg(ap, unsigned long long int);
920 * For d, i, u, o, x, and X conversions, if precision is specified,
921 * the '0' flag should be ignored. This is so with Solaris 2.6,
922 * Digital UNIX 4.0, HPUX 10, Linux, FreeBSD, NetBSD; but not with Perl.
924 #ifndef PERL_COMPATIBLE
925 if (precision_specified)
928 if (fmt_spec == 'd') {
929 if (force_sign && arg_sign >= 0)
930 tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
931 /* leave negative numbers for sprintf to handle,
932 to avoid handling tricky cases like (short int)(-32768) */
933 #ifdef LINUX_COMPATIBLE
934 } else if (fmt_spec == 'p' && force_sign && arg_sign > 0) {
935 tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
937 } else if (alternate_form) {
938 if (arg_sign != 0 && (fmt_spec == 'x' || fmt_spec == 'X')) {
939 tmp[str_arg_l++] = '0';
940 tmp[str_arg_l++] = fmt_spec;
942 /* alternate form should have no effect for p conversion, but ... */
943 #ifdef HPUX_COMPATIBLE
944 else if (fmt_spec == 'p'
945 /* HPUX 10: for an alternate form of p conversion,
946 * a nonzero result is prefixed by 0x. */
947 #ifndef HPUX_BUG_COMPATIBLE
948 /* Actually it uses 0x prefix even for a zero value. */
952 tmp[str_arg_l++] = '0';
953 tmp[str_arg_l++] = 'x';
957 zero_padding_insertion_ind = str_arg_l;
958 if (!precision_specified)
959 precision = 1; /* default precision is 1 */
960 if (precision == 0 && arg_sign == 0
961 #if defined(HPUX_BUG_COMPATIBLE) || defined(LINUX_COMPATIBLE)
963 /* HPUX 10 man page claims: With conversion character p the result of
964 * converting a zero value with a precision of zero is a null string.
965 * Actually HP returns all zeroes, and Linux returns "(nil)". */
968 /* converted to null string */
969 /* When zero value is formatted with an explicit precision 0,
970 the resulting formatted string is empty (d, i, u, o, x, X, p). */
974 f[f_l++] = '%'; /* construct a simple format string for sprintf */
975 if (!length_modifier) {
976 } else if (length_modifier == '2') {
980 f[f_l++] = length_modifier;
984 str_arg_l += sprintf(tmp + str_arg_l, f, ptr_arg);
985 else if (fmt_spec == 'd') { /* signed */
986 switch (length_modifier) {
989 str_arg_l += sprintf(tmp + str_arg_l, f, int_arg);
992 str_arg_l += sprintf(tmp + str_arg_l, f, long_arg);
994 #ifdef SNPRINTF_LONGLONG_SUPPORT
996 str_arg_l += sprintf(tmp + str_arg_l, f, long_long_arg);
1000 } else { /* unsigned */
1001 switch (length_modifier) {
1004 str_arg_l += sprintf(tmp + str_arg_l, f, uint_arg);
1007 str_arg_l += sprintf(tmp + str_arg_l, f, ulong_arg);
1009 #ifdef SNPRINTF_LONGLONG_SUPPORT
1011 str_arg_l += sprintf(tmp + str_arg_l, f, ulong_long_arg);
1016 /* include the optional minus sign and possible "0x"
1017 in the region before the zero padding insertion point */
1018 if (zero_padding_insertion_ind < str_arg_l &&
1019 tmp[zero_padding_insertion_ind] == '-') {
1020 zero_padding_insertion_ind++;
1022 if (zero_padding_insertion_ind + 1 < str_arg_l &&
1023 tmp[zero_padding_insertion_ind] == '0' &&
1024 (tmp[zero_padding_insertion_ind + 1] == 'x' ||
1025 tmp[zero_padding_insertion_ind + 1] == 'X')) {
1026 zero_padding_insertion_ind += 2;
1030 size_t num_of_digits = str_arg_l - zero_padding_insertion_ind;
1031 if (alternate_form && fmt_spec == 'o'
1032 #ifdef HPUX_COMPATIBLE /* ("%#.o",0) -> "" */
1035 #ifdef DIGITAL_UNIX_BUG_COMPATIBLE /* ("%#o",0) -> "00" */
1037 /* unless zero is already the first character */
1038 && !(zero_padding_insertion_ind < str_arg_l
1039 && tmp[zero_padding_insertion_ind] == '0')
1041 ) { /* assure leading zero for alternate-form octal numbers */
1042 if (!precision_specified || precision < num_of_digits + 1) {
1043 /* precision is increased to force the first character to be zero,
1044 except if a zero value is formatted with an explicit precision
1046 precision = num_of_digits + 1;
1047 precision_specified = 1;
1050 /* zero padding to specified precision? */
1051 if (num_of_digits < precision)
1052 number_of_zeros_to_pad = precision - num_of_digits;
1054 /* zero padding to specified minimal field width? */
1055 if (!justify_left && zero_padding) {
1056 int n = min_field_width - (str_arg_l + number_of_zeros_to_pad);
1058 number_of_zeros_to_pad += n;
1062 default: /* unrecognized conversion specifier, keep format string as-is */
1063 zero_padding = 0; /* turn zero padding off for non-numeric convers. */
1064 #ifndef DIGITAL_UNIX_COMPATIBLE
1066 min_field_width = 0; /* reset flags */
1068 #if defined(PERL_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1069 /* keep the entire format string unchanged */
1070 str_arg = starting_p;
1071 str_arg_l = p - starting_p;
1072 /* well, not exactly so for Linux, which does something inbetween,
1073 * and I don't feel an urge to imitate it: "%+++++hy" -> "%+y" */
1075 /* discard the unrecognized conversion, just keep *
1076 * the unrecognized conversion character */
1081 str_arg_l++; /* include invalid conversion specifier unchanged
1082 if not at end-of-string */
1086 p++; /* step over the just processed conversion specifier */
1087 /* insert padding to the left as requested by min_field_width;
1088 this does not include the zero padding in case of numerical conversions */
1089 if (!justify_left) { /* left padding with blank or zero */
1090 int n = min_field_width - (str_arg_l + number_of_zeros_to_pad);
1092 if (str_l < str_m) {
1093 int avail = str_m - str_l;
1094 fast_memset(str + str_l, (zero_padding ? '0' : ' '),
1095 (n > avail ? avail : n));
1100 /* zero padding as requested by the precision or by the minimal field width
1101 * for numeric conversions required? */
1102 if (number_of_zeros_to_pad <= 0) {
1103 /* will not copy first part of numeric right now, *
1104 * force it to be copied later in its entirety */
1105 zero_padding_insertion_ind = 0;
1107 /* insert first part of numerics (sign or '0x') before zero padding */
1108 int n = zero_padding_insertion_ind;
1110 if (str_l < str_m) {
1111 int avail = str_m - str_l;
1112 fast_memcpy(str + str_l, str_arg, (n > avail ? avail : n));
1116 /* insert zero padding as requested by the precision or min field width */
1117 n = number_of_zeros_to_pad;
1119 if (str_l < str_m) {
1120 int avail = str_m - str_l;
1121 fast_memset(str + str_l, '0', (n > avail ? avail : n));
1126 /* insert formatted string
1127 * (or as-is conversion specifier for unknown conversions) */
1129 int n = str_arg_l - zero_padding_insertion_ind;
1131 if (str_l < str_m) {
1132 int avail = str_m - str_l;
1133 fast_memcpy(str + str_l, str_arg + zero_padding_insertion_ind,
1134 (n > avail ? avail : n));
1139 /* insert right padding */
1140 if (justify_left) { /* right blank padding to the field width */
1141 int n = min_field_width - (str_arg_l + number_of_zeros_to_pad);
1143 if (str_l < str_m) {
1144 int avail = str_m - str_l;
1145 fast_memset(str + str_l, ' ', (n > avail ? avail : n));
1152 #if defined(NEED_SNPRINTF_ONLY)
1155 if (str_m > 0) { /* make sure the string is null-terminated
1156 even at the expense of overwriting the last character
1157 (shouldn't happen, but just in case) */
1158 str[str_l <= str_m - 1 ? str_l : str_m - 1] = '\0';
1160 /* Return the number of characters formatted (excluding trailing null
1161 * character), that is, the number of characters that would have been
1162 * written to the buffer if it were large enough.
1164 * The value of str_l should be returned, but str_l is of unsigned type
1165 * size_t, and snprintf is int, possibly leading to an undetected
1166 * integer overflow, resulting in a negative return value, which is illegal.
1167 * Both XSH5 and ISO C99 (at least the draft) are silent on this issue.
1168 * Should errno be set to EOVERFLOW and EOF returned in this case???
1175 char *bvprintf(const char *fmt, va_list ap)
1179 if (vasprintf(&res, fmt, ap) < 0) {
1180 /* Do not want to use xbt_die() here, as it uses the logging
1181 * infrastucture and may fail to allocate memory too. */
1182 fprintf(stderr, "bprintf: vasprintf failed. Aborting.\n");
1188 char *bprintf(const char *fmt, ...)
1194 res = bvprintf(fmt, ap);