1 /* Copyright (c) 2005-2010, 2012-2014. 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 "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 { register 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 register char *dd; register const char *ss; \
377 for (ss=(s), dd=(d); nn>0; nn--) *dd++ = *ss++; } }
379 #define fast_memset(d,c,n) \
380 { register 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 register char *dd; register 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 static char credits[] = "\n\
436 @(#)snprintf.c, v2.2: Mark Martinec, <mark.martinec@ijs.si>\n\
437 @(#)snprintf.c, v2.2: Copyright 1999, Mark Martinec. Frontier Artistic License applies.\n\
438 @(#)snprintf.c, v2.2: http://www.ijs.si/software/snprintf/\n";
440 static void __foo__(void)
442 printf("%s", credits);
446 #if defined(NEED_ASPRINTF)
447 int asprintf(char **ptr, const char *fmt, /*args */ ...)
454 va_start(ap, fmt); /* measure the required size */
455 str_l = portable_vsnprintf(NULL, (size_t) 0, fmt, ap);
457 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
458 *ptr = (char *) xbt_malloc(str_m = (size_t) str_l + 1);
465 str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
467 assert(str_l2 == str_l);
473 #if defined(NEED_VASPRINTF)
474 int vasprintf(char **ptr, const char *fmt, va_list ap)
482 va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */
483 str_l = portable_vsnprintf(NULL, (size_t) 0, fmt, ap2); /*get required size */
486 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
487 *ptr = (char *) xbt_malloc(str_m = (size_t) str_l + 1);
492 int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
493 assert(str_l2 == str_l);
499 #if defined(NEED_ASNPRINTF)
500 int asnprintf(char **ptr, size_t str_m, const char *fmt, /*args */ ...)
506 va_start(ap, fmt); /* measure the required size */
507 str_l = portable_vsnprintf(NULL, (size_t) 0, fmt, ap);
509 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
510 if ((size_t) str_l + 1 < str_m)
511 str_m = (size_t) str_l + 1; /* truncate */
512 /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
513 if (str_m == 0) { /* not interested in resulting string, just return size */
515 *ptr = (char *) xbt_malloc(str_m);
522 str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
524 assert(str_l2 == str_l);
531 #if defined(NEED_VASNPRINTF)
532 int vasnprintf(char **ptr, size_t str_m, const char *fmt, va_list ap)
539 va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */
540 str_l = portable_vsnprintf(NULL, (size_t) 0, fmt, ap2); /*get required size */
543 assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */
544 if ((size_t) str_l + 1 < str_m)
545 str_m = (size_t) str_l + 1; /* truncate */
546 /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
547 if (str_m == 0) { /* not interested in resulting string, just return size */
549 *ptr = (char *) xbt_malloc(str_m);
554 int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
555 assert(str_l2 == str_l);
563 * If the system does have snprintf and the portable routine is not
564 * specifically required, this module produces no code for snprintf/vsnprintf.
566 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
568 #if !defined(NEED_SNPRINTF_ONLY)
569 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args */
576 str_l = portable_vsnprintf(str, str_m, fmt, ap);
582 #if defined(NEED_SNPRINTF_ONLY)
583 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args */
587 int portable_vsnprintf(char *str, size_t str_m, const char *fmt,
592 #if defined(NEED_SNPRINTF_ONLY)
598 /* In contrast with POSIX, the ISO C99 now says
599 * that str can be NULL and str_m can be 0.
600 * This is more useful than the old: if (str_m < 1) return -1; */
602 #if defined(NEED_SNPRINTF_ONLY)
609 /* if (str_l < str_m) str[str_l++] = *p++; -- this would be sufficient */
610 /* but the following code achieves better performance for cases
611 * where format string is long and contains few conversions */
612 const char *q = strchr(p + 1, '%');
613 size_t n = !q ? strlen(p) : (q - p);
615 size_t avail = str_m - str_l;
616 fast_memcpy(str + str_l, p, (n > avail ? avail : n));
621 const char *starting_p;
622 size_t min_field_width = 0, precision = 0;
623 int zero_padding = 0, precision_specified = 0, justify_left = 0;
624 int alternate_form = 0, force_sign = 0;
625 int space_for_positive = 1; /* If both the ' ' and '+' flags appear,
626 the ' ' flag should be ignored. */
627 char length_modifier = '\0'; /* allowed values: \0, h, l, L */
628 char tmp[32]; /* temporary buffer for simple numeric->string conversion */
630 const char *str_arg; /* string address in case of string argument */
631 size_t str_arg_l; /* natural field width of arg without padding
633 unsigned char uchar_arg;
634 /* unsigned char argument value - only defined for c conversion.
635 N.B. standard explicitly states the char argument for
636 the c conversion is unsigned */
638 size_t number_of_zeros_to_pad = 0;
639 /* number of zeros to be inserted for numeric conversions
640 as required by the precision or minimal field width */
642 size_t zero_padding_insertion_ind = 0;
643 /* index into tmp where zero padding is to be inserted */
645 char fmt_spec = '\0';
646 /* current conversion specifier character */
648 str_arg = credits; /* just to make compiler happy (defined but not used) */
653 while (*p == '0' || *p == '-' || *p == '+' ||
654 *p == ' ' || *p == '#' || *p == '\'') {
664 space_for_positive = 0;
668 /* If both the ' ' and '+' flags appear, the ' ' flag should be ignored */
669 #ifdef PERL_COMPATIBLE
670 /* ... but in Perl the last of ' ' and '+' applies */
671 space_for_positive = 1;
682 /* If the '0' and '-' flags both appear, the '0' flag should be ignored. */
684 /* parse field width */
692 min_field_width = -j;
695 } else if (isdigit((int) (*p))) {
696 /* size_t could be wider than unsigned int;
697 make sure we treat argument like common implementations do */
698 unsigned int uj = *p++ - '0';
699 while (isdigit((int) (*p)))
700 uj = 10 * uj + (unsigned int) (*p++ - '0');
701 min_field_width = uj;
703 /* parse precision */
706 precision_specified = 1;
708 int j = va_arg(ap, int);
713 precision_specified = 0;
716 * Solaris 2.6 man page claims that in this case the precision
717 * should be set to 0. Digital Unix 4.0, HPUX 10 and BSD man page
718 * claim that this case should be treated as unspecified precision,
719 * which is what we do here.
722 } else if (isdigit((int) (*p))) {
723 /* size_t could be wider than unsigned int;
724 make sure we treat argument like common implementations do */
725 unsigned int uj = *p++ - '0';
726 while (isdigit((int) (*p)))
727 uj = 10 * uj + (unsigned int) (*p++ - '0');
731 /* parse 'h', 'l' and 'll' length modifiers */
732 if (*p == 'h' || *p == 'l') {
733 length_modifier = *p;
735 if (length_modifier == 'l' && *p == 'l') { /* double l = long long */
736 #ifdef SNPRINTF_LONGLONG_SUPPORT
737 length_modifier = '2'; /* double l encoded as '2' */
739 length_modifier = 'l'; /* treat it as a single 'l' */
745 /* common synonyms: */
752 length_modifier = 'l';
756 length_modifier = 'l';
760 length_modifier = 'l';
765 /* get parameter value, do initial processing */
767 case '%': /* % behaves similar to 's' regarding flags and field widths */
768 case 'c': /* c behaves similar to 's' regarding flags and field widths */
770 length_modifier = '\0'; /* wint_t and wchar_t not supported */
771 /* the result of zero padding flag with non-numeric conversion specifier */
772 /* is undefined. Solaris and HPUX 10 does zero padding in this case, */
773 /* Digital Unix and Linux does not. */
774 #if !defined(SOLARIS_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
775 zero_padding = 0; /* turn zero padding off for string conversions */
783 int j = va_arg(ap, int);
784 uchar_arg = (unsigned char) j; /* standard demands unsigned char */
785 str_arg = (const char *) &uchar_arg;
789 str_arg = va_arg(ap, const char *);
792 /* make sure not to address string beyond the specified precision !!! */
793 else if (!precision_specified)
794 str_arg_l = strlen(str_arg);
795 /* truncate string if necessary as requested by precision */
796 else if (precision == 0)
799 /* memchr on HP does not like n > 2^31 !!! */
800 char *q = (char *) memchr(str_arg, '\0',
802 0x7fffffff ? precision : 0x7fffffff);
803 str_arg_l = !q ? precision : (q - str_arg);
816 /* NOTE: the u, o, x, X and p conversion specifiers imply
817 the value is unsigned; d implies a signed value */
820 /* 0 if numeric argument is zero (or if pointer is NULL for 'p'),
821 +1 if greater than zero (or nonzero for unsigned arguments),
822 -1 if negative (unsigned argument is never negative) */
825 unsigned int uint_arg = 0;
826 /* only defined for length modifier h, or for no length modifiers */
828 long int long_arg = 0;
829 unsigned long int ulong_arg = 0;
830 /* only defined for length modifier l */
832 void *ptr_arg = NULL;
833 /* pointer argument value -only defined for p conversion */
835 #ifdef SNPRINTF_LONGLONG_SUPPORT
836 long long int long_long_arg = 0;
837 unsigned long long int ulong_long_arg = 0;
838 /* only defined for length modifier ll */
840 if (fmt_spec == 'p') {
841 /* HPUX 10: An l, h, ll or L before any other conversion character
842 * (other than d, i, u, o, x, or X) is ignored.
844 * not specified, but seems to behave as HPUX does.
845 * Solaris: If an h, l, or L appears before any other conversion
846 * specifier (other than d, i, u, o, x, or X), the behavior
847 * is undefined. (Actually %hp converts only 16-bits of address
848 * and %llp treats address as 64-bit data which is incompatible
849 * with (void *) argument on a 32-bit system).
851 #ifdef SOLARIS_COMPATIBLE
852 # ifdef SOLARIS_BUG_COMPATIBLE
853 /* keep length modifiers even if it represents 'll' */
855 if (length_modifier == '2')
856 length_modifier = '\0';
859 length_modifier = '\0';
861 ptr_arg = va_arg(ap, void *);
864 } else if (fmt_spec == 'd') { /* signed */
865 switch (length_modifier) {
868 /* It is non-portable to specify a second argument of char or short
869 * to va_arg, because arguments seen by the called function
870 * are not char or short. C converts char and short arguments
871 * to int before passing them to a function.
873 int_arg = va_arg(ap, int);
876 else if (int_arg < 0)
880 long_arg = va_arg(ap, long int);
883 else if (long_arg < 0)
886 #ifdef SNPRINTF_LONGLONG_SUPPORT
888 long_long_arg = va_arg(ap, long long int);
889 if (long_long_arg > 0)
891 else if (long_long_arg < 0)
896 } else { /* unsigned */
897 switch (length_modifier) {
900 uint_arg = va_arg(ap, unsigned int);
905 ulong_arg = va_arg(ap, unsigned long int);
909 #ifdef SNPRINTF_LONGLONG_SUPPORT
911 ulong_long_arg = va_arg(ap, unsigned long long int);
921 * For d, i, u, o, x, and X conversions, if precision is specified,
922 * the '0' flag should be ignored. This is so with Solaris 2.6,
923 * Digital UNIX 4.0, HPUX 10, Linux, FreeBSD, NetBSD; but not with Perl.
925 #ifndef PERL_COMPATIBLE
926 if (precision_specified)
929 if (fmt_spec == 'd') {
930 if (force_sign && arg_sign >= 0)
931 tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
932 /* leave negative numbers for sprintf to handle,
933 to avoid handling tricky cases like (short int)(-32768) */
934 #ifdef LINUX_COMPATIBLE
935 } else if (fmt_spec == 'p' && force_sign && arg_sign > 0) {
936 tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
938 } else if (alternate_form) {
939 if (arg_sign != 0 && (fmt_spec == 'x' || fmt_spec == 'X')) {
940 tmp[str_arg_l++] = '0';
941 tmp[str_arg_l++] = fmt_spec;
943 /* alternate form should have no effect for p conversion, but ... */
944 #ifdef HPUX_COMPATIBLE
945 else if (fmt_spec == 'p'
946 /* HPUX 10: for an alternate form of p conversion,
947 * a nonzero result is prefixed by 0x. */
948 #ifndef HPUX_BUG_COMPATIBLE
949 /* Actually it uses 0x prefix even for a zero value. */
953 tmp[str_arg_l++] = '0';
954 tmp[str_arg_l++] = 'x';
958 zero_padding_insertion_ind = str_arg_l;
959 if (!precision_specified)
960 precision = 1; /* default precision is 1 */
961 if (precision == 0 && arg_sign == 0
962 #if defined(HPUX_BUG_COMPATIBLE) || defined(LINUX_COMPATIBLE)
964 /* HPUX 10 man page claims: With conversion character p the result of
965 * converting a zero value with a precision of zero is a null string.
966 * Actually HP returns all zeroes, and Linux returns "(nil)". */
969 /* converted to null string */
970 /* When zero value is formatted with an explicit precision 0,
971 the resulting formatted string is empty (d, i, u, o, x, X, p). */
975 f[f_l++] = '%'; /* construct a simple format string for sprintf */
976 if (!length_modifier) {
977 } else if (length_modifier == '2') {
981 f[f_l++] = length_modifier;
985 str_arg_l += sprintf(tmp + str_arg_l, f, ptr_arg);
986 else if (fmt_spec == 'd') { /* signed */
987 switch (length_modifier) {
990 str_arg_l += sprintf(tmp + str_arg_l, f, int_arg);
993 str_arg_l += sprintf(tmp + str_arg_l, f, long_arg);
995 #ifdef SNPRINTF_LONGLONG_SUPPORT
997 str_arg_l += sprintf(tmp + str_arg_l, f, long_long_arg);
1001 } else { /* unsigned */
1002 switch (length_modifier) {
1005 str_arg_l += sprintf(tmp + str_arg_l, f, uint_arg);
1008 str_arg_l += sprintf(tmp + str_arg_l, f, ulong_arg);
1010 #ifdef SNPRINTF_LONGLONG_SUPPORT
1012 str_arg_l += sprintf(tmp + str_arg_l, f, ulong_long_arg);
1017 /* include the optional minus sign and possible "0x"
1018 in the region before the zero padding insertion point */
1019 if (zero_padding_insertion_ind < str_arg_l &&
1020 tmp[zero_padding_insertion_ind] == '-') {
1021 zero_padding_insertion_ind++;
1023 if (zero_padding_insertion_ind + 1 < str_arg_l &&
1024 tmp[zero_padding_insertion_ind] == '0' &&
1025 (tmp[zero_padding_insertion_ind + 1] == 'x' ||
1026 tmp[zero_padding_insertion_ind + 1] == 'X')) {
1027 zero_padding_insertion_ind += 2;
1031 size_t num_of_digits = str_arg_l - zero_padding_insertion_ind;
1032 if (alternate_form && fmt_spec == 'o'
1033 #ifdef HPUX_COMPATIBLE /* ("%#.o",0) -> "" */
1036 #ifdef DIGITAL_UNIX_BUG_COMPATIBLE /* ("%#o",0) -> "00" */
1038 /* unless zero is already the first character */
1039 && !(zero_padding_insertion_ind < str_arg_l
1040 && tmp[zero_padding_insertion_ind] == '0')
1042 ) { /* assure leading zero for alternate-form octal numbers */
1043 if (!precision_specified || precision < num_of_digits + 1) {
1044 /* precision is increased to force the first character to be zero,
1045 except if a zero value is formatted with an explicit precision
1047 precision = num_of_digits + 1;
1048 precision_specified = 1;
1051 /* zero padding to specified precision? */
1052 if (num_of_digits < precision)
1053 number_of_zeros_to_pad = precision - num_of_digits;
1055 /* zero padding to specified minimal field width? */
1056 if (!justify_left && zero_padding) {
1057 int n = min_field_width - (str_arg_l + number_of_zeros_to_pad);
1059 number_of_zeros_to_pad += n;
1063 default: /* unrecognized conversion specifier, keep format string as-is */
1064 zero_padding = 0; /* turn zero padding off for non-numeric convers. */
1065 #ifndef DIGITAL_UNIX_COMPATIBLE
1067 min_field_width = 0; /* reset flags */
1069 #if defined(PERL_COMPATIBLE) || defined(LINUX_COMPATIBLE)
1070 /* keep the entire format string unchanged */
1071 str_arg = starting_p;
1072 str_arg_l = p - starting_p;
1073 /* well, not exactly so for Linux, which does something inbetween,
1074 * and I don't feel an urge to imitate it: "%+++++hy" -> "%+y" */
1076 /* discard the unrecognized conversion, just keep *
1077 * the unrecognized conversion character */
1082 str_arg_l++; /* include invalid conversion specifier unchanged
1083 if not at end-of-string */
1087 p++; /* step over the just processed conversion specifier */
1088 /* insert padding to the left as requested by min_field_width;
1089 this does not include the zero padding in case of numerical conversions */
1090 if (!justify_left) { /* left padding with blank or zero */
1091 int n = min_field_width - (str_arg_l + number_of_zeros_to_pad);
1093 if (str_l < str_m) {
1094 int avail = str_m - str_l;
1095 fast_memset(str + str_l, (zero_padding ? '0' : ' '),
1096 (n > avail ? avail : n));
1101 /* zero padding as requested by the precision or by the minimal field width
1102 * for numeric conversions required? */
1103 if (number_of_zeros_to_pad <= 0) {
1104 /* will not copy first part of numeric right now, *
1105 * force it to be copied later in its entirety */
1106 zero_padding_insertion_ind = 0;
1108 /* insert first part of numerics (sign or '0x') before zero padding */
1109 int n = zero_padding_insertion_ind;
1111 if (str_l < str_m) {
1112 int avail = str_m - str_l;
1113 fast_memcpy(str + str_l, str_arg, (n > avail ? avail : n));
1117 /* insert zero padding as requested by the precision or min field width */
1118 n = number_of_zeros_to_pad;
1120 if (str_l < str_m) {
1121 int avail = str_m - str_l;
1122 fast_memset(str + str_l, '0', (n > avail ? avail : n));
1127 /* insert formatted string
1128 * (or as-is conversion specifier for unknown conversions) */
1130 int n = str_arg_l - zero_padding_insertion_ind;
1132 if (str_l < str_m) {
1133 int avail = str_m - str_l;
1134 fast_memcpy(str + str_l, str_arg + zero_padding_insertion_ind,
1135 (n > avail ? avail : n));
1140 /* insert right padding */
1141 if (justify_left) { /* right blank padding to the field width */
1142 int n = min_field_width - (str_arg_l + number_of_zeros_to_pad);
1144 if (str_l < str_m) {
1145 int avail = str_m - str_l;
1146 fast_memset(str + str_l, ' ', (n > avail ? avail : n));
1153 #if defined(NEED_SNPRINTF_ONLY)
1156 if (str_m > 0) { /* make sure the string is null-terminated
1157 even at the expense of overwriting the last character
1158 (shouldn't happen, but just in case) */
1159 str[str_l <= str_m - 1 ? str_l : str_m - 1] = '\0';
1161 /* Return the number of characters formatted (excluding trailing null
1162 * character), that is, the number of characters that would have been
1163 * written to the buffer if it were large enough.
1165 * The value of str_l should be returned, but str_l is of unsigned type
1166 * size_t, and snprintf is int, possibly leading to an undetected
1167 * integer overflow, resulting in a negative return value, which is illegal.
1168 * Both XSH5 and ISO C99 (at least the draft) are silent on this issue.
1169 * Should errno be set to EOVERFLOW and EOF returned in this case???
1176 char *bvprintf(const char *fmt, va_list ap)
1180 if (vasprintf(&res, fmt, ap) < 0) {
1181 /* Do not want to use xbt_die() here, as it uses the logging
1182 * infrastucture and may fail to allocate memory too. */
1183 fprintf(stderr, "bprintf: vasprintf failed. Aborting.\n");
1189 char *bprintf(const char *fmt, ...)
1195 res = bvprintf(fmt, ap);