]> git.lyx.org Git - lyx.git/blob - src/support/snprintf.c
fix a couple of hard crashes, constify local variables, whitespace changes, some...
[lyx.git] / src / support / snprintf.c
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 as per ISO C9X;
31  * - written in standard ISO/ANSI C - requires an ANSI C compiler.
32  *
33  * SUPPORTED FORMATS AND DATA TYPES
34  *
35  * This snprintf only supports format specifiers:
36  * s, c, d, o, u, 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  * Data type 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  *   data type 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 data type modifier 'll'. long long int is a language
48  *   extension which may not be portable.
49  *
50  * Conversion of numeric data (formats d, o, u, x, X, p) with data type
51  * modifiers (none or h, l, ll) is left to the system routine sprintf,
52  * but all handling of flags, field width and precision as well as c and
53  * s formats is done very carefully by this portable routine. If a string
54  * precision (truncation) is specified (e.g. %.8s) it is guaranteed the
55  * string beyond the specified precision will not be referenced.
56  *
57  * Data type modifiers h, l and ll are ignored for c and s formats (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 data type modifiers are ignored
63  *   - U is a synonym for lu, explicit data type modifiers are ignored
64  *   - O is a synonym for lo, explicit data type modifiers are ignored
65  *
66  * The following is specifically not supported:
67  *   - flag ' (thousands' grouping character) is recognized but ignored
68  *   - numeric formats: f, e, E, g, G and synonym F
69  *   - data type modifier 'L' (long double) and 'q' (quad - use 'll' instead)
70  *   - wide character/string formats: C, lc, S, ls
71  *   - writeback of converted string length: conversion character n
72  *   - the n$ specification for direct reference to n-th argument
73  *   - locales
74  *
75  * It is permitted for str_m to be zero, and it is permitted to specify NULL
76  * pointer for resulting string argument if str_m is zero (as per ISO C9X).
77  *
78  * The return value is the number of characters which would be generated
79  * for the given input, excluding the trailing null. If this value
80  * is greater or equal to str_m, not all characters from the result
81  * have been stored in str. If str_m is greater than zero it is
82  * guaranteed the resulting string will be null-terminated.
83  *
84  * NOTE that this matches the ISO C9X and GNU C library 2.1,
85  * but is different from some older implementations!
86  *
87  * Routines asprintf and vasprintf return a pointer (in the ptr argument)
88  * to a buffer sufficiently large to hold the resulting string. This pointer
89  * should be passed to free(3) to release the allocated storage when it is
90  * no longer needed. If sufficient space cannot be allocated, these functions
91  * will return -1 and set ptr to be a NULL pointer. These two routines are a
92  * GNU C library extensions (glibc).
93  *
94  * Routines asnprintf and vasnprintf are similar to asprintf and vasprintf,
95  * yet, like snprintf and vsnprintf counterparts, will write at most str_m-1
96  * characters into the allocated output string, the last character in the
97  * allocated buffer then gets the terminating null. If the formatted string
98  * length (the return value) is greater than or equal to the str_m argument,
99  * the resulting string was truncated and some of the formatted characters
100  * were discarded. These routines present a handy way to limit the amount
101  * of allocated memory to some sane value.
102  *
103  * AVAILABILITY
104  *   http://www.ijs.si/software/snprintf/
105  *
106  * REVISION HISTORY
107  * 1999-04      V0.9  Mark Martinec
108  *              - initial version, some modifications after comparing printf
109  *                man pages for Digital Unix 4.0, Solaris 2.6 and HPUX 10,
110  *                and checking how Perl handles sprintf (differently!);
111  * 1999-04-09   V1.0  Mark Martinec <mark.martinec@ijs.si>
112  *              - added main test program, fixed remaining inconsistencies,
113  *                added optional (long long int) support;
114  * 1999-04-12   V1.1  Mark Martinec <mark.martinec@ijs.si>
115  *              - support the 'p' format (pointer to void);
116  *              - if a string precision is specified
117  *                make sure the string beyond the specified precision
118  *                will not be referenced (e.g. by strlen);
119  * 1999-04-13   V1.2  Mark Martinec <mark.martinec@ijs.si>
120  *              - support synonyms %D=%ld, %U=%lu, %O=%lo;
121  *              - speed up the case of long format string with few conversions;
122  * 1999-06-30   V1.3  Mark Martinec <mark.martinec@ijs.si>
123  *              - fixed runaway loop (eventually crashing when str_l wraps
124  *                beyond 2*31) while copying format string without
125  *                conversion specifiers to a buffer that is too short
126  *                (thanks to Edwin Young <edwiny@autonomy.com> for
127  *                spotting the problem);
128  *              - added macros PORTABLE_SNPRINTF_VERSION_(MAJOR|MINOR)
129  *                to snprintf.h
130  * 2000-02-14   V2.0 (never released) Mark Martinec <mark.martinec@ijs.si>
131  *              - relaxed license terms: The Artistic License now applies.
132  *                You may still apply the GNU GENERAL PUBLIC LICENSE
133  *                as was distributed with previous versions, if you prefer;
134  *              - changed REVISION HISTORY dates to use ISO 8601 date format;
135  *              - added vsnprintf (patch also independently proposed by
136  *                Caolan McNamara 2000-05-04, and Keith M Willenson 2000-06-01)
137  * 2000-06-27   V2.1  Mark Martinec <mark.martinec@ijs.si>
138  *              - removed POSIX check for str_m<1; value 0 for str_m is
139  *                allowed by ISO C9X (and GNU C library 2.1) - (pointed out
140  *                on 2000-05-04 by Caolan McNamara, caolan@ csn dot ul dot ie).
141  *                Besides relaxed license this change in standards adherence
142  *                is the main reason to bump up the major version number;
143  *              - added nonstandard routines asnprintf, vasnprintf, asprintf,
144  *                vasprintf that dynamically allocate storage for the
145  *                resulting string; these routines are not compiled by default,
146  *                see comments where NEED_V?ASN?PRINTF macros are defined;
147  *              - autoconf contributed by Caolan McNamara
148  */
149
150
151 /* Define HAVE_SNPRINTF if your system already has snprintf and vsnprintf.
152  *
153  * If HAVE_SNPRINTF is defined this module will not produce code for
154  * snprintf and vsnprintf, unless PREFER_PORTABLE_SNPRINTF is defined as well,
155  * causing this portable version of snprintf to be called portable_snprintf
156  * (and portable_vsnprintf).
157  */
158 /* #define HAVE_SNPRINTF */
159
160 /* Define PREFER_PORTABLE_SNPRINTF if your system does have snprintf and
161  * vsnprintf but you would prefer to use the portable routine(s) instead.
162  * In this case the portable routine is declared as portable_snprintf
163  * (and portable_vsnprintf) and a macro 'snprintf' (and 'vsnprintf')
164  * is defined to expand to 'portable_v?snprintf' - see file snprintf.h .
165  * Defining this macro is only useful if HAVE_SNPRINTF is also defined,
166  * but does does no harm if defined nevertheless.
167  */
168 /* #define PREFER_PORTABLE_SNPRINTF */
169
170 /* Define SNPRINTF_LONGLONG_SUPPORT if you want to support
171  * data type (long long int) and data type modifier 'll' (e.g. %lld).
172  * If undefined, 'll' is recognized but treated as a single 'l'.
173  *
174  * If the system's sprintf does not handle 'll'
175  * the SNPRINTF_LONGLONG_SUPPORT must not be defined!
176  *
177  * This is off by default since (long long int) is a language extension.
178  */
179 /* #define SNPRINTF_LONGLONG_SUPPORT */
180
181 /* Define NEED_SNPRINTF_ONLY if you only need snprintf, and not vsnprintf.
182  * If NEED_SNPRINTF_ONLY is defined, the snprintf will be defined directly,
183  * otherwise both snprintf and vsnprintf routines will be defined
184  * and snprintf will be a simple wrapper around vsnprintf, at the expense
185  * of an extra procedure call.
186  */
187 /* #define NEED_SNPRINTF_ONLY */
188
189 /* Define NEED_V?ASN?PRINTF macros if you need library extension
190  * routines asprintf, vasprintf, asnprintf, vasnprintf respectively,
191  * and your system library does not provide them. They are all small
192  * wrapper routines around portable_vsnprintf. Defining any of the four
193  * NEED_V?ASN?PRINTF macros automatically turns off NEED_SNPRINTF_ONLY
194  * and turns on PREFER_PORTABLE_SNPRINTF.
195  *
196  * Watch for name conflicts with the system library if these routines
197  * are already present there.
198  *
199  * NOTE: vasprintf and vasnprintf routines need va_copy() from stdarg.h, as
200  * specified by C9X, to be able to traverse the same list of arguments twice.
201  * I don't know of any other standard and portable way of achieving the same.
202  * With some versions of gcc you may use __va_copy(). You might even get away
203  * with "ap2 = ap", in this case you must not call va_end(ap2) !
204  */
205 /* #define NEED_ASPRINTF   */
206 /* #define NEED_ASNPRINTF  */
207 /* #define NEED_VASPRINTF  */
208 /* #define NEED_VASNPRINTF */
209
210
211 /* Define the following macros if desired:
212  *   SOLARIS_COMPATIBLE, SOLARIS_BUG_COMPATIBLE,
213  *   HPUX_COMPATIBLE, HPUX_BUG_COMPATIBLE,
214  *   DIGITAL_UNIX_COMPATIBLE, DIGITAL_UNIX_BUG_COMPATIBLE,
215  *   PERL_COMPATIBLE, PERL_BUG_COMPATIBLE,
216  *
217  * - For portable applications it is best not to rely on peculiarities
218  *   of a given implementation so it may be best not to define any
219  *   of the macros that select compatibility and to avoid features
220  *   that vary among the systems.
221  *
222  * - Selecting compatibility with more than one operating system
223  *   is not strictly forbidden but is not recommended.
224  *
225  * - 'x'_BUG_COMPATIBLE implies 'x'_COMPATIBLE .
226  *
227  * - 'x'_COMPATIBLE refers to (and enables) a behaviour that is
228  *   documented in a sprintf man page on a given operating system
229  *   and actually adhered to by the system's sprintf (but not on
230  *   most other operating systems). It may also refer to and enable
231  *   a behaviour that is declared 'undefined' or 'implementation specific'
232  *   in the man page but a given implementation behaves predictably
233  *   in a certain way.
234  *
235  * - 'x'_BUG_COMPATIBLE refers to (and enables) a behaviour of system's sprintf
236  *   that contradicts the sprintf man page on the same operating system.
237  *
238  * - I do not claim that the 'x'_COMPATIBLE and 'x'_BUG_COMPATIBLE
239  *   conditionals take into account all idiosyncrasies of a particular
240  *   implementation, there may be other incompatibilities.
241  */
242
243 /* added by Lgb, the LyX Project */
244 #ifdef HAVE_CONFIG_H
245 #include <config.h>
246 #endif
247
248 \f
249 /* ============================================= */
250 /* NO USER SERVICABLE PARTS FOLLOWING THIS POINT */
251 /* ============================================= */
252
253 #define PORTABLE_SNPRINTF_VERSION_MAJOR 2
254 #define PORTABLE_SNPRINTF_VERSION_MINOR 1
255
256 #if defined(NEED_ASPRINTF) || defined(NEED_ASNPRINTF) || defined(NEED_VASPRINTF) || defined(NEED_VASNPRINTF)
257 # if defined(NEED_SNPRINTF_ONLY)
258 # undef NEED_SNPRINTF_ONLY
259 # endif
260 # if !defined(PREFER_PORTABLE_SNPRINTF)
261 # define PREFER_PORTABLE_SNPRINTF
262 # endif
263 #endif
264
265 #if defined(SOLARIS_BUG_COMPATIBLE) && !defined(SOLARIS_COMPATIBLE)
266 #define SOLARIS_COMPATIBLE
267 #endif
268
269 #if defined(HPUX_BUG_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
270 #define HPUX_COMPATIBLE
271 #endif
272
273 #if defined(DIGITAL_UNIX_BUG_COMPATIBLE) && !defined(DIGITAL_UNIX_COMPATIBLE)
274 #define DIGITAL_UNIX_COMPATIBLE
275 #endif
276
277 #if defined(PERL_BUG_COMPATIBLE) && !defined(PERL_COMPATIBLE)
278 #define PERL_COMPATIBLE
279 #endif
280
281 #include <sys/types.h>
282 #include <string.h>
283 #include <stdlib.h>
284 #include <stdio.h>
285 #include <stdarg.h>
286 #include <assert.h>
287 #include <errno.h>
288
289 #ifdef isdigit
290 #undef isdigit
291 #endif
292 #define isdigit(c) ((c) >= '0' && (c) <= '9')
293
294 /* prototypes */
295
296 #if defined(NEED_ASPRINTF)
297 int asprintf   (char **ptr, const char *fmt, /*args*/ ...);
298 #endif
299 #if defined(NEED_VASPRINTF)
300 int vasprintf  (char **ptr, const char *fmt, va_list ap);
301 #endif
302 #if defined(NEED_ASNPRINTF)
303 int asnprintf  (char **ptr, size_t str_m, const char *fmt, /*args*/ ...);
304 #endif
305 #if defined(NEED_VASNPRINTF)
306 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap);
307 #endif
308
309 #define va_copy(ap2,ap) ap2 = ap
310
311 #if defined(HAVE_SNPRINTF)
312 /* declare our portable snprintf  routine under name portable_snprintf  */
313 /* declare our portable vsnprintf routine under name portable_vsnprintf */
314 #else
315 /* declare our portable routines under names snprintf and vsnprintf */
316 #define portable_snprintf snprintf
317 #if !defined(NEED_SNPRINTF_ONLY)
318 #define portable_vsnprintf vsnprintf
319 #endif
320 #endif
321
322 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
323 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...);
324 #if !defined(NEED_SNPRINTF_ONLY)
325 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap);
326 #endif
327 #endif
328
329 /* declarations */
330
331 #if !defined(lint)
332 static char credits[] = "\n\
333 @(#)snprintf.c, v2.1: Mark Martinec, <mark.martinec@ijs.si>\n\
334 @(#)snprintf.c, v2.1: Copyright 1999, Mark Martinec. Artistic license applies.\n\
335 @(#)snprintf.c, v2.1: http://www.ijs.si/software/snprintf/\n";
336 #endif
337
338 #if defined(NEED_ASPRINTF)
339 int asprintf(char **ptr, const char *fmt, /*args*/ ...) {
340   va_list ap;
341   size_t str_m;
342   int str_l;
343
344   *ptr = NULL;
345   va_start(ap, fmt);                            /* measure the required size */
346   str_l = portable_vsnprintf(NULL, (size_t) 0, fmt, ap);
347   va_end(ap);
348   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
349   *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
350   if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
351   else {
352     int str_l2;
353     va_start(ap, fmt);
354     str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
355     va_end(ap);
356     assert(str_l2 == str_l);
357   }
358   return str_l;
359 }
360 #endif
361
362 #if defined(NEED_VASPRINTF)
363 int vasprintf(char **ptr, const char *fmt, va_list ap) {
364   size_t str_m;
365   int str_l;
366
367   *ptr = NULL;
368   { va_list ap2;
369     va_copy(ap2, ap);  /* don't consume the original ap, we'll need it again */
370                        /* measure the required size: */
371     str_l = portable_vsnprintf(NULL, (size_t) 0, fmt, ap2);
372     va_end(ap2);
373   }
374   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
375   *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
376   if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
377   else {
378     int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
379     assert(str_l2 == str_l);
380   }
381   return str_l;
382 }
383 #endif
384
385 #if defined(NEED_ASNPRINTF)
386 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...) {
387   va_list ap;
388   int str_l;
389
390   *ptr = NULL;
391   va_start(ap, fmt);                            /* measure the required size */
392   str_l = portable_vsnprintf(NULL, (size_t) 0, fmt, ap);
393   va_end(ap);
394   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
395   if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1;      /* truncate */
396   /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
397   if (str_m == 0) {  /* not interested in resulting string, just return size */
398   } else {
399     *ptr = (char *) malloc(str_m);
400     if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
401     else {
402       int str_l2;
403       va_start(ap, fmt);
404       str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
405       va_end(ap);
406       assert(str_l2 == str_l);
407     }
408   }
409   return str_l;
410 }
411 #endif
412
413 #if defined(NEED_VASNPRINTF)
414 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap) {
415   int str_l;
416
417   *ptr = NULL;
418   { va_list ap2;
419     va_copy(ap2, ap);  /* don't consume the original ap, we'll need it again */
420                        /* measure the required size: */
421     str_l = portable_vsnprintf(NULL, (size_t) 0, fmt, ap2);
422     va_end(ap2);
423   }
424   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
425   if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1;      /* truncate */
426   /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
427   if (str_m == 0) {  /* not interested in resulting string, just return size */
428   } else {
429     *ptr = (char *) malloc(str_m);
430     if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
431     else {
432       int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
433       assert(str_l2 == str_l);
434     }
435   }
436   return str_l;
437 }
438 #endif
439
440 /*
441  * If the system does have snprintf and the portable routine is not
442  * specifically required, this module produces no code for snprintf/vsnprintf.
443  */
444 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
445
446 #if !defined(NEED_SNPRINTF_ONLY)
447 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
448   va_list ap;
449   int str_l;
450
451   va_start(ap, fmt);
452   str_l = portable_vsnprintf(str, str_m, fmt, ap);
453   va_end(ap);
454   return str_l;
455 }
456 #endif
457
458 #if defined(NEED_SNPRINTF_ONLY)
459 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
460 #else
461 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap) {
462 #endif
463
464 #if defined(NEED_SNPRINTF_ONLY)
465   va_list ap;
466 #endif
467   size_t str_l = 0;
468   const char *p = fmt;
469
470 /* In contrast with POSIX, the ISO C9X now says
471  * that str can be NULL and str_m can be 0. This is more useful. */
472 /*if (str_m < 1) return -1;*/
473
474 #if defined(NEED_SNPRINTF_ONLY)
475   va_start(ap, fmt);
476 #endif
477   if (!p) p = "";
478   while (*p) {
479     if (*p != '%') {
480    /* if (str_l < str_m) str[str_l++] = *p++;    -- this would be sufficient */
481    /* but the following code achieves better performance for cases
482     * where format string is long and contains few conversions */
483       const char *q = strchr(p+1,'%');
484       int n = !q ? strlen(p) : (q-p);
485       int avail = (int)(str_m-str_l);
486       if (avail > 0) {
487         register int k; register char *r; register const char* p1;
488         for (p1=p, r=str+str_l, k=(n>avail?avail:n); k>0; k--) *r++ = *p1++;
489       }
490       p += n; str_l += n;
491     } else {
492       const char *starting_p;
493       int min_field_width = 0, precision = 0;
494       int zero_padding = 0, precision_specified = 0, justify_left = 0;
495       int alternative_form = 0, force_sign = 0;
496       int space_for_positive = 1; /* If both the ' ' and '+' flags appear,
497                                      the ' ' flag should be ignored. */
498       char data_type_modifier = '\0';      /* allowed valued: \0, h, l, L, p */
499       char tmp[32];/* temporary buffer for simple numeric->string conversion */
500
501       const char *str_arg = 0;/* string address in case of string arguments  */
502       int str_arg_l;  /* natural field width of arg without padding and sign */
503
504       long int long_arg;  /* long int argument value - always defined
505         in case of numeric arguments, regardless of data type modifiers.
506         In case of data type modifier 'll' the value is stored in long_long_arg
507         and only the sign of long_arg is guaranteed to be correct */
508       void *ptr_arg; /* pointer argument value - only defined for p format   */
509       int int_arg;   /* int argument value - only defined if no h or l modif.*/
510 #ifdef SNPRINTF_LONGLONG_SUPPORT
511       long long int long_long_arg = 0;  /* long long argument value - only
512                                            defined if ll modifier is present */
513 #endif
514       int number_of_zeros_to_pad = 0;
515       int zero_padding_insertion_ind = 0;
516       char fmt_spec = '\0';            /* current format specifier character */
517
518       starting_p = p; p++;  /* skip '%' */
519    /* parse flags */
520       while (*p == '0' || *p == '-' || *p == '+' ||
521              *p == ' ' || *p == '#' || *p == '\'') {
522         switch (*p) {
523         case '0': zero_padding = 1; break;
524         case '-': justify_left = 1; break;
525         case '+': force_sign = 1; space_for_positive = 0; break;
526         case ' ': force_sign = 1;
527      /* If both the ' ' and '+' flags appear, the ' ' flag should be ignored */
528 #ifdef PERL_COMPATIBLE
529      /* ... but in Perl the last of ' ' and '+' applies */
530                   space_for_positive = 1;
531 #endif
532                   break;
533         case '#': alternative_form = 1; break;
534         case '\'': break;
535         }
536         p++;
537       }
538    /* If the '0' and '-' flags both appear, the '0' flag should be ignored. */
539
540    /* parse field width */
541       if (*p == '*') {
542         p++; min_field_width = va_arg(ap, int);
543         if (min_field_width < 0)
544           { min_field_width = -min_field_width; justify_left = 1; }
545       } else if (isdigit((int)(*p))) {
546         min_field_width = *p++ - '0';
547         while (isdigit((int)(*p)))
548           min_field_width = 10*min_field_width + (*p++ - '0');
549       }
550    /* parse precision */
551       if (*p == '.') {
552         p++; precision_specified = 1;
553         if (*p == '*') {
554           p++; precision = va_arg(ap, int);
555           if (precision < 0) {
556             precision_specified = 0; precision = 0;
557          /* NOTE:
558           *   Solaris 2.6 man page claims that in this case the precision
559           *   should be set to 0.  Digital Unix 4.0 and HPUX 10 man page
560           *   claim that this case should be treated as unspecified precision,
561           *   which is what we do here.
562           */
563           }
564         } else if (isdigit((int)(*p))) {
565           precision = *p++ - '0';
566           while (isdigit((int)(*p))) precision = 10*precision + (*p++ - '0');
567         }
568       }
569    /* parse 'h', 'l' and 'll' data type modifiers */
570       if (*p == 'h' || *p == 'l') {
571         data_type_modifier = *p; p++;
572         if (data_type_modifier == 'l' && *p == 'l') {/* double l = long long */
573 #ifdef SNPRINTF_LONGLONG_SUPPORT
574           data_type_modifier = '2';               /* double l encoded as '2' */
575 #else
576           data_type_modifier = 'l';                /* treat it as single 'l' */
577 #endif
578           p++;
579         }
580       }
581       fmt_spec = *p;
582    /* common synonyms: */
583       switch (fmt_spec) {
584       case 'i': fmt_spec = 'd'; break;
585       case 'D': fmt_spec = 'd'; data_type_modifier = 'l'; break;
586       case 'U': fmt_spec = 'u'; data_type_modifier = 'l'; break;
587       case 'O': fmt_spec = 'o'; data_type_modifier = 'l'; break;
588       default: break;
589       }
590    /* get parameter value, do initial processing */
591       switch (fmt_spec) {
592       case '%': /* % behaves similar to 's' regarding flags and field widths */
593       case 'c': /* c behaves similar to 's' regarding flags and field widths */
594       case 's':
595         data_type_modifier = '\0';       /* wint_t and wchar_t not supported */
596      /* the result of zero padding flag with non-numeric format is undefined */
597      /* Solaris and HPUX 10 does zero padding in this case, Digital Unix not */
598 #ifdef DIGITAL_UNIX_COMPATIBLE
599         zero_padding = 0;        /* turn zero padding off for string formats */
600 #endif
601         str_arg_l = 1;
602         switch (fmt_spec) {
603         case '%':
604           str_arg = p; break;
605         case 'c':
606           { int j = va_arg(ap, int); str_arg = (const char*) &j; }
607           break;
608         case 's':
609           str_arg = va_arg(ap, const char *);
610           if (!str_arg) str_arg_l = 0;
611        /* make sure not to address string beyond the specified precision !!! */
612           else if (!precision_specified) str_arg_l = strlen(str_arg);
613        /* truncate string if necessary as requested by precision */
614           else if (precision <= 0) str_arg_l = 0;
615           else {
616             const char *q = memchr(str_arg,'\0',(size_t)precision);
617             str_arg_l = !q ? precision : (q-str_arg);
618           }
619           break;
620         default: break;
621         }
622         break;
623       case 'd': case 'o': case 'u': case 'x': case 'X': case 'p':
624         long_arg = 0; int_arg = 0; ptr_arg = NULL;
625         if (fmt_spec == 'p') {
626         /* HPUX 10: An l, h, ll or L before any other conversion character
627          *   (other than d, i, o, u, x, or X) is ignored.
628          * Digital Unix:
629          *   not specified, but seems to behave as HPUX does.
630          * Solaris: If an h, l, or L appears before any other conversion
631          *   specifier (other than d, i, o, u, x, or X), the behavior
632          *   is undefined. (Actually %hp converts only 16-bits of address
633          *   and %llp treats address as 64-bit data which is incompatible
634          *   with (void *) argument on a 32-bit system).
635          */
636 #ifdef SOLARIS_COMPATIBLE
637 #  ifdef SOLARIS_BUG_COMPATIBLE
638           /* keep data type modifiers even if it represents 'll' */
639 #  else
640           if (data_type_modifier == '2') data_type_modifier = '\0';
641 #  endif
642 #else
643           data_type_modifier = '\0';
644 #endif
645           ptr_arg = va_arg(ap, void *); long_arg = !ptr_arg ? 0 : 1;
646         } else {
647           switch (data_type_modifier) {
648           case '\0':
649           case 'h':
650          /* It is non-portable to specify a second argument of char or short
651           * to va_arg, because arguments seen by the called function
652           * are not char or short.  C converts char and short arguments
653           * to int before passing them to a function.
654           */
655             int_arg = va_arg(ap, int); long_arg = int_arg; break;
656           case 'l':
657             long_arg = va_arg(ap, long int); break;
658 #ifdef SNPRINTF_LONGLONG_SUPPORT
659           case '2':
660             long_long_arg = va_arg(ap, long long int);
661             /* only the sign of long_arg is guaranteed */
662             if      (long_long_arg > 0) long_arg = +1;
663             else if (long_long_arg < 0) long_arg = -1;
664             else long_arg = 0;
665             break;
666 #endif
667           }
668         }
669         str_arg = tmp; str_arg_l = 0;
670      /* NOTE:
671       *   For d, i, o, u, x, and X conversions, if precision is specified,
672       *   the '0' flag should be ignored. This is so with Solaris 2.6,
673       *   Digital UNIX 4.0 and HPUX 10;  but not with Perl.
674       */
675 #ifndef PERL_COMPATIBLE
676         if (precision_specified) zero_padding = 0;
677 #endif
678         if (fmt_spec == 'd') {
679           if (force_sign && long_arg >= 0)
680             tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
681          /* leave negative numbers for sprintf to handle,
682             to avoid handling tricky cases like (short int)(-32768) */
683         } else if (alternative_form) {
684           if (long_arg != 0 && (fmt_spec == 'x' || fmt_spec == 'X') )
685             { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = fmt_spec; }
686 #ifdef HPUX_COMPATIBLE
687           else if (fmt_spec == 'p'
688          /* HPUX 10: for an alternative form of p conversion,
689           *          a nonzero result is prefixed by 0x. */
690 #ifndef HPUX_BUG_COMPATIBLE
691          /* Actually it uses 0x prefix even for a zero value. */
692                    && long_arg != 0
693 #endif
694                  ) { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = 'x'; }
695 #endif
696         }
697         zero_padding_insertion_ind = str_arg_l;
698         if (!precision_specified) precision = 1;   /* default precision is 1 */
699         if (precision == 0 && long_arg == 0
700 #ifdef HPUX_BUG_COMPATIBLE
701             && fmt_spec != 'p'
702          /* HPUX 10 man page claims: With conversion character p the result of
703           * converting a zero value with a precision of zero is a null string.
704           * Actually it returns all zeroes. */
705 #endif
706        ) {  /* converted to null string */  }
707         else {
708           char f[5]; int f_l = 0;
709           f[f_l++] = '%';
710           if (!data_type_modifier) { }
711           else if (data_type_modifier=='2') { f[f_l++] = 'l'; f[f_l++] = 'l'; }
712           else f[f_l++] = data_type_modifier;
713           f[f_l++] = fmt_spec; f[f_l++] = '\0';
714           if (fmt_spec == 'p') str_arg_l+=sprintf(tmp+str_arg_l, f, ptr_arg);
715           else {
716             switch (data_type_modifier) {
717             case '\0':
718             case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, int_arg);  break;
719             case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, long_arg); break;
720 #ifdef SNPRINTF_LONGLONG_SUPPORT
721             case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,long_long_arg); break;
722 #endif
723             }
724           }
725           if (zero_padding_insertion_ind < str_arg_l &&
726               tmp[zero_padding_insertion_ind] == '-')
727             zero_padding_insertion_ind++;
728         }
729         { int num_of_digits = str_arg_l - zero_padding_insertion_ind;
730           if (alternative_form && fmt_spec == 'o'
731 #ifdef HPUX_COMPATIBLE                                  /* ("%#.o",0) -> ""  */
732               && (str_arg_l > 0)
733 #endif
734 #ifdef DIGITAL_UNIX_BUG_COMPATIBLE                      /* ("%#o",0) -> "00" */
735 #else
736               && !(zero_padding_insertion_ind < str_arg_l
737                    && tmp[zero_padding_insertion_ind] == '0')
738 #endif
739          ) {      /* assure leading zero for alternative-form octal numbers */
740             if (!precision_specified || precision < num_of_digits+1)
741               { precision = num_of_digits+1; precision_specified = 1; }
742           }
743        /* zero padding to specified precision? */
744           if (num_of_digits < precision) 
745             number_of_zeros_to_pad = precision - num_of_digits;
746         }
747      /* zero padding to specified minimal field width? */
748         if (!justify_left && zero_padding) {
749           int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
750           if (n > 0) number_of_zeros_to_pad += n;
751         }
752         break;
753       default:  /* unrecognized format, keep format string unchanged */
754         zero_padding = 0;   /* turn zero padding off for non-numeric formats */
755 #ifndef DIGITAL_UNIX_COMPATIBLE
756         justify_left = 1; min_field_width = 0;                /* reset flags */
757 #endif
758 #ifdef PERL_COMPATIBLE
759      /* keep the entire format string unchanged */
760         str_arg = starting_p; str_arg_l = p - starting_p;
761 #else
762      /* discard the unrecognized format, just keep the unrecognized fmt char */
763         str_arg = p; str_arg_l = 0;
764 #endif
765         if (*p) str_arg_l++;  /* include invalid fmt specifier if not at EOS */
766         break;
767       }
768       if (*p) p++;          /* step over the just processed format specifier */
769    /* insert padding to the left as requested by min_field_width */
770       if (!justify_left) {                /* left padding with blank or zero */
771         int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
772         if (n > 0) {
773           int avail = (int)(str_m-str_l);
774           if (avail > 0) {      /* memset(str+str_l, zp, (n>avail?avail:n)); */
775             const char zp = (zero_padding ? '0' : ' ');
776             register int k; register char *r;
777             for (r=str+str_l, k=(n>avail?avail:n); k>0; k--) *r++ = zp;
778           }
779           str_l += n;
780         }
781       }
782    /* zero padding as requested by the precision for numeric formats requred?*/
783       if (number_of_zeros_to_pad <= 0) {
784      /* will not copy first part of numeric here,   *
785       * force it to be copied later in its entirety */
786         zero_padding_insertion_ind = 0;
787       } else {
788      /* insert first part of numerics (sign or '0x') before zero padding */
789         int n = zero_padding_insertion_ind;
790         if (n > 0) {
791           int avail = (int)(str_m-str_l);
792           if (avail > 0) memcpy(str+str_l, str_arg, (size_t)(n>avail?avail:n));
793           str_l += n;
794         }
795      /* insert zero padding as requested by the precision */
796         n = number_of_zeros_to_pad;
797         if (n > 0) {
798           int avail = (int)(str_m-str_l);
799           if (avail > 0) {     /* memset(str+str_l, '0', (n>avail?avail:n)); */
800             register int k; register char *r;
801             for (r=str+str_l, k=(n>avail?avail:n); k>0; k--) *r++ = '0';
802           }
803           str_l += n;
804         }
805       }
806    /* insert formatted string (or unmodified format for unknown formats) */
807       { int n = str_arg_l - zero_padding_insertion_ind;
808         if (n > 0) {
809           int avail = (int)(str_m-str_l);
810           if (avail > 0) memcpy(str+str_l, str_arg+zero_padding_insertion_ind,
811                                 (size_t)(n>avail ? avail : n) );
812           str_l += n;
813         }
814       }
815    /* insert right padding */
816       if (justify_left) {          /* right blank padding to the field width */
817         int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
818         if (n > 0) {
819           int avail = (int)(str_m-str_l);
820           if (avail > 0) {     /* memset(str+str_l, ' ', (n>avail?avail:n)); */
821             register int k; register char *r;
822             for (r=str+str_l, k=(n>avail?avail:n); k>0; k--) *r++ = ' ';
823           }
824           str_l += n;
825         }
826       }
827     }
828   }
829 #if defined(NEED_SNPRINTF_ONLY)
830   va_end(ap);
831 #endif
832   if (str_m > 0) { /* make sure the string is null-terminated
833                       even at the expense of overwriting the last character */
834     str[str_l <= str_m-1 ? str_l : str_m-1] = '\0';
835   }
836
837   return str_l;    /* return the number of characters formatted
838                       (excluding trailing null character),
839                       that is, the number of characters that would have been
840                       written to the buffer if it were large enough */
841 }
842 #endif