Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Some new functions to this. Bloatware, here we come.
[simgrid.git] / src / xbt / snprintf.c
1 #include "gras_config.h"
2
3 /*
4  * snprintf.c - a portable implementation of snprintf
5  *
6  * AUTHOR
7  *   Mark Martinec <mark.martinec@ijs.si>, April 1999.
8  *
9  *   Copyright 1999, Mark Martinec. All rights reserved.
10  *
11  * TERMS AND CONDITIONS
12  *   This program is free software; you can redistribute it and/or modify
13  *   it under the terms of the "Frontier Artistic License" which comes
14  *   with this Kit.
15  *
16  *   This program is distributed in the hope that it will be useful,
17  *   but WITHOUT ANY WARRANTY; without even the implied warranty
18  *   of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
19  *   See the Frontier Artistic License for more details.
20  *
21  *   You should have received a copy of the Frontier Artistic License
22  *   with this Kit in the file named LICENSE.txt .
23  *   If not, I'll be glad to provide one.
24  *
25  * FEATURES
26  * - careful adherence to specs regarding flags, field width and precision;
27  * - good performance for large string handling (large format, large
28  *   argument or large paddings). Performance is similar to system's sprintf
29  *   and in several cases significantly better (make sure you compile with
30  *   optimizations turned on, tell the compiler the code is strict ANSI
31  *   if necessary to give it more freedom for optimizations);
32  * - return value semantics per ISO/IEC 9899:1999 ("ISO C99");
33  * - written in standard ISO/ANSI C - requires an ANSI C compiler.
34  *
35  * SUPPORTED CONVERSION SPECIFIERS AND DATA TYPES
36  *
37  * This snprintf only supports the following conversion specifiers:
38  * s, c, d, u, o, x, X, p  (and synonyms: i, D, U, O - see below)
39  * with flags: '-', '+', ' ', '0' and '#'.
40  * An asterisk is supported for field width as well as precision.
41  *
42  * Length modifiers 'h' (short int), 'l' (long int),
43  * and 'll' (long long int) are supported.
44  * NOTE:
45  *   If macro SNPRINTF_LONGLONG_SUPPORT is not defined (default) the
46  *   length modifier 'll' is recognized but treated the same as 'l',
47  *   which may cause argument value truncation! Defining
48  *   SNPRINTF_LONGLONG_SUPPORT requires that your system's sprintf also
49  *   handles length modifier 'll'.  long long int is a language extension
50  *   which may not be portable.
51  *
52  * Conversion of numeric data (conversion specifiers d, u, o, x, X, p)
53  * with length modifiers (none or h, l, ll) is left to the system routine
54  * sprintf, but all handling of flags, field width and precision as well as
55  * c and s conversions is done very carefully by this portable routine.
56  * If a string precision (truncation) is specified (e.g. %.8s) it is
57  * guaranteed the string beyond the specified precision will not be referenced.
58  *
59  * Length modifiers h, l and ll are ignored for c and s conversions (data
60  * types wint_t and wchar_t are not supported).
61  *
62  * The following common synonyms for conversion characters are supported:
63  *   - i is a synonym for d
64  *   - D is a synonym for ld, explicit length modifiers are ignored
65  *   - U is a synonym for lu, explicit length modifiers are ignored
66  *   - O is a synonym for lo, explicit length modifiers are ignored
67  * The D, O and U conversion characters are nonstandard, they are supported
68  * for backward compatibility only, and should not be used for new code.
69  *
70  * The following is specifically NOT supported:
71  *   - flag ' (thousands' grouping character) is recognized but ignored
72  *   - numeric conversion specifiers: f, e, E, g, G and synonym F,
73  *     as well as the new a and A conversion specifiers
74  *   - length modifier 'L' (long double) and 'q' (quad - use 'll' instead)
75  *   - wide character/string conversions: lc, ls, and nonstandard
76  *     synonyms C and S
77  *   - writeback of converted string length: conversion character n
78  *   - the n$ specification for direct reference to n-th argument
79  *   - locales
80  *
81  * It is permitted for str_m to be zero, and it is permitted to specify NULL
82  * pointer for resulting string argument if str_m is zero (as per ISO C99).
83  *
84  * The return value is the number of characters which would be generated
85  * for the given input, excluding the trailing null. If this value
86  * is greater or equal to str_m, not all characters from the result
87  * have been stored in str, output bytes beyond the (str_m-1) -th character
88  * are discarded. If str_m is greater than zero it is guaranteed
89  * the resulting string will be null-terminated.
90  *
91  * NOTE that this matches the ISO C99, OpenBSD, and GNU C library 2.1,
92  * but is different from some older and vendor implementations,
93  * and is also different from XPG, XSH5, SUSv2 specifications.
94  * For historical discussion on changes in the semantics and standards
95  * of snprintf see printf(3) man page in the Linux programmers manual.
96  *
97  * Routines asprintf and vasprintf return a pointer (in the ptr argument)
98  * to a buffer sufficiently large to hold the resulting string. This pointer
99  * should be passed to free(3) to release the allocated storage when it is
100  * no longer needed. If sufficient space cannot be allocated, these functions
101  * will return -1 and set ptr to be a NULL pointer. These two routines are a
102  * GNU C library extensions (glibc).
103  *
104  * Routines asnprintf and vasnprintf are similar to asprintf and vasprintf,
105  * yet, like snprintf and vsnprintf counterparts, will write at most str_m-1
106  * characters into the allocated output string, the last character in the
107  * allocated buffer then gets the terminating null. If the formatted string
108  * length (the return value) is greater than or equal to the str_m argument,
109  * the resulting string was truncated and some of the formatted characters
110  * were discarded. These routines present a handy way to limit the amount
111  * of allocated memory to some sane value.
112  *
113  * AVAILABILITY
114  *   http://www.ijs.si/software/snprintf/
115  *
116  * REVISION HISTORY
117  * 1999-04      V0.9  Mark Martinec
118  *              - initial version, some modifications after comparing printf
119  *                man pages for Digital Unix 4.0, Solaris 2.6 and HPUX 10,
120  *                and checking how Perl handles sprintf (differently!);
121  * 1999-04-09   V1.0  Mark Martinec <mark.martinec@ijs.si>
122  *              - added main test program, fixed remaining inconsistencies,
123  *                added optional (long long int) support;
124  * 1999-04-12   V1.1  Mark Martinec <mark.martinec@ijs.si>
125  *              - support the 'p' conversion (pointer to void);
126  *              - if a string precision is specified
127  *                make sure the string beyond the specified precision
128  *                will not be referenced (e.g. by strlen);
129  * 1999-04-13   V1.2  Mark Martinec <mark.martinec@ijs.si>
130  *              - support synonyms %D=%ld, %U=%lu, %O=%lo;
131  *              - speed up the case of long format string with few conversions;
132  * 1999-06-30   V1.3  Mark Martinec <mark.martinec@ijs.si>
133  *              - fixed runaway loop (eventually crashing when str_l wraps
134  *                beyond 2^31) while copying format string without
135  *                conversion specifiers to a buffer that is too short
136  *                (thanks to Edwin Young <edwiny@autonomy.com> for
137  *                spotting the problem);
138  *              - added macros PORTABLE_SNPRINTF_VERSION_(MAJOR|MINOR)
139  *                to snprintf.h
140  * 2000-02-14   V2.0 (never released) Mark Martinec <mark.martinec@ijs.si>
141  *              - relaxed license terms: The Artistic License now applies.
142  *                You may still apply the GNU GENERAL PUBLIC LICENSE
143  *                as was distributed with previous versions, if you prefer;
144  *              - changed REVISION HISTORY dates to use ISO 8601 date format;
145  *              - added vsnprintf (patch also independently proposed by
146  *                Caolan McNamara 2000-05-04, and Keith M Willenson 2000-06-01)
147  * 2000-06-27   V2.1  Mark Martinec <mark.martinec@ijs.si>
148  *              - removed POSIX check for str_m<1; value 0 for str_m is
149  *                allowed by ISO C99 (and GNU C library 2.1) - (pointed out
150  *                on 2000-05-04 by Caolan McNamara, caolan@ csn dot ul dot ie).
151  *                Besides relaxed license this change in standards adherence
152  *                is the main reason to bump up the major version number;
153  *              - added nonstandard routines asnprintf, vasnprintf, asprintf,
154  *                vasprintf that dynamically allocate storage for the
155  *                resulting string; these routines are not compiled by default,
156  *                see comments where NEED_V?ASN?PRINTF macros are defined;
157  *              - autoconf contributed by Caolan McNamara
158  * 2000-10-06   V2.2  Mark Martinec <mark.martinec@ijs.si>
159  *              - BUG FIX: the %c conversion used a temporary variable
160  *                that was no longer in scope when referenced,
161  *                possibly causing incorrect resulting character;
162  *              - BUG FIX: make precision and minimal field width unsigned
163  *                to handle huge values (2^31 <= n < 2^32) correctly;
164  *                also be more careful in the use of signed/unsigned/size_t
165  *                internal variables - probably more careful than many
166  *                vendor implementations, but there may still be a case
167  *                where huge values of str_m, precision or minimal field
168  *                could cause incorrect behaviour;
169  *              - use separate variables for signed/unsigned arguments,
170  *                and for short/int, long, and long long argument lengths
171  *                to avoid possible incompatibilities on certain
172  *                computer architectures. Also use separate variable
173  *                arg_sign to hold sign of a numeric argument,
174  *                to make code more transparent;
175  *              - some fiddling with zero padding and "0x" to make it
176  *                Linux compatible;
177  *              - systematically use macros fast_memcpy and fast_memset
178  *                instead of case-by-case hand optimization; determine some
179  *                breakeven string lengths for different architectures;
180  *              - terminology change: 'format' -> 'conversion specifier',
181  *                'C9x' -> 'ISO/IEC 9899:1999 ("ISO C99")',
182  *                'alternative form' -> 'alternate form',
183  *                'data type modifier' -> 'length modifier';
184  *              - several comments rephrased and new ones added;
185  *              - make compiler not complain about 'credits' defined but
186  *                not used;
187  */
188
189
190 /* Define HAVE_SNPRINTF if your system already has snprintf and vsnprintf.
191  *
192  * If HAVE_SNPRINTF is defined this module will not produce code for
193  * snprintf and vsnprintf, unless PREFER_PORTABLE_SNPRINTF is defined as well,
194  * causing this portable version of snprintf to be called portable_snprintf
195  * (and portable_vsnprintf).
196  */
197 /* #define HAVE_SNPRINTF */
198
199 /* Define PREFER_PORTABLE_SNPRINTF if your system does have snprintf and
200  * vsnprintf but you would prefer to use the portable routine(s) instead.
201  * In this case the portable routine is declared as portable_snprintf
202  * (and portable_vsnprintf) and a macro 'snprintf' (and 'vsnprintf')
203  * is defined to expand to 'portable_v?snprintf' - see file snprintf.h .
204  * Defining this macro is only useful if HAVE_SNPRINTF is also defined,
205  * but does does no harm if defined nevertheless.
206  */
207 /* #define PREFER_PORTABLE_SNPRINTF */
208
209 /* Define SNPRINTF_LONGLONG_SUPPORT if you want to support
210  * data type (long long int) and length modifier 'll' (e.g. %lld).
211  * If undefined, 'll' is recognized but treated as a single 'l'.
212  *
213  * If the system's sprintf does not handle 'll'
214  * the SNPRINTF_LONGLONG_SUPPORT must not be defined!
215  *
216  * This is off by default as (long long int) is a language extension.
217  */
218 /* #define SNPRINTF_LONGLONG_SUPPORT */
219
220 /* Define NEED_SNPRINTF_ONLY if you only need snprintf, and not vsnprintf.
221  * If NEED_SNPRINTF_ONLY is defined, the snprintf will be defined directly,
222  * otherwise both snprintf and vsnprintf routines will be defined
223  * and snprintf will be a simple wrapper around vsnprintf, at the expense
224  * of an extra procedure call.
225  */
226 /* #define NEED_SNPRINTF_ONLY */
227
228 /* Define NEED_V?ASN?PRINTF macros if you need library extension
229  * routines asprintf, vasprintf, asnprintf, vasnprintf respectively,
230  * and your system library does not provide them. They are all small
231  * wrapper routines around portable_vsnprintf. Defining any of the four
232  * NEED_V?ASN?PRINTF macros automatically turns off NEED_SNPRINTF_ONLY
233  * and turns on PREFER_PORTABLE_SNPRINTF.
234  *
235  * Watch for name conflicts with the system library if these routines
236  * are already present there.
237  *
238  * NOTE: vasprintf and vasnprintf routines need va_copy() from stdarg.h, as
239  * specified by C99, to be able to traverse the same list of arguments twice.
240  * I don't know of any other standard and portable way of achieving the same.
241  * With some versions of gcc you may use __va_copy(). You might even get away
242  * with "ap2 = ap", in this case you must not call va_end(ap2) !
243  *   #define va_copy(ap2,ap) ap2 = ap
244  */
245 /* #define NEED_ASPRINTF   */
246 /* #define NEED_ASNPRINTF  */
247 /* #define NEED_VASPRINTF  */
248 /* #define NEED_VASNPRINTF */
249
250
251 /* Define the following macros if desired:
252  *   SOLARIS_COMPATIBLE, SOLARIS_BUG_COMPATIBLE,
253  *   HPUX_COMPATIBLE, HPUX_BUG_COMPATIBLE, LINUX_COMPATIBLE,
254  *   DIGITAL_UNIX_COMPATIBLE, DIGITAL_UNIX_BUG_COMPATIBLE,
255  *   PERL_COMPATIBLE, PERL_BUG_COMPATIBLE,
256  *
257  * - For portable applications it is best not to rely on peculiarities
258  *   of a given implementation so it may be best not to define any
259  *   of the macros that select compatibility and to avoid features
260  *   that vary among the systems.
261  *
262  * - Selecting compatibility with more than one operating system
263  *   is not strictly forbidden but is not recommended.
264  *
265  * - 'x'_BUG_COMPATIBLE implies 'x'_COMPATIBLE .
266  *
267  * - 'x'_COMPATIBLE refers to (and enables) a behaviour that is
268  *   documented in a sprintf man page on a given operating system
269  *   and actually adhered to by the system's sprintf (but not on
270  *   most other operating systems). It may also refer to and enable
271  *   a behaviour that is declared 'undefined' or 'implementation specific'
272  *   in the man page but a given implementation behaves predictably
273  *   in a certain way.
274  *
275  * - 'x'_BUG_COMPATIBLE refers to (and enables) a behaviour of system's sprintf
276  *   that contradicts the sprintf man page on the same operating system.
277  *
278  * - I do not claim that the 'x'_COMPATIBLE and 'x'_BUG_COMPATIBLE
279  *   conditionals take into account all idiosyncrasies of a particular
280  *   implementation, there may be other incompatibilities.
281  */
282
283
284 \f
285 /* ============================================= */
286 /* NO USER SERVICABLE PARTS FOLLOWING THIS POINT */
287 /* ============================================= */
288
289 #define PORTABLE_SNPRINTF_VERSION_MAJOR 2
290 #define PORTABLE_SNPRINTF_VERSION_MINOR 2
291
292 #if defined(NEED_ASPRINTF) || defined(NEED_ASNPRINTF) || defined(NEED_VASPRINTF) || defined(NEED_VASNPRINTF)
293 # if defined(NEED_SNPRINTF_ONLY)
294 # undef NEED_SNPRINTF_ONLY
295 # endif
296 # if !defined(PREFER_PORTABLE_SNPRINTF)
297 # define PREFER_PORTABLE_SNPRINTF
298 # endif
299 #endif
300
301 #if defined(SOLARIS_BUG_COMPATIBLE) && !defined(SOLARIS_COMPATIBLE)
302 #define SOLARIS_COMPATIBLE
303 #endif
304
305 #if defined(HPUX_BUG_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
306 #define HPUX_COMPATIBLE
307 #endif
308
309 #if defined(DIGITAL_UNIX_BUG_COMPATIBLE) && !defined(DIGITAL_UNIX_COMPATIBLE)
310 #define DIGITAL_UNIX_COMPATIBLE
311 #endif
312
313 #if defined(PERL_BUG_COMPATIBLE) && !defined(PERL_COMPATIBLE)
314 #define PERL_COMPATIBLE
315 #endif
316
317 #if defined(LINUX_BUG_COMPATIBLE) && !defined(LINUX_COMPATIBLE)
318 #define LINUX_COMPATIBLE
319 #endif
320
321 #include <sys/types.h>
322 #include <string.h>
323 #include <stdlib.h>
324 #include <stdio.h>
325 #include <stdarg.h>
326 #include "gras_config.h" /* to get a working stdarg.h */
327 #include <assert.h>
328 #include <errno.h>
329
330 #ifdef isdigit
331 #undef isdigit
332 #endif
333 #define isdigit(c) ((c) >= '0' && (c) <= '9')
334
335 /* For copying strings longer or equal to 'breakeven_point'
336  * it is more efficient to call memcpy() than to do it inline.
337  * The value depends mostly on the processor architecture,
338  * but also on the compiler and its optimization capabilities.
339  * The value is not critical, some small value greater than zero
340  * will be just fine if you don't care to squeeze every drop
341  * of performance out of the code.
342  *
343  * Small values favor memcpy, large values favor inline code.
344  */
345 #if defined(__alpha__) || defined(__alpha)
346 #  define breakeven_point   2   /* AXP (DEC Alpha)     - gcc or cc or egcs */
347 #endif
348 #if defined(__i386__)  || defined(__i386)
349 #  define breakeven_point  12   /* Intel Pentium/Linux - gcc 2.96 */
350 #endif
351 #if defined(__hppa)
352 #  define breakeven_point  10   /* HP-PA               - gcc */
353 #endif
354 #if defined(__sparc__) || defined(__sparc)
355 #  define breakeven_point  33   /* Sun Sparc 5         - gcc 2.8.1 */
356 #endif
357
358 /* some other values of possible interest: */
359 /* #define breakeven_point  8 */  /* VAX 4000          - vaxc */
360 /* #define breakeven_point 19 */  /* VAX 4000          - gcc 2.7.0 */
361
362 #ifndef breakeven_point
363 #  define breakeven_point   6   /* some reasonable one-size-fits-all value */
364 #endif
365
366 #define fast_memcpy(d,s,n) \
367   { register size_t nn = (size_t)(n); \
368     if (nn >= breakeven_point) memcpy((d), (s), nn); \
369     else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
370       register char *dd; register const char *ss; \
371       for (ss=(s), dd=(d); nn>0; nn--) *dd++ = *ss++; } }
372
373 #define fast_memset(d,c,n) \
374   { register size_t nn = (size_t)(n); \
375     if (nn >= breakeven_point) memset((d), (int)(c), nn); \
376     else if (nn > 0) { /* proc call overhead is worth only for large strings*/\
377       register char *dd; register const int cc=(int)(c); \
378       for (dd=(d); nn>0; nn--) *dd++ = cc; } }
379
380 /* prototypes */
381
382 #if defined(NEED_ASPRINTF)
383 int asprintf   (char **ptr, const char *fmt, /*args*/ ...);
384 #endif
385 #if defined(NEED_VASPRINTF)
386 int vasprintf  (char **ptr, const char *fmt, va_list ap);
387 #endif
388 #if defined(NEED_ASNPRINTF)
389 int asnprintf  (char **ptr, size_t str_m, const char *fmt, /*args*/ ...);
390 #endif
391 #if defined(NEED_VASNPRINTF)
392 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap);
393 #endif
394
395 #if defined(HAVE_SNPRINTF)
396 /* declare our portable snprintf  routine under name portable_snprintf  */
397 /* declare our portable vsnprintf routine under name portable_vsnprintf */
398 #else
399 /* declare our portable routines under names snprintf and vsnprintf */
400 #define portable_snprintf snprintf
401 #if !defined(NEED_SNPRINTF_ONLY)
402 #define portable_vsnprintf vsnprintf
403 #endif
404 #endif
405
406 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
407 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...);
408 #if !defined(NEED_SNPRINTF_ONLY)
409 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap);
410 #endif
411 #endif
412
413 /* declarations */
414
415 static char credits[] = "\n\
416 @(#)snprintf.c, v2.2: Mark Martinec, <mark.martinec@ijs.si>\n\
417 @(#)snprintf.c, v2.2: Copyright 1999, Mark Martinec. Frontier Artistic License applies.\n\
418 @(#)snprintf.c, v2.2: http://www.ijs.si/software/snprintf/\n";
419
420 static void __foo__(void) 
421 {
422    printf("%s",credits);
423    __foo__();
424 }
425
426 #if defined(NEED_ASPRINTF)
427 int asprintf(char **ptr, const char *fmt, /*args*/ ...) {
428   va_list ap;
429   size_t str_m;
430   int str_l;
431
432   *ptr = NULL;
433   va_start(ap, fmt);                            /* measure the required size */
434   str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
435   va_end(ap);
436   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
437   *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
438   if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
439   else {
440     int str_l2;
441     va_start(ap, fmt);
442     str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
443     va_end(ap);
444     assert(str_l2 == str_l);
445   }
446   return str_l;
447 }
448 #endif
449
450 #if defined(NEED_VASPRINTF)
451 int vasprintf(char **ptr, const char *fmt, va_list ap) {
452   size_t str_m;
453   int str_l;
454
455   *ptr = NULL;
456   { va_list ap2;
457     va_copy(ap2, ap);  /* don't consume the original ap, we'll need it again */
458     str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
459     va_end(ap2);
460   }
461   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
462   *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
463   if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
464   else {
465     int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
466     assert(str_l2 == str_l);
467   }
468   return str_l;
469 }
470 #endif
471
472 #if defined(NEED_ASNPRINTF)
473 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...) {
474   va_list ap;
475   int str_l;
476
477   *ptr = NULL;
478   va_start(ap, fmt);                            /* measure the required size */
479   str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap);
480   va_end(ap);
481   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
482   if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1;      /* truncate */
483   /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
484   if (str_m == 0) {  /* not interested in resulting string, just return size */
485   } else {
486     *ptr = (char *) malloc(str_m);
487     if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
488     else {
489       int str_l2;
490       va_start(ap, fmt);
491       str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
492       va_end(ap);
493       assert(str_l2 == str_l);
494     }
495   }
496   return str_l;
497 }
498 #endif
499
500 #if defined(NEED_VASNPRINTF)
501 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap) {
502   int str_l;
503
504   *ptr = NULL;
505   { va_list ap2;
506     va_copy(ap2, ap);  /* don't consume the original ap, we'll need it again */
507     str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/
508     va_end(ap2);
509   }
510   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
511   if ((size_t)str_l + 1 < str_m) 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 */
514   } else {
515     *ptr = (char *) malloc(str_m);
516     if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
517     else {
518       int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
519       assert(str_l2 == str_l);
520     }
521   }
522   return str_l;
523 }
524 #endif
525
526 /*
527  * If the system does have snprintf and the portable routine is not
528  * specifically required, this module produces no code for snprintf/vsnprintf.
529  */
530 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
531
532 #if !defined(NEED_SNPRINTF_ONLY)
533 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
534   va_list ap;
535   int str_l;
536
537   va_start(ap, fmt);
538   str_l = portable_vsnprintf(str, str_m, fmt, ap);
539   va_end(ap);
540   return str_l;
541 }
542 #endif
543
544 #if defined(NEED_SNPRINTF_ONLY)
545 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
546 #else
547 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap) {
548 #endif
549
550 #if defined(NEED_SNPRINTF_ONLY)
551   va_list ap;
552 #endif
553   size_t str_l = 0;
554   const char *p = fmt;
555
556 /* In contrast with POSIX, the ISO C99 now says
557  * that str can be NULL and str_m can be 0.
558  * This is more useful than the old:  if (str_m < 1) return -1; */
559
560 #if defined(NEED_SNPRINTF_ONLY)
561   va_start(ap, fmt);
562 #endif
563   if (!p) p = "";
564   while (*p) {
565     if (*p != '%') {
566    /* if (str_l < str_m) str[str_l++] = *p++;    -- this would be sufficient */
567    /* but the following code achieves better performance for cases
568     * where format string is long and contains few conversions */
569       const char *q = strchr(p+1,'%');
570       size_t n = !q ? strlen(p) : (q-p);
571       if (str_l < str_m) {
572         size_t avail = str_m-str_l;
573         fast_memcpy(str+str_l, p, (n>avail?avail:n));
574       }
575       p += n; str_l += n;
576     } else {
577       const char *starting_p;
578       size_t min_field_width = 0, precision = 0;
579       int zero_padding = 0, precision_specified = 0, justify_left = 0;
580       int alternate_form = 0, force_sign = 0;
581       int space_for_positive = 1; /* If both the ' ' and '+' flags appear,
582                                      the ' ' flag should be ignored. */
583       char length_modifier = '\0';            /* allowed values: \0, h, l, L */
584       char tmp[32];/* temporary buffer for simple numeric->string conversion */
585
586       const char *str_arg;      /* string address in case of string argument */
587       size_t str_arg_l;         /* natural field width of arg without padding
588                                    and sign */
589       unsigned char uchar_arg;
590         /* unsigned char argument value - only defined for c conversion.
591            N.B. standard explicitly states the char argument for
592            the c conversion is unsigned */
593
594       size_t number_of_zeros_to_pad = 0;
595         /* number of zeros to be inserted for numeric conversions
596            as required by the precision or minimal field width */
597
598       size_t zero_padding_insertion_ind = 0;
599         /* index into tmp where zero padding is to be inserted */
600
601       char fmt_spec = '\0';
602         /* current conversion specifier character */
603
604       str_arg = credits;/* just to make compiler happy (defined but not used)*/
605       str_arg = NULL;
606       starting_p = p; p++;  /* skip '%' */
607    /* parse flags */
608       while (*p == '0' || *p == '-' || *p == '+' ||
609              *p == ' ' || *p == '#' || *p == '\'') {
610         switch (*p) {
611         case '0': zero_padding = 1; break;
612         case '-': justify_left = 1; break;
613         case '+': force_sign = 1; space_for_positive = 0; break;
614         case ' ': force_sign = 1;
615      /* If both the ' ' and '+' flags appear, the ' ' flag should be ignored */
616 #ifdef PERL_COMPATIBLE
617      /* ... but in Perl the last of ' ' and '+' applies */
618                   space_for_positive = 1;
619 #endif
620                   break;
621         case '#': alternate_form = 1; break;
622         case '\'': break;
623         }
624         p++;
625       }
626    /* If the '0' and '-' flags both appear, the '0' flag should be ignored. */
627
628    /* parse field width */
629       if (*p == '*') {
630         int j;
631         p++; j = va_arg(ap, int);
632         if (j >= 0) min_field_width = j;
633         else { min_field_width = -j; justify_left = 1; }
634       } else if (isdigit((int)(*p))) {
635         /* size_t could be wider than unsigned int;
636            make sure we treat argument like common implementations do */
637         unsigned int uj = *p++ - '0';
638         while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
639         min_field_width = uj;
640       }
641    /* parse precision */
642       if (*p == '.') {
643         p++; precision_specified = 1;
644         if (*p == '*') {
645           int j = va_arg(ap, int);
646           p++;
647           if (j >= 0) precision = j;
648           else {
649             precision_specified = 0; precision = 0;
650          /* NOTE:
651           *   Solaris 2.6 man page claims that in this case the precision
652           *   should be set to 0.  Digital Unix 4.0, HPUX 10 and BSD man page
653           *   claim that this case should be treated as unspecified precision,
654           *   which is what we do here.
655           */
656           }
657         } else if (isdigit((int)(*p))) {
658           /* size_t could be wider than unsigned int;
659              make sure we treat argument like common implementations do */
660           unsigned int uj = *p++ - '0';
661           while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0');
662           precision = uj;
663         }
664       }
665    /* parse 'h', 'l' and 'll' length modifiers */
666       if (*p == 'h' || *p == 'l') {
667         length_modifier = *p; p++;
668         if (length_modifier == 'l' && *p == 'l') {   /* double l = long long */
669 #ifdef SNPRINTF_LONGLONG_SUPPORT
670           length_modifier = '2';                  /* double l encoded as '2' */
671 #else
672           length_modifier = 'l';                 /* treat it as a single 'l' */
673 #endif
674           p++;
675         }
676       }
677       fmt_spec = *p;
678    /* common synonyms: */
679       switch (fmt_spec) {
680       case 'i': fmt_spec = 'd'; break;
681       case 'D': fmt_spec = 'd'; length_modifier = 'l'; break;
682       case 'U': fmt_spec = 'u'; length_modifier = 'l'; break;
683       case 'O': fmt_spec = 'o'; length_modifier = 'l'; break;
684       default: break;
685       }
686    /* get parameter value, do initial processing */
687       switch (fmt_spec) {
688       case '%': /* % behaves similar to 's' regarding flags and field widths */
689       case 'c': /* c behaves similar to 's' regarding flags and field widths */
690       case 's':
691         length_modifier = '\0';          /* wint_t and wchar_t not supported */
692      /* the result of zero padding flag with non-numeric conversion specifier*/
693      /* is undefined. Solaris and HPUX 10 does zero padding in this case,    */
694      /* Digital Unix and Linux does not. */
695 #if !defined(SOLARIS_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
696         zero_padding = 0;    /* turn zero padding off for string conversions */
697 #endif
698         str_arg_l = 1;
699         switch (fmt_spec) {
700         case '%':
701           str_arg = p; break;
702         case 'c': {
703           int j = va_arg(ap, int);
704           uchar_arg = (unsigned char) j;   /* standard demands unsigned char */
705           str_arg = (const char *) &uchar_arg;
706           break;
707         }
708         case 's':
709           str_arg = va_arg(ap, const char *);
710           if (!str_arg) str_arg_l = 0;
711        /* make sure not to address string beyond the specified precision !!! */
712           else if (!precision_specified) str_arg_l = strlen(str_arg);
713        /* truncate string if necessary as requested by precision */
714           else if (precision == 0) str_arg_l = 0;
715           else {
716        /* memchr on HP does not like n > 2^31  !!! */
717             char *q = (char *) memchr(str_arg, '\0',
718                              precision <= 0x7fffffff ? precision : 0x7fffffff);
719             str_arg_l = !q ? precision : (q-str_arg);
720           }
721           break;
722         default: break;
723         }
724         break;
725       case 'd': case 'u': case 'o': case 'x': case 'X': case 'p': {
726         /* NOTE: the u, o, x, X and p conversion specifiers imply
727                  the value is unsigned;  d implies a signed value */
728
729         int arg_sign = 0;
730           /* 0 if numeric argument is zero (or if pointer is NULL for 'p'),
731             +1 if greater than zero (or nonzero for unsigned arguments),
732             -1 if negative (unsigned argument is never negative) */
733
734         int int_arg = 0;  unsigned int uint_arg = 0;
735           /* only defined for length modifier h, or for no length modifiers */
736
737         long int long_arg = 0;  unsigned long int ulong_arg = 0;
738           /* only defined for length modifier l */
739
740         void *ptr_arg = NULL;
741           /* pointer argument value -only defined for p conversion */
742
743 #ifdef SNPRINTF_LONGLONG_SUPPORT
744         long long int long_long_arg = 0;
745         unsigned long long int ulong_long_arg = 0;
746           /* only defined for length modifier ll */
747 #endif
748         if (fmt_spec == 'p') {
749         /* HPUX 10: An l, h, ll or L before any other conversion character
750          *   (other than d, i, u, o, x, or X) is ignored.
751          * Digital Unix:
752          *   not specified, but seems to behave as HPUX does.
753          * Solaris: If an h, l, or L appears before any other conversion
754          *   specifier (other than d, i, u, o, x, or X), the behavior
755          *   is undefined. (Actually %hp converts only 16-bits of address
756          *   and %llp treats address as 64-bit data which is incompatible
757          *   with (void *) argument on a 32-bit system).
758          */
759 #ifdef SOLARIS_COMPATIBLE
760 #  ifdef SOLARIS_BUG_COMPATIBLE
761           /* keep length modifiers even if it represents 'll' */
762 #  else
763           if (length_modifier == '2') length_modifier = '\0';
764 #  endif
765 #else
766           length_modifier = '\0';
767 #endif
768           ptr_arg = va_arg(ap, void *);
769           if (ptr_arg != NULL) arg_sign = 1;
770         } else if (fmt_spec == 'd') {  /* signed */
771           switch (length_modifier) {
772           case '\0':
773           case 'h':
774          /* It is non-portable to specify a second argument of char or short
775           * to va_arg, because arguments seen by the called function
776           * are not char or short.  C converts char and short arguments
777           * to int before passing them to a function.
778           */
779             int_arg = va_arg(ap, int);
780             if      (int_arg > 0) arg_sign =  1;
781             else if (int_arg < 0) arg_sign = -1;
782             break;
783           case 'l':
784             long_arg = va_arg(ap, long int);
785             if      (long_arg > 0) arg_sign =  1;
786             else if (long_arg < 0) arg_sign = -1;
787             break;
788 #ifdef SNPRINTF_LONGLONG_SUPPORT
789           case '2':
790             long_long_arg = va_arg(ap, long long int);
791             if      (long_long_arg > 0) arg_sign =  1;
792             else if (long_long_arg < 0) arg_sign = -1;
793             break;
794 #endif
795           }
796         } else {  /* unsigned */
797           switch (length_modifier) {
798           case '\0':
799           case 'h':
800             uint_arg = va_arg(ap, unsigned int);
801             if (uint_arg) arg_sign = 1;
802             break;
803           case 'l':
804             ulong_arg = va_arg(ap, unsigned long int);
805             if (ulong_arg) arg_sign = 1;
806             break;
807 #ifdef SNPRINTF_LONGLONG_SUPPORT
808           case '2':
809             ulong_long_arg = va_arg(ap, unsigned long long int);
810             if (ulong_long_arg) arg_sign = 1;
811             break;
812 #endif
813           }
814         }
815         str_arg = tmp; str_arg_l = 0;
816      /* NOTE:
817       *   For d, i, u, o, x, and X conversions, if precision is specified,
818       *   the '0' flag should be ignored. This is so with Solaris 2.6,
819       *   Digital UNIX 4.0, HPUX 10, Linux, FreeBSD, NetBSD; but not with Perl.
820       */
821 #ifndef PERL_COMPATIBLE
822         if (precision_specified) zero_padding = 0;
823 #endif
824         if (fmt_spec == 'd') {
825           if (force_sign && arg_sign >= 0)
826             tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
827          /* leave negative numbers for sprintf to handle,
828             to avoid handling tricky cases like (short int)(-32768) */
829 #ifdef LINUX_COMPATIBLE
830         } else if (fmt_spec == 'p' && force_sign && arg_sign > 0) {
831           tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
832 #endif
833         } else if (alternate_form) {
834           if (arg_sign != 0 && (fmt_spec == 'x' || fmt_spec == 'X') )
835             { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = fmt_spec; }
836          /* alternate form should have no effect for p conversion, but ... */
837 #ifdef HPUX_COMPATIBLE
838           else if (fmt_spec == 'p'
839          /* HPUX 10: for an alternate form of p conversion,
840           *          a nonzero result is prefixed by 0x. */
841 #ifndef HPUX_BUG_COMPATIBLE
842          /* Actually it uses 0x prefix even for a zero value. */
843                    && arg_sign != 0
844 #endif
845                   ) { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = 'x'; }
846 #endif
847         }
848         zero_padding_insertion_ind = str_arg_l;
849         if (!precision_specified) precision = 1;   /* default precision is 1 */
850         if (precision == 0 && arg_sign == 0
851 #if defined(HPUX_BUG_COMPATIBLE) || defined(LINUX_COMPATIBLE)
852             && fmt_spec != 'p'
853          /* HPUX 10 man page claims: With conversion character p the result of
854           * converting a zero value with a precision of zero is a null string.
855           * Actually HP returns all zeroes, and Linux returns "(nil)". */
856 #endif
857         ) {
858          /* converted to null string */
859          /* When zero value is formatted with an explicit precision 0,
860             the resulting formatted string is empty (d, i, u, o, x, X, p).   */
861         } else {
862           char f[5]; int f_l = 0;
863           f[f_l++] = '%';    /* construct a simple format string for sprintf */
864           if (!length_modifier) { }
865           else if (length_modifier=='2') { f[f_l++] = 'l'; f[f_l++] = 'l'; }
866           else f[f_l++] = length_modifier;
867           f[f_l++] = fmt_spec; f[f_l++] = '\0';
868           if (fmt_spec == 'p') str_arg_l += sprintf(tmp+str_arg_l, f, ptr_arg);
869           else if (fmt_spec == 'd') {  /* signed */
870             switch (length_modifier) {
871             case '\0':
872             case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, int_arg);  break;
873             case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, long_arg); break;
874 #ifdef SNPRINTF_LONGLONG_SUPPORT
875             case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,long_long_arg); break;
876 #endif
877             }
878           } else {  /* unsigned */
879             switch (length_modifier) {
880             case '\0':
881             case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, uint_arg);  break;
882             case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, ulong_arg); break;
883 #ifdef SNPRINTF_LONGLONG_SUPPORT
884             case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,ulong_long_arg);break;
885 #endif
886             }
887           }
888          /* include the optional minus sign and possible "0x"
889             in the region before the zero padding insertion point */
890           if (zero_padding_insertion_ind < str_arg_l &&
891               tmp[zero_padding_insertion_ind] == '-') {
892             zero_padding_insertion_ind++;
893           }
894           if (zero_padding_insertion_ind+1 < str_arg_l &&
895               tmp[zero_padding_insertion_ind]   == '0' &&
896              (tmp[zero_padding_insertion_ind+1] == 'x' ||
897               tmp[zero_padding_insertion_ind+1] == 'X') ) {
898             zero_padding_insertion_ind += 2;
899           }
900         }
901         { size_t num_of_digits = str_arg_l - zero_padding_insertion_ind;
902           if (alternate_form && fmt_spec == 'o'
903 #ifdef HPUX_COMPATIBLE                                  /* ("%#.o",0) -> ""  */
904               && (str_arg_l > 0)
905 #endif
906 #ifdef DIGITAL_UNIX_BUG_COMPATIBLE                      /* ("%#o",0) -> "00" */
907 #else
908               /* unless zero is already the first character */
909               && !(zero_padding_insertion_ind < str_arg_l
910                    && tmp[zero_padding_insertion_ind] == '0')
911 #endif
912           ) {        /* assure leading zero for alternate-form octal numbers */
913             if (!precision_specified || precision < num_of_digits+1) {
914              /* precision is increased to force the first character to be zero,
915                 except if a zero value is formatted with an explicit precision
916                 of zero */
917               precision = num_of_digits+1; precision_specified = 1;
918             }
919           }
920        /* zero padding to specified precision? */
921           if (num_of_digits < precision) 
922             number_of_zeros_to_pad = precision - num_of_digits;
923         }
924      /* zero padding to specified minimal field width? */
925         if (!justify_left && zero_padding) {
926           int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
927           if (n > 0) number_of_zeros_to_pad += n;
928         }
929         break;
930       }
931       default: /* unrecognized conversion specifier, keep format string as-is*/
932         zero_padding = 0;  /* turn zero padding off for non-numeric convers. */
933 #ifndef DIGITAL_UNIX_COMPATIBLE
934         justify_left = 1; min_field_width = 0;                /* reset flags */
935 #endif
936 #if defined(PERL_COMPATIBLE) || defined(LINUX_COMPATIBLE)
937      /* keep the entire format string unchanged */
938         str_arg = starting_p; str_arg_l = p - starting_p;
939      /* well, not exactly so for Linux, which does something inbetween,
940       * and I don't feel an urge to imitate it: "%+++++hy" -> "%+y"  */
941 #else
942      /* discard the unrecognized conversion, just keep *
943       * the unrecognized conversion character          */
944         str_arg = p; str_arg_l = 0;
945 #endif
946         if (*p) str_arg_l++;  /* include invalid conversion specifier unchanged
947                                  if not at end-of-string */
948         break;
949       }
950       if (*p) p++;      /* step over the just processed conversion specifier */
951    /* insert padding to the left as requested by min_field_width;
952       this does not include the zero padding in case of numerical conversions*/
953       if (!justify_left) {                /* left padding with blank or zero */
954         int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
955         if (n > 0) {
956           if (str_l < str_m) {
957             int avail = str_m-str_l;
958             fast_memset(str+str_l, (zero_padding?'0':' '), (n>avail?avail:n));
959           }
960           str_l += n;
961         }
962       }
963    /* zero padding as requested by the precision or by the minimal field width
964     * for numeric conversions required? */
965       if (number_of_zeros_to_pad <= 0) {
966      /* will not copy first part of numeric right now, *
967       * force it to be copied later in its entirety    */
968         zero_padding_insertion_ind = 0;
969       } else {
970      /* insert first part of numerics (sign or '0x') before zero padding */
971         int n = zero_padding_insertion_ind;
972         if (n > 0) {
973           if (str_l < str_m) {
974             int avail = str_m-str_l;
975             fast_memcpy(str+str_l, str_arg, (n>avail?avail:n));
976           }
977           str_l += n;
978         }
979      /* insert zero padding as requested by the precision or min field width */
980         n = number_of_zeros_to_pad;
981         if (n > 0) {
982           if (str_l < str_m) {
983             int avail = str_m-str_l;
984             fast_memset(str+str_l, '0', (n>avail?avail:n));
985           }
986           str_l += n;
987         }
988       }
989    /* insert formatted string
990     * (or as-is conversion specifier for unknown conversions) */
991       { int n = str_arg_l - zero_padding_insertion_ind;
992         if (n > 0) {
993           if (str_l < str_m) {
994             int avail = str_m-str_l;
995             fast_memcpy(str+str_l, str_arg+zero_padding_insertion_ind,
996                         (n>avail?avail:n));
997           }
998           str_l += n;
999         }
1000       }
1001    /* insert right padding */
1002       if (justify_left) {          /* right blank padding to the field width */
1003         int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
1004         if (n > 0) {
1005           if (str_l < str_m) {
1006             int avail = str_m-str_l;
1007             fast_memset(str+str_l, ' ', (n>avail?avail:n));
1008           }
1009           str_l += n;
1010         }
1011       }
1012     }
1013   }
1014 #if defined(NEED_SNPRINTF_ONLY)
1015   va_end(ap);
1016 #endif
1017   if (str_m > 0) { /* make sure the string is null-terminated
1018                       even at the expense of overwriting the last character
1019                       (shouldn't happen, but just in case) */
1020     str[str_l <= str_m-1 ? str_l : str_m-1] = '\0';
1021   }
1022   /* Return the number of characters formatted (excluding trailing null
1023    * character), that is, the number of characters that would have been
1024    * written to the buffer if it were large enough.
1025    *
1026    * The value of str_l should be returned, but str_l is of unsigned type
1027    * size_t, and snprintf is int, possibly leading to an undetected
1028    * integer overflow, resulting in a negative return value, which is illegal.
1029    * Both XSH5 and ISO C99 (at least the draft) are silent on this issue.
1030    * Should errno be set to EOVERFLOW and EOF returned in this case???
1031    */
1032   return (int) str_l;
1033 }
1034 #endif
1035
1036
1037 /* FIXME: better place */
1038 #include "xbt/sysdep.h"
1039
1040 char *bprintf(const char*fmt, ...) {
1041   va_list ap;
1042   char *res;
1043   
1044   va_start(ap, fmt);
1045   vasprintf(&res,fmt,ap);
1046   va_end(ap);
1047   return res;
1048 }