]> git.lyx.org Git - features.git/blob - src/support/snprintf.c
make vsnprintf work on systems without it
[features.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
244 \f
245 /* ============================================= */
246 /* NO USER SERVICABLE PARTS FOLLOWING THIS POINT */
247 /* ============================================= */
248
249 #define PORTABLE_SNPRINTF_VERSION_MAJOR 2
250 #define PORTABLE_SNPRINTF_VERSION_MINOR 1
251
252 #if defined(NEED_ASPRINTF) || defined(NEED_ASNPRINTF) || defined(NEED_VASPRINTF) || defined(NEED_VASNPRINTF)
253 # if defined(NEED_SNPRINTF_ONLY)
254 # undef NEED_SNPRINTF_ONLY
255 # endif
256 # if !defined(PREFER_PORTABLE_SNPRINTF)
257 # define PREFER_PORTABLE_SNPRINTF
258 # endif
259 #endif
260
261 #if defined(SOLARIS_BUG_COMPATIBLE) && !defined(SOLARIS_COMPATIBLE)
262 #define SOLARIS_COMPATIBLE
263 #endif
264
265 #if defined(HPUX_BUG_COMPATIBLE) && !defined(HPUX_COMPATIBLE)
266 #define HPUX_COMPATIBLE
267 #endif
268
269 #if defined(DIGITAL_UNIX_BUG_COMPATIBLE) && !defined(DIGITAL_UNIX_COMPATIBLE)
270 #define DIGITAL_UNIX_COMPATIBLE
271 #endif
272
273 #if defined(PERL_BUG_COMPATIBLE) && !defined(PERL_COMPATIBLE)
274 #define PERL_COMPATIBLE
275 #endif
276
277 #include <sys/types.h>
278 #include <string.h>
279 #include <stdlib.h>
280 #include <stdio.h>
281 #include <stdarg.h>
282 #include <assert.h>
283 #include <errno.h>
284
285 #ifdef isdigit
286 #undef isdigit
287 #endif
288 #define isdigit(c) ((c) >= '0' && (c) <= '9')
289
290 /* prototypes */
291
292 #if defined(NEED_ASPRINTF)
293 int asprintf   (char **ptr, const char *fmt, /*args*/ ...);
294 #endif
295 #if defined(NEED_VASPRINTF)
296 int vasprintf  (char **ptr, const char *fmt, va_list ap);
297 #endif
298 #if defined(NEED_ASNPRINTF)
299 int asnprintf  (char **ptr, size_t str_m, const char *fmt, /*args*/ ...);
300 #endif
301 #if defined(NEED_VASNPRINTF)
302 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap);
303 #endif
304
305 #define va_copy(ap2,ap) ap2 = ap
306
307 #if defined(HAVE_SNPRINTF)
308 /* declare our portable snprintf  routine under name portable_snprintf  */
309 /* declare our portable vsnprintf routine under name portable_vsnprintf */
310 #else
311 /* declare our portable routines under names snprintf and vsnprintf */
312 #define portable_snprintf snprintf
313 #if !defined(NEED_SNPRINTF_ONLY)
314 #define portable_vsnprintf vsnprintf
315 #endif
316 #endif
317
318 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
319 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...);
320 #if !defined(NEED_SNPRINTF_ONLY)
321 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap);
322 #endif
323 #endif
324
325 /* declarations */
326
327 #if !defined(lint)
328 static char credits[] = "\n\
329 @(#)snprintf.c, v2.1: Mark Martinec, <mark.martinec@ijs.si>\n\
330 @(#)snprintf.c, v2.1: Copyright 1999, Mark Martinec. Artistic license applies.\n\
331 @(#)snprintf.c, v2.1: http://www.ijs.si/software/snprintf/\n";
332 #endif
333
334 #if defined(NEED_ASPRINTF)
335 int asprintf(char **ptr, const char *fmt, /*args*/ ...) {
336   va_list ap;
337   size_t str_m;
338   int str_l;
339
340   *ptr = NULL;
341   va_start(ap, fmt);                            /* measure the required size */
342   str_l = portable_vsnprintf(NULL, (size_t) 0, fmt, ap);
343   va_end(ap);
344   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
345   *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
346   if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
347   else {
348     int str_l2;
349     va_start(ap, fmt);
350     str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
351     va_end(ap);
352     assert(str_l2 == str_l);
353   }
354   return str_l;
355 }
356 #endif
357
358 #if defined(NEED_VASPRINTF)
359 int vasprintf(char **ptr, const char *fmt, va_list ap) {
360   size_t str_m;
361   int str_l;
362
363   *ptr = NULL;
364   { va_list ap2;
365     va_copy(ap2, ap);  /* don't consume the original ap, we'll need it again */
366                        /* measure the required size: */
367     str_l = portable_vsnprintf(NULL, (size_t) 0, fmt, ap2);
368     va_end(ap2);
369   }
370   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
371   *ptr = (char *) malloc(str_m = (size_t)str_l + 1);
372   if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
373   else {
374     int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
375     assert(str_l2 == str_l);
376   }
377   return str_l;
378 }
379 #endif
380
381 #if defined(NEED_ASNPRINTF)
382 int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...) {
383   va_list ap;
384   int str_l;
385
386   *ptr = NULL;
387   va_start(ap, fmt);                            /* measure the required size */
388   str_l = portable_vsnprintf(NULL, (size_t) 0, fmt, ap);
389   va_end(ap);
390   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
391   if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1;      /* truncate */
392   /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
393   if (str_m == 0) {  /* not interested in resulting string, just return size */
394   } else {
395     *ptr = (char *) malloc(str_m);
396     if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
397     else {
398       int str_l2;
399       va_start(ap, fmt);
400       str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
401       va_end(ap);
402       assert(str_l2 == str_l);
403     }
404   }
405   return str_l;
406 }
407 #endif
408
409 #if defined(NEED_VASNPRINTF)
410 int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap) {
411   int str_l;
412
413   *ptr = NULL;
414   { va_list ap2;
415     va_copy(ap2, ap);  /* don't consume the original ap, we'll need it again */
416                        /* measure the required size: */
417     str_l = portable_vsnprintf(NULL, (size_t) 0, fmt, ap2);
418     va_end(ap2);
419   }
420   assert(str_l >= 0);        /* possible integer overflow if str_m > INT_MAX */
421   if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1;      /* truncate */
422   /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */
423   if (str_m == 0) {  /* not interested in resulting string, just return size */
424   } else {
425     *ptr = (char *) malloc(str_m);
426     if (*ptr == NULL) { errno = ENOMEM; str_l = -1; }
427     else {
428       int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap);
429       assert(str_l2 == str_l);
430     }
431   }
432   return str_l;
433 }
434 #endif
435
436 /*
437  * If the system does have snprintf and the portable routine is not
438  * specifically required, this module produces no code for snprintf/vsnprintf.
439  */
440 #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF)
441
442 #if !defined(NEED_SNPRINTF_ONLY)
443 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
444   va_list ap;
445   int str_l;
446
447   va_start(ap, fmt);
448   str_l = portable_vsnprintf(str, str_m, fmt, ap);
449   va_end(ap);
450   return str_l;
451 }
452 #endif
453
454 #if defined(NEED_SNPRINTF_ONLY)
455 int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) {
456 #else
457 int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap) {
458 #endif
459
460 #if defined(NEED_SNPRINTF_ONLY)
461   va_list ap;
462 #endif
463   size_t str_l = 0;
464   const char *p = fmt;
465
466 /* In contrast with POSIX, the ISO C9X now says
467  * that str can be NULL and str_m can be 0. This is more useful. */
468 /*if (str_m < 1) return -1;*/
469
470 #if defined(NEED_SNPRINTF_ONLY)
471   va_start(ap, fmt);
472 #endif
473   if (!p) p = "";
474   while (*p) {
475     if (*p != '%') {
476    /* if (str_l < str_m) str[str_l++] = *p++;    -- this would be sufficient */
477    /* but the following code achieves better performance for cases
478     * where format string is long and contains few conversions */
479       const char *q = strchr(p+1,'%');
480       int n = !q ? strlen(p) : (q-p);
481       int avail = (int)(str_m-str_l);
482       if (avail > 0) {
483         register int k; register char *r; register const char* p1;
484         for (p1=p, r=str+str_l, k=(n>avail?avail:n); k>0; k--) *r++ = *p1++;
485       }
486       p += n; str_l += n;
487     } else {
488       const char *starting_p;
489       int min_field_width = 0, precision = 0;
490       int zero_padding = 0, precision_specified = 0, justify_left = 0;
491       int alternative_form = 0, force_sign = 0;
492       int space_for_positive = 1; /* If both the ' ' and '+' flags appear,
493                                      the ' ' flag should be ignored. */
494       char data_type_modifier = '\0';      /* allowed valued: \0, h, l, L, p */
495       char tmp[32];/* temporary buffer for simple numeric->string conversion */
496
497       const char *str_arg = 0;/* string address in case of string arguments  */
498       int str_arg_l;  /* natural field width of arg without padding and sign */
499
500       long int long_arg;  /* long int argument value - always defined
501         in case of numeric arguments, regardless of data type modifiers.
502         In case of data type modifier 'll' the value is stored in long_long_arg
503         and only the sign of long_arg is guaranteed to be correct */
504       void *ptr_arg; /* pointer argument value - only defined for p format   */
505       int int_arg;   /* int argument value - only defined if no h or l modif.*/
506 #ifdef SNPRINTF_LONGLONG_SUPPORT
507       long long int long_long_arg = 0;  /* long long argument value - only
508                                            defined if ll modifier is present */
509 #endif
510       int number_of_zeros_to_pad = 0;
511       int zero_padding_insertion_ind = 0;
512       char fmt_spec = '\0';            /* current format specifier character */
513
514       starting_p = p; p++;  /* skip '%' */
515    /* parse flags */
516       while (*p == '0' || *p == '-' || *p == '+' ||
517              *p == ' ' || *p == '#' || *p == '\'') {
518         switch (*p) {
519         case '0': zero_padding = 1; break;
520         case '-': justify_left = 1; break;
521         case '+': force_sign = 1; space_for_positive = 0; break;
522         case ' ': force_sign = 1;
523      /* If both the ' ' and '+' flags appear, the ' ' flag should be ignored */
524 #ifdef PERL_COMPATIBLE
525      /* ... but in Perl the last of ' ' and '+' applies */
526                   space_for_positive = 1;
527 #endif
528                   break;
529         case '#': alternative_form = 1; break;
530         case '\'': break;
531         }
532         p++;
533       }
534    /* If the '0' and '-' flags both appear, the '0' flag should be ignored. */
535
536    /* parse field width */
537       if (*p == '*') {
538         p++; min_field_width = va_arg(ap, int);
539         if (min_field_width < 0)
540           { min_field_width = -min_field_width; justify_left = 1; }
541       } else if (isdigit((int)(*p))) {
542         min_field_width = *p++ - '0';
543         while (isdigit((int)(*p)))
544           min_field_width = 10*min_field_width + (*p++ - '0');
545       }
546    /* parse precision */
547       if (*p == '.') {
548         p++; precision_specified = 1;
549         if (*p == '*') {
550           p++; precision = va_arg(ap, int);
551           if (precision < 0) {
552             precision_specified = 0; precision = 0;
553          /* NOTE:
554           *   Solaris 2.6 man page claims that in this case the precision
555           *   should be set to 0.  Digital Unix 4.0 and HPUX 10 man page
556           *   claim that this case should be treated as unspecified precision,
557           *   which is what we do here.
558           */
559           }
560         } else if (isdigit((int)(*p))) {
561           precision = *p++ - '0';
562           while (isdigit((int)(*p))) precision = 10*precision + (*p++ - '0');
563         }
564       }
565    /* parse 'h', 'l' and 'll' data type modifiers */
566       if (*p == 'h' || *p == 'l') {
567         data_type_modifier = *p; p++;
568         if (data_type_modifier == 'l' && *p == 'l') {/* double l = long long */
569 #ifdef SNPRINTF_LONGLONG_SUPPORT
570           data_type_modifier = '2';               /* double l encoded as '2' */
571 #else
572           data_type_modifier = 'l';                /* treat it as single 'l' */
573 #endif
574           p++;
575         }
576       }
577       fmt_spec = *p;
578    /* common synonyms: */
579       switch (fmt_spec) {
580       case 'i': fmt_spec = 'd'; break;
581       case 'D': fmt_spec = 'd'; data_type_modifier = 'l'; break;
582       case 'U': fmt_spec = 'u'; data_type_modifier = 'l'; break;
583       case 'O': fmt_spec = 'o'; data_type_modifier = 'l'; break;
584       default: break;
585       }
586    /* get parameter value, do initial processing */
587       switch (fmt_spec) {
588       case '%': /* % behaves similar to 's' regarding flags and field widths */
589       case 'c': /* c behaves similar to 's' regarding flags and field widths */
590       case 's':
591         data_type_modifier = '\0';       /* wint_t and wchar_t not supported */
592      /* the result of zero padding flag with non-numeric format is undefined */
593      /* Solaris and HPUX 10 does zero padding in this case, Digital Unix not */
594 #ifdef DIGITAL_UNIX_COMPATIBLE
595         zero_padding = 0;        /* turn zero padding off for string formats */
596 #endif
597         str_arg_l = 1;
598         switch (fmt_spec) {
599         case '%':
600           str_arg = p; break;
601         case 'c':
602           { int j = va_arg(ap, int); str_arg = (const char*) &j; }
603           break;
604         case 's':
605           str_arg = va_arg(ap, const char *);
606           if (!str_arg) str_arg_l = 0;
607        /* make sure not to address string beyond the specified precision !!! */
608           else if (!precision_specified) str_arg_l = strlen(str_arg);
609        /* truncate string if necessary as requested by precision */
610           else if (precision <= 0) str_arg_l = 0;
611           else {
612             const char *q = memchr(str_arg,'\0',(size_t)precision);
613             str_arg_l = !q ? precision : (q-str_arg);
614           }
615           break;
616         default: break;
617         }
618         break;
619       case 'd': case 'o': case 'u': case 'x': case 'X': case 'p':
620         long_arg = 0; int_arg = 0; ptr_arg = NULL;
621         if (fmt_spec == 'p') {
622         /* HPUX 10: An l, h, ll or L before any other conversion character
623          *   (other than d, i, o, u, x, or X) is ignored.
624          * Digital Unix:
625          *   not specified, but seems to behave as HPUX does.
626          * Solaris: If an h, l, or L appears before any other conversion
627          *   specifier (other than d, i, o, u, x, or X), the behavior
628          *   is undefined. (Actually %hp converts only 16-bits of address
629          *   and %llp treats address as 64-bit data which is incompatible
630          *   with (void *) argument on a 32-bit system).
631          */
632 #ifdef SOLARIS_COMPATIBLE
633 #  ifdef SOLARIS_BUG_COMPATIBLE
634           /* keep data type modifiers even if it represents 'll' */
635 #  else
636           if (data_type_modifier == '2') data_type_modifier = '\0';
637 #  endif
638 #else
639           data_type_modifier = '\0';
640 #endif
641           ptr_arg = va_arg(ap, void *); long_arg = !ptr_arg ? 0 : 1;
642         } else {
643           switch (data_type_modifier) {
644           case '\0':
645           case 'h':
646          /* It is non-portable to specify a second argument of char or short
647           * to va_arg, because arguments seen by the called function
648           * are not char or short.  C converts char and short arguments
649           * to int before passing them to a function.
650           */
651             int_arg = va_arg(ap, int); long_arg = int_arg; break;
652           case 'l':
653             long_arg = va_arg(ap, long int); break;
654 #ifdef SNPRINTF_LONGLONG_SUPPORT
655           case '2':
656             long_long_arg = va_arg(ap, long long int);
657             /* only the sign of long_arg is guaranteed */
658             if      (long_long_arg > 0) long_arg = +1;
659             else if (long_long_arg < 0) long_arg = -1;
660             else long_arg = 0;
661             break;
662 #endif
663           }
664         }
665         str_arg = tmp; str_arg_l = 0;
666      /* NOTE:
667       *   For d, i, o, u, x, and X conversions, if precision is specified,
668       *   the '0' flag should be ignored. This is so with Solaris 2.6,
669       *   Digital UNIX 4.0 and HPUX 10;  but not with Perl.
670       */
671 #ifndef PERL_COMPATIBLE
672         if (precision_specified) zero_padding = 0;
673 #endif
674         if (fmt_spec == 'd') {
675           if (force_sign && long_arg >= 0)
676             tmp[str_arg_l++] = space_for_positive ? ' ' : '+';
677          /* leave negative numbers for sprintf to handle,
678             to avoid handling tricky cases like (short int)(-32768) */
679         } else if (alternative_form) {
680           if (long_arg != 0 && (fmt_spec == 'x' || fmt_spec == 'X') )
681             { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = fmt_spec; }
682 #ifdef HPUX_COMPATIBLE
683           else if (fmt_spec == 'p'
684          /* HPUX 10: for an alternative form of p conversion,
685           *          a nonzero result is prefixed by 0x. */
686 #ifndef HPUX_BUG_COMPATIBLE
687          /* Actually it uses 0x prefix even for a zero value. */
688                    && long_arg != 0
689 #endif
690                   ) { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = 'x'; }
691 #endif
692         }
693         zero_padding_insertion_ind = str_arg_l;
694         if (!precision_specified) precision = 1;   /* default precision is 1 */
695         if (precision == 0 && long_arg == 0
696 #ifdef HPUX_BUG_COMPATIBLE
697             && fmt_spec != 'p'
698          /* HPUX 10 man page claims: With conversion character p the result of
699           * converting a zero value with a precision of zero is a null string.
700           * Actually it returns all zeroes. */
701 #endif
702         ) {  /* converted to null string */  }
703         else {
704           char f[5]; int f_l = 0;
705           f[f_l++] = '%';
706           if (!data_type_modifier) { }
707           else if (data_type_modifier=='2') { f[f_l++] = 'l'; f[f_l++] = 'l'; }
708           else f[f_l++] = data_type_modifier;
709           f[f_l++] = fmt_spec; f[f_l++] = '\0';
710           if (fmt_spec == 'p') str_arg_l+=sprintf(tmp+str_arg_l, f, ptr_arg);
711           else {
712             switch (data_type_modifier) {
713             case '\0':
714             case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, int_arg);  break;
715             case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, long_arg); break;
716 #ifdef SNPRINTF_LONGLONG_SUPPORT
717             case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,long_long_arg); break;
718 #endif
719             }
720           }
721           if (zero_padding_insertion_ind < str_arg_l &&
722               tmp[zero_padding_insertion_ind] == '-')
723             zero_padding_insertion_ind++;
724         }
725         { int num_of_digits = str_arg_l - zero_padding_insertion_ind;
726           if (alternative_form && fmt_spec == 'o'
727 #ifdef HPUX_COMPATIBLE                                  /* ("%#.o",0) -> ""  */
728               && (str_arg_l > 0)
729 #endif
730 #ifdef DIGITAL_UNIX_BUG_COMPATIBLE                      /* ("%#o",0) -> "00" */
731 #else
732               && !(zero_padding_insertion_ind < str_arg_l
733                    && tmp[zero_padding_insertion_ind] == '0')
734 #endif
735           ) {      /* assure leading zero for alternative-form octal numbers */
736             if (!precision_specified || precision < num_of_digits+1)
737               { precision = num_of_digits+1; precision_specified = 1; }
738           }
739        /* zero padding to specified precision? */
740           if (num_of_digits < precision) 
741             number_of_zeros_to_pad = precision - num_of_digits;
742         }
743      /* zero padding to specified minimal field width? */
744         if (!justify_left && zero_padding) {
745           int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
746           if (n > 0) number_of_zeros_to_pad += n;
747         }
748         break;
749       default:  /* unrecognized format, keep format string unchanged */
750         zero_padding = 0;   /* turn zero padding off for non-numeric formats */
751 #ifndef DIGITAL_UNIX_COMPATIBLE
752         justify_left = 1; min_field_width = 0;                /* reset flags */
753 #endif
754 #ifdef PERL_COMPATIBLE
755      /* keep the entire format string unchanged */
756         str_arg = starting_p; str_arg_l = p - starting_p;
757 #else
758      /* discard the unrecognized format, just keep the unrecognized fmt char */
759         str_arg = p; str_arg_l = 0;
760 #endif
761         if (*p) str_arg_l++;  /* include invalid fmt specifier if not at EOS */
762         break;
763       }
764       if (*p) p++;          /* step over the just processed format specifier */
765    /* insert padding to the left as requested by min_field_width */
766       if (!justify_left) {                /* left padding with blank or zero */
767         int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
768         if (n > 0) {
769           int avail = (int)(str_m-str_l);
770           if (avail > 0) {      /* memset(str+str_l, zp, (n>avail?avail:n)); */
771             const char zp = (zero_padding ? '0' : ' ');
772             register int k; register char *r;
773             for (r=str+str_l, k=(n>avail?avail:n); k>0; k--) *r++ = zp;
774           }
775           str_l += n;
776         }
777       }
778    /* zero padding as requested by the precision for numeric formats requred?*/
779       if (number_of_zeros_to_pad <= 0) {
780      /* will not copy first part of numeric here,   *
781       * force it to be copied later in its entirety */
782         zero_padding_insertion_ind = 0;
783       } else {
784      /* insert first part of numerics (sign or '0x') before zero padding */
785         int n = zero_padding_insertion_ind;
786         if (n > 0) {
787           int avail = (int)(str_m-str_l);
788           if (avail > 0) memcpy(str+str_l, str_arg, (size_t)(n>avail?avail:n));
789           str_l += n;
790         }
791      /* insert zero padding as requested by the precision */
792         n = number_of_zeros_to_pad;
793         if (n > 0) {
794           int avail = (int)(str_m-str_l);
795           if (avail > 0) {     /* memset(str+str_l, '0', (n>avail?avail:n)); */
796             register int k; register char *r;
797             for (r=str+str_l, k=(n>avail?avail:n); k>0; k--) *r++ = '0';
798           }
799           str_l += n;
800         }
801       }
802    /* insert formatted string (or unmodified format for unknown formats) */
803       { int n = str_arg_l - zero_padding_insertion_ind;
804         if (n > 0) {
805           int avail = (int)(str_m-str_l);
806           if (avail > 0) memcpy(str+str_l, str_arg+zero_padding_insertion_ind,
807                                 (size_t)(n>avail ? avail : n) );
808           str_l += n;
809         }
810       }
811    /* insert right padding */
812       if (justify_left) {          /* right blank padding to the field width */
813         int n = min_field_width - (str_arg_l+number_of_zeros_to_pad);
814         if (n > 0) {
815           int avail = (int)(str_m-str_l);
816           if (avail > 0) {     /* memset(str+str_l, ' ', (n>avail?avail:n)); */
817             register int k; register char *r;
818             for (r=str+str_l, k=(n>avail?avail:n); k>0; k--) *r++ = ' ';
819           }
820           str_l += n;
821         }
822       }
823     }
824   }
825 #if defined(NEED_SNPRINTF_ONLY)
826   va_end(ap);
827 #endif
828   if (str_m > 0) { /* make sure the string is null-terminated
829                       even at the expense of overwriting the last character */
830     str[str_l <= str_m-1 ? str_l : str_m-1] = '\0';
831   }
832
833   return str_l;    /* return the number of characters formatted
834                       (excluding trailing null character),
835                       that is, the number of characters that would have been
836                       written to the buffer if it were large enough */
837 }
838 #endif