ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/group/trunk/OOPSE-4/src/openbabel/snprintf.c
Revision: 2440
Committed: Wed Nov 16 19:42:11 2005 UTC (18 years, 7 months ago) by tim
Content type: text/plain
File size: 50365 byte(s)
Log Message:
adding openbabel

File Contents

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