Debian Codegraph @

matio-1.5.30/snprintf/snprintf.c

raw symbols SCIP
1 /*
2 * Copyright (c) 1995 Patrick Powell.
3 *
4 * This code is based on code written by Patrick Powell <[email protected]>.
5 * It may be used for any purpose as long as this notice remains intact on all
6 * source code distributions.
7 */
8
9 /*
10 * Copyright (c) 2008 Holger Weiss.
11 *
12 * This version of the code is maintained by Holger Weiss <[email protected]>.
13 * My changes to the code may freely be used, modified and/or redistributed for
14 * any purpose. It would be nice if additions and fixes to this file (including
15 * trivial code cleanups) would be sent back in order to let me include them in
16 * the version available at <http://www.jhweiss.de/software/snprintf.html>.
17 * However, this is not a requirement for using or redistributing (possibly
18 * modified) versions of this file, nor is leaving this notice intact mandatory.
19 */
20
21 /*
22 * History
23 *
24 * 2008-01-20 Holger Weiss <[email protected]> for C99-snprintf 1.1:
25 *
26 * Fixed the detection of infinite floating point values on IRIX (and
27 * possibly other systems) and applied another few minor cleanups.
28 *
29 * 2008-01-06 Holger Weiss <[email protected]> for C99-snprintf 1.0:
30 *
31 * Added a lot of new features, fixed many bugs, and incorporated various
32 * improvements done by Andrew Tridgell <[email protected]>, Russ Allbery
33 * <[email protected]>, Hrvoje Niksic <[email protected]>, Damien Miller
34 * <[email protected]>, and others for the Samba, INN, Wget, and OpenSSH
35 * projects. The additions include: support the "e", "E", "g", "G", and
36 * "F" conversion specifiers (and use conversion style "f" or "F" for the
37 * still unsupported "a" and "A" specifiers); support the "hh", "ll", "j",
38 * "t", and "z" length modifiers; support the "#" flag and the (non-C99)
39 * "'" flag; use localeconv(3) (if available) to get both the current
40 * locale's decimal point character and the separator between groups of
41 * digits; fix the handling of various corner cases of field width and
42 * precision specifications; fix various floating point conversion bugs;
43 * handle infinite and NaN floating point values; don't attempt to write to
44 * the output buffer (which may be NULL) if a size of zero was specified;
45 * check for integer overflow of the field width, precision, and return
46 * values and during the floating point conversion; use the OUTCHAR() macro
47 * instead of a function for better performance; provide asprintf(3) and
48 * vasprintf(3) functions; add new test cases. The replacement functions
49 * have been renamed to use an "rpl_" prefix, the function calls in the
50 * main project (and in this file) must be redefined accordingly for each
51 * replacement function which is needed (by using Autoconf or other means).
52 * Various other minor improvements have been applied and the coding style
53 * was cleaned up for consistency.
54 *
55 * 2007-07-23 Holger Weiss <[email protected]> for Mutt 1.5.13:
56 *
57 * C99 compliant snprintf(3) and vsnprintf(3) functions return the number
58 * of characters that would have been written to a sufficiently sized
59 * buffer (excluding the '\0'). The original code simply returned the
60 * length of the resulting output string, so that's been fixed.
61 *
62 * 1998-03-05 Michael Elkins <[email protected]> for Mutt 0.90.8:
63 *
64 * The original code assumed that both snprintf(3) and vsnprintf(3) were
65 * missing. Some systems only have snprintf(3) but not vsnprintf(3), so
66 * the code is now broken down under HAVE_SNPRINTF and HAVE_VSNPRINTF.
67 *
68 * 1998-01-27 Thomas Roessler <[email protected]> for Mutt 0.89i:
69 *
70 * The PGP code was using unsigned hexadecimal formats. Unfortunately,
71 * unsigned formats simply didn't work.
72 *
73 * 1997-10-22 Brandon Long <[email protected]> for Mutt 0.87.1:
74 *
75 * Ok, added some minimal floating point support, which means this probably
76 * requires libm on most operating systems. Don't yet support the exponent
77 * (e,E) and sigfig (g,G). Also, fmtint() was pretty badly broken, it just
78 * wasn't being exercised in ways which showed it, so that's been fixed.
79 * Also, formatted the code to Mutt conventions, and removed dead code left
80 * over from the original. Also, there is now a builtin-test, run with:
81 * gcc -DTEST_SNPRINTF -o snprintf snprintf.c -lm && ./snprintf
82 *
83 * 2996-09-15 Brandon Long <[email protected]> for Mutt 0.43:
84 *
85 * This was ugly. It is still ugly. I opted out of floating point
86 * numbers, but the formatter understands just about everything from the
87 * normal C string format, at least as far as I can tell from the Solaris
88 * 2.5 printf(3S) man page.
89 */
90
91 /*
92 * ToDo
93 *
94 * - Add wide character support.
95 * - Add support for "%a" and "%A" conversions.
96 * - Create test routines which predefine the expected results. Our test cases
97 * usually expose bugs in system implementations rather than in ours :-)
98 */
99
100 /*
101 * Usage
102 *
103 * 1) The following preprocessor macros should be defined to 1 if the feature or
104 * file in question is available on the target system (by using Autoconf or
105 * other means), though basic functionality should be available as long as
106 * HAVE_STDARG_H and HAVE_STDLIB_H are defined correctly:
107 *
108 * HAVE_VSNPRINTF
109 * HAVE_SNPRINTF
110 * HAVE_VASPRINTF
111 * HAVE_ASPRINTF
112 * HAVE_STDARG_H
113 * HAVE_STDDEF_H
114 * HAVE_STDINT_H
115 * HAVE_STDLIB_H
116 * HAVE_FLOAT_H
117 * HAVE_INTTYPES_H
118 * HAVE_LOCALE_H
119 * HAVE_LOCALECONV
120 * HAVE_LCONV_DECIMAL_POINT
121 * HAVE_LCONV_THOUSANDS_SEP
122 * HAVE_LONG_DOUBLE
123 * HAVE_LONG_LONG_INT
124 * HAVE_UNSIGNED_LONG_LONG_INT
125 * HAVE_INTMAX_T
126 * HAVE_UINTMAX_T
127 * HAVE_UINTPTR_T
128 * HAVE_PTRDIFF_T
129 * HAVE_VA_COPY
130 * HAVE___VA_COPY
131 *
132 * 2) The calls to the functions which should be replaced must be redefined
133 * throughout the project files (by using Autoconf or other means):
134 *
135 * #define vsnprintf rpl_vsnprintf
136 * #define snprintf rpl_snprintf
137 * #define vasprintf rpl_vasprintf
138 * #define asprintf rpl_asprintf
139 *
140 * 3) The required replacement functions should be declared in some header file
141 * included throughout the project files:
142 *
143 * #if HAVE_CONFIG_H
144 * #include <config.h>
145 * #endif
146 * #if HAVE_STDARG_H
147 * #include <stdarg.h>
148 * #if !HAVE_VSNPRINTF
149 * int rpl_vsnprintf(char *, size_t, const char *, va_list);
150 * #endif
151 * #if !HAVE_SNPRINTF
152 * int rpl_snprintf(char *, size_t, const char *, ...);
153 * #endif
154 * #if !HAVE_VASPRINTF
155 * int rpl_vasprintf(char **, const char *, va_list);
156 * #endif
157 * #if !HAVE_ASPRINTF
158 * int rpl_asprintf(char **, const char *, ...);
159 * #endif
160 * #endif
161 *
162 * Autoconf macros for handling step 1 and step 2 are available at
163 * <http://www.jhweiss.de/software/snprintf.html>.
164 */
165
166 #include "matioConfig.h"
167
168 #if !HAVE_SNPRINTF || !HAVE_VSNPRINTF || !HAVE_ASPRINTF || !HAVE_VASPRINTF
169 #include <stdio.h> /* For NULL, size_t, vsnprintf(3), and vasprintf(3). */
170 #ifdef VA_START
171 #undef VA_START
172 #endif /* defined(VA_START) */
173 #ifdef VA_SHIFT
174 #undef VA_SHIFT
175 #endif /* defined(VA_SHIFT) */
176 #if HAVE_STDARG_H
177 #include <stdarg.h>
178 #define VA_START(ap, last) va_start(ap, last)
179 #define VA_SHIFT(ap, value, type) /* No-op for ANSI C. */
180 #else /* Assume <varargs.h> is available. */
181 #include <varargs.h>
182 #define VA_START(ap, last) va_start(ap) /* "last" is ignored. */
183 #define VA_SHIFT(ap, value, type) value = va_arg(ap, type)
184 #endif /* HAVE_STDARG_H */
185
186 #if !HAVE_VASPRINTF
187 #if HAVE_STDLIB_H
188 #include <stdlib.h> /* For malloc(3). */
189 #endif /* HAVE_STDLIB_H */
190 #ifdef VA_COPY
191 #undef VA_COPY
192 #endif /* defined(VA_COPY) */
193 #ifdef VA_END_COPY
194 #undef VA_END_COPY
195 #endif /* defined(VA_END_COPY) */
196 #if HAVE_VA_COPY
197 #define VA_COPY(dest, src) va_copy(dest, src)
198 #define VA_END_COPY(ap) va_end(ap)
199 #elif HAVE___VA_COPY
200 #define VA_COPY(dest, src) __va_copy(dest, src)
201 #define VA_END_COPY(ap) va_end(ap)
202 #else
203 #define VA_COPY(dest, src) (void)mymemcpy(&dest, &src, sizeof(va_list))
204 #define VA_END_COPY(ap) /* No-op. */
205 #define NEED_MYMEMCPY 1
206 static void *mymemcpy(void *, const void *, size_t);
207 #endif /* HAVE_VA_COPY */
208 #endif /* !HAVE_VASPRINTF */
209
210 #if !HAVE_VSNPRINTF
211 #include <errno.h> /* For ERANGE and errno. */
212 #include <limits.h> /* For *_MAX. */
213 #if HAVE_FLOAT_H
214 #include <float.h> /* For *DBL_{MIN,MAX}_10_EXP. */
215 #endif /* HAVE_FLOAT_H */
216 #if HAVE_INTTYPES_H
217 #include <inttypes.h> /* For intmax_t (if not defined in <stdint.h>). */
218 #endif /* HAVE_INTTYPES_H */
219 #if HAVE_LOCALE_H
220 #include <locale.h> /* For localeconv(3). */
221 #endif /* HAVE_LOCALE_H */
222 #if HAVE_STDDEF_H
223 #include <stddef.h> /* For ptrdiff_t. */
224 #endif /* HAVE_STDDEF_H */
225 #if HAVE_STDINT_H
226 #include <stdint.h> /* For intmax_t. */
227 #endif /* HAVE_STDINT_H */
228
229 /* Support for unsigned long long int. We may also need ULLONG_MAX. */
230 #ifndef ULONG_MAX /* We may need ULONG_MAX as a fallback. */
231 #ifdef UINT_MAX
232 #define ULONG_MAX UINT_MAX
233 #else
234 #define ULONG_MAX INT_MAX
235 #endif /* defined(UINT_MAX) */
236 #endif /* !defined(ULONG_MAX) */
237 #ifdef ULLONG
238 #undef ULLONG
239 #endif /* defined(ULLONG) */
240 #if HAVE_UNSIGNED_LONG_LONG_INT
241 #define ULLONG unsigned long long int
242 #ifndef ULLONG_MAX
243 #define ULLONG_MAX ULONG_MAX
244 #endif /* !defined(ULLONG_MAX) */
245 #else
246 #define ULLONG unsigned long int
247 #ifdef ULLONG_MAX
248 #undef ULLONG_MAX
249 #endif /* defined(ULLONG_MAX) */
250 #define ULLONG_MAX ULONG_MAX
251 #endif /* HAVE_LONG_LONG_INT */
252
253 /* Support for uintmax_t. We also need UINTMAX_MAX. */
254 #ifdef UINTMAX_T
255 #undef UINTMAX_T
256 #endif /* defined(UINTMAX_T) */
257 #if HAVE_UINTMAX_T || defined(uintmax_t)
258 #define UINTMAX_T uintmax_t
259 #ifndef UINTMAX_MAX
260 #define UINTMAX_MAX ULLONG_MAX
261 #endif /* !defined(UINTMAX_MAX) */
262 #else
263 #define UINTMAX_T ULLONG
264 #ifdef UINTMAX_MAX
265 #undef UINTMAX_MAX
266 #endif /* defined(UINTMAX_MAX) */
267 #define UINTMAX_MAX ULLONG_MAX
268 #endif /* HAVE_UINTMAX_T || defined(uintmax_t) */
269
270 /* Support for long double. */
271 #ifndef LDOUBLE
272 #if HAVE_LONG_DOUBLE
273 #define LDOUBLE long double
274 #define LDOUBLE_MIN_10_EXP LDBL_MIN_10_EXP
275 #define LDOUBLE_MAX_10_EXP LDBL_MAX_10_EXP
276 #else
277 #define LDOUBLE double
278 #define LDOUBLE_MIN_10_EXP DBL_MIN_10_EXP
279 #define LDOUBLE_MAX_10_EXP DBL_MAX_10_EXP
280 #endif /* HAVE_LONG_DOUBLE */
281 #endif /* !defined(LDOUBLE) */
282
283 /* Support for long long int. */
284 #ifndef LLONG
285 #if HAVE_LONG_LONG_INT
286 #define LLONG long long int
287 #else
288 #define LLONG long int
289 #endif /* HAVE_LONG_LONG_INT */
290 #endif /* !defined(LLONG) */
291
292 /* Support for intmax_t. */
293 #ifndef INTMAX_T
294 #if HAVE_INTMAX_T || defined(intmax_t)
295 #define INTMAX_T intmax_t
296 #else
297 #define INTMAX_T LLONG
298 #endif /* HAVE_INTMAX_T || defined(intmax_t) */
299 #endif /* !defined(INTMAX_T) */
300
301 /* Support for uintptr_t. */
302 #ifndef UINTPTR_T
303 #if HAVE_UINTPTR_T || defined(uintptr_t)
304 #define UINTPTR_T uintptr_t
305 #else
306 #define UINTPTR_T unsigned long int
307 #endif /* HAVE_UINTPTR_T || defined(uintptr_t) */
308 #endif /* !defined(UINTPTR_T) */
309
310 /* Support for ptrdiff_t. */
311 #ifndef PTRDIFF_T
312 #if HAVE_PTRDIFF_T || defined(ptrdiff_t)
313 #define PTRDIFF_T ptrdiff_t
314 #else
315 #define PTRDIFF_T long int
316 #endif /* HAVE_PTRDIFF_T || defined(ptrdiff_t) */
317 #endif /* !defined(PTRDIFF_T) */
318
319 /*
320 * We need an unsigned integer type corresponding to ptrdiff_t (cf. C99:
321 * 7.19.6.1, 7). However, we'll simply use PTRDIFF_T and convert it to an
322 * unsigned type if necessary. This should work just fine in practice.
323 */
324 #ifndef UPTRDIFF_T
325 #define UPTRDIFF_T PTRDIFF_T
326 #endif /* !defined(UPTRDIFF_T) */
327
328 /*
329 * We need a signed integer type corresponding to size_t (cf. C99: 7.19.6.1, 7).
330 * However, we'll simply use size_t and convert it to a signed type if
331 * necessary. This should work just fine in practice.
332 */
333 #ifndef SSIZE_T
334 #define SSIZE_T size_t
335 #endif /* !defined(SSIZE_T) */
336
337 /* Either ERANGE or E2BIG should be available everywhere. */
338 #ifndef ERANGE
339 #define ERANGE E2BIG
340 #endif /* !defined(ERANGE) */
341 #ifndef EOVERFLOW
342 #define EOVERFLOW ERANGE
343 #endif /* !defined(EOVERFLOW) */
344
345 /*
346 * Buffer size to hold the octal string representation of UINT128_MAX without
347 * nul-termination ("3777777777777777777777777777777777777777777").
348 */
349 #ifdef MAX_CONVERT_LENGTH
350 #undef MAX_CONVERT_LENGTH
351 #endif /* defined(MAX_CONVERT_LENGTH) */
352 #define MAX_CONVERT_LENGTH 43
353
354 /* Format read states. */
355 #define PRINT_S_DEFAULT 0
356 #define PRINT_S_FLAGS 1
357 #define PRINT_S_WIDTH 2
358 #define PRINT_S_DOT 3
359 #define PRINT_S_PRECISION 4
360 #define PRINT_S_MOD 5
361 #define PRINT_S_CONV 6
362
363 /* Format flags. */
364 #define PRINT_F_MINUS (1 << 0)
365 #define PRINT_F_PLUS (1 << 1)
366 #define PRINT_F_SPACE (1 << 2)
367 #define PRINT_F_NUM (1 << 3)
368 #define PRINT_F_ZERO (1 << 4)
369 #define PRINT_F_QUOTE (1 << 5)
370 #define PRINT_F_UP (1 << 6)
371 #define PRINT_F_UNSIGNED (1 << 7)
372 #define PRINT_F_TYPE_G (1 << 8)
373 #define PRINT_F_TYPE_E (1 << 9)
374
375 /* Conversion flags. */
376 #define PRINT_C_CHAR 1
377 #define PRINT_C_SHORT 2
378 #define PRINT_C_LONG 3
379 #define PRINT_C_LLONG 4
380 #define PRINT_C_LDOUBLE 5
381 #define PRINT_C_SIZE 6
382 #define PRINT_C_PTRDIFF 7
383 #define PRINT_C_INTMAX 8
384
385 #ifndef MAX
386 #define MAX(x, y) ((x >= y) ? x : y)
387 #endif /* !defined(MAX) */
388 #ifndef CHARTOINT
389 #define CHARTOINT(ch) (ch - '0')
390 #endif /* !defined(CHARTOINT) */
391 #ifndef ISDIGIT
392 #define ISDIGIT(ch) ('0' <= (unsigned char)ch && (unsigned char)ch <= '9')
393 #endif /* !defined(ISDIGIT) */
394 #ifndef ISNAN
395 #define ISNAN(x) (x != x)
396 #endif /* !defined(ISNAN) */
397 #ifndef ISINF
398 #define ISINF(x) ((x < -1 || x > 1) && x + x == x)
399 #endif /* !defined(ISINF) */
400
401 #ifdef OUTCHAR
402 #undef OUTCHAR
403 #endif /* defined(OUTCHAR) */
404 #define OUTCHAR(str, len, size, ch) \
405 do { \
406 if (len + 1 < size) \
407 str[len] = ch; \
408 (len)++; \
409 } while (/* CONSTCOND */ 0)
410
411 static void fmtstr(char *, size_t *, size_t, const char *, int, int, int);
412 static void fmtint(char *, size_t *, size_t, INTMAX_T, int, int, int, int);
413 static void fmtflt(char *, size_t *, size_t, LDOUBLE, int, int, int, int *);
414 static void printsep(char *, size_t *, size_t);
415 static int getnumsep(int);
416 static int getexponent(LDOUBLE);
417 static int convert(UINTMAX_T, char *, size_t, int, int);
418 static UINTMAX_T cast(LDOUBLE);
419 static UINTMAX_T myround(LDOUBLE);
420 static LDOUBLE mypow10(int);
421
422 //extern int errno;
423
424 int
425 rpl_vsnprintf(char *str, size_t size, const char *format, va_list args)
426 {
427 LDOUBLE fvalue;
428 INTMAX_T value;
429 unsigned char cvalue;
430 const char *strvalue;
431 INTMAX_T *intmaxptr;
432 PTRDIFF_T *ptrdiffptr;
433 SSIZE_T *sizeptr;
434 LLONG *llongptr;
435 long int *longptr;
436 int *intptr;
437 short int *shortptr;
438 signed char *charptr;
439 size_t len = 0;
440 int overflow = 0;
441 int base = 0;
442 int cflags = 0;
443 int flags = 0;
444 int width = 0;
445 int precision = -1;
446 int state = PRINT_S_DEFAULT;
447 char ch = *format++;
448
449 /*
450 * C99 says: "If `n' is zero, nothing is written, and `s' may be a null
451 * pointer." (7.19.6.5, 2) We're forgiving and allow a NULL pointer
452 * even if a size larger than zero was specified. At least NetBSD's
453 * snprintf(3) does the same, as well as other versions of this file.
454 * (Though some of these versions will write to a non-NULL buffer even
455 * if a size of zero was specified, which violates the standard.)
456 */
457 if (str == NULL && size != 0)
458 size = 0;
459
460 while (ch != '\0')
461 switch (state) {
462 case PRINT_S_DEFAULT:
463 if (ch == '%')
464 state = PRINT_S_FLAGS;
465 else
466 OUTCHAR(str, len, size, ch);
467 ch = *format++;
468 break;
469 case PRINT_S_FLAGS:
470 switch (ch) {
471 case '-':
472 flags |= PRINT_F_MINUS;
473 ch = *format++;
474 break;
475 case '+':
476 flags |= PRINT_F_PLUS;
477 ch = *format++;
478 break;
479 case ' ':
480 flags |= PRINT_F_SPACE;
481 ch = *format++;
482 break;
483 case '#':
484 flags |= PRINT_F_NUM;
485 ch = *format++;
486 break;
487 case '0':
488 flags |= PRINT_F_ZERO;
489 ch = *format++;
490 break;
491 case '\'': /* SUSv2 flag (not in C99). */
492 flags |= PRINT_F_QUOTE;
493 ch = *format++;
494 break;
495 default:
496 state = PRINT_S_WIDTH;
497 break;
498 }
499 break;
500 case PRINT_S_WIDTH:
501 if (ISDIGIT(ch)) {
502 ch = CHARTOINT(ch);
503 if (width > (INT_MAX - ch) / 10) {
504 overflow = 1;
505 goto out;
506 }
507 width = 10 * width + ch;
508 ch = *format++;
509 } else if (ch == '*') {
510 /*
511 * C99 says: "A negative field width argument is
512 * taken as a `-' flag followed by a positive
513 * field width." (7.19.6.1, 5)
514 */
515 if ((width = va_arg(args, int)) < 0) {
516 flags |= PRINT_F_MINUS;
517 width = -width;
518 }
519 ch = *format++;
520 state = PRINT_S_DOT;
521 } else
522 state = PRINT_S_DOT;
523 break;
524 case PRINT_S_DOT:
525 if (ch == '.') {
526 state = PRINT_S_PRECISION;
527 ch = *format++;
528 } else
529 state = PRINT_S_MOD;
530 break;
531 case PRINT_S_PRECISION:
532 if (precision == -1)
533 precision = 0;
534 if (ISDIGIT(ch)) {
535 ch = CHARTOINT(ch);
536 if (precision > (INT_MAX - ch) / 10) {
537 overflow = 1;
538 goto out;
539 }
540 precision = 10 * precision + ch;
541 ch = *format++;
542 } else if (ch == '*') {
543 /*
544 * C99 says: "A negative precision argument is
545 * taken as if the precision were omitted."
546 * (7.19.6.1, 5)
547 */
548 if ((precision = va_arg(args, int)) < 0)
549 precision = -1;
550 ch = *format++;
551 state = PRINT_S_MOD;
552 } else
553 state = PRINT_S_MOD;
554 break;
555 case PRINT_S_MOD:
556 switch (ch) {
557 case 'h':
558 ch = *format++;
559 if (ch == 'h') { /* It's a char. */
560 ch = *format++;
561 cflags = PRINT_C_CHAR;
562 } else
563 cflags = PRINT_C_SHORT;
564 break;
565 case 'l':
566 ch = *format++;
567 if (ch == 'l') { /* It's a long long. */
568 ch = *format++;
569 cflags = PRINT_C_LLONG;
570 } else
571 cflags = PRINT_C_LONG;
572 break;
573 case 'L':
574 cflags = PRINT_C_LDOUBLE;
575 ch = *format++;
576 break;
577 case 'j':
578 cflags = PRINT_C_INTMAX;
579 ch = *format++;
580 break;
581 case 't':
582 cflags = PRINT_C_PTRDIFF;
583 ch = *format++;
584 break;
585 case 'z':
586 cflags = PRINT_C_SIZE;
587 ch = *format++;
588 break;
589 }
590 state = PRINT_S_CONV;
591 break;
592 case PRINT_S_CONV:
593 switch (ch) {
594 case 'd':
595 /* FALLTHROUGH */
596 case 'i':
597 switch (cflags) {
598 case PRINT_C_CHAR:
599 value = (signed char)va_arg(args, int);
600 break;
601 case PRINT_C_SHORT:
602 value = (short int)va_arg(args, int);
603 break;
604 case PRINT_C_LONG:
605 value = va_arg(args, long int);
606 break;
607 case PRINT_C_LLONG:
608 value = va_arg(args, LLONG);
609 break;
610 case PRINT_C_SIZE:
611 value = va_arg(args, SSIZE_T);
612 break;
613 case PRINT_C_INTMAX:
614 value = va_arg(args, INTMAX_T);
615 break;
616 case PRINT_C_PTRDIFF:
617 value = va_arg(args, PTRDIFF_T);
618 break;
619 default:
620 value = va_arg(args, int);
621 break;
622 }
623 fmtint(str, &len, size, value, 10, width,
624 precision, flags);
625 break;
626 case 'X':
627 flags |= PRINT_F_UP;
628 /* FALLTHROUGH */
629 case 'x':
630 base = 16;
631 /* FALLTHROUGH */
632 case 'o':
633 if (base == 0)
634 base = 8;
635 /* FALLTHROUGH */
636 case 'u':
637 if (base == 0)
638 base = 10;
639 flags |= PRINT_F_UNSIGNED;
640 switch (cflags) {
641 case PRINT_C_CHAR:
642 value = (unsigned char)va_arg(args,
643 unsigned int);
644 break;
645 case PRINT_C_SHORT:
646 value = (unsigned short int)va_arg(args,
647 unsigned int);
648 break;
649 case PRINT_C_LONG:
650 value = va_arg(args, unsigned long int);
651 break;
652 case PRINT_C_LLONG:
653 value = va_arg(args, ULLONG);
654 break;
655 case PRINT_C_SIZE:
656 value = va_arg(args, size_t);
657 break;
658 case PRINT_C_INTMAX:
659 value = va_arg(args, UINTMAX_T);
660 break;
661 case PRINT_C_PTRDIFF:
662 value = va_arg(args, UPTRDIFF_T);
663 break;
664 default:
665 value = va_arg(args, unsigned int);
666 break;
667 }
668 fmtint(str, &len, size, value, base, width,
669 precision, flags);
670 break;
671 case 'A':
672 /* Not yet supported, we'll use "%F". */
673 /* FALLTHROUGH */
674 case 'E':
675 if (ch == 'E')
676 flags |= PRINT_F_TYPE_E;
677 /* FALLTHROUGH */
678 case 'G':
679 if (ch == 'G')
680 flags |= PRINT_F_TYPE_G;
681 /* FALLTHROUGH */
682 case 'F':
683 flags |= PRINT_F_UP;
684 /* FALLTHROUGH */
685 case 'a':
686 /* Not yet supported, we'll use "%f". */
687 /* FALLTHROUGH */
688 case 'e':
689 if (ch == 'e')
690 flags |= PRINT_F_TYPE_E;
691 /* FALLTHROUGH */
692 case 'g':
693 if (ch == 'g')
694 flags |= PRINT_F_TYPE_G;
695 /* FALLTHROUGH */
696 case 'f':
697 if (cflags == PRINT_C_LDOUBLE)
698 fvalue = va_arg(args, LDOUBLE);
699 else
700 fvalue = va_arg(args, double);
701 fmtflt(str, &len, size, fvalue, width,
702 precision, flags, &overflow);
703 if (overflow)
704 goto out;
705 break;
706 case 'c':
707 cvalue = va_arg(args, int);
708 OUTCHAR(str, len, size, cvalue);
709 break;
710 case 's':
711 strvalue = va_arg(args, char *);
712 fmtstr(str, &len, size, strvalue, width,
713 precision, flags);
714 break;
715 case 'p':
716 /*
717 * C99 says: "The value of the pointer is
718 * converted to a sequence of printing
719 * characters, in an implementation-defined
720 * manner." (C99: 7.19.6.1, 8)
721 */
722 if ((strvalue = (const char*)va_arg(args, void *)) == NULL)
723 /*
724 * We use the glibc format. BSD prints
725 * "0x0", SysV "0".
726 */
727 fmtstr(str, &len, size, "(nil)", width,
728 -1, flags);
729 else {
730 /*
731 * We use the BSD/glibc format. SysV
732 * omits the "0x" prefix (which we emit
733 * using the PRINT_F_NUM flag).
734 */
735 flags |= PRINT_F_NUM;
736 flags |= PRINT_F_UNSIGNED;
737 fmtint(str, &len, size,
738 (UINTPTR_T)strvalue, 16, width,
739 precision, flags);
740 }
741 break;
742 case 'n':
743 switch (cflags) {
744 case PRINT_C_CHAR:
745 charptr = va_arg(args, signed char *);
746 *charptr = len;
747 break;
748 case PRINT_C_SHORT:
749 shortptr = va_arg(args, short int *);
750 *shortptr = len;
751 break;
752 case PRINT_C_LONG:
753 longptr = va_arg(args, long int *);
754 *longptr = len;
755 break;
756 case PRINT_C_LLONG:
757 llongptr = va_arg(args, LLONG *);
758 *llongptr = len;
759 break;
760 case PRINT_C_SIZE:
761 /*
762 * C99 says that with the "z" length
763 * modifier, "a following `n' conversion
764 * specifier applies to a pointer to a
765 * signed integer type corresponding to
766 * size_t argument." (7.19.6.1, 7)
767 */
768 sizeptr = va_arg(args, SSIZE_T *);
769 *sizeptr = len;
770 break;
771 case PRINT_C_INTMAX:
772 intmaxptr = va_arg(args, INTMAX_T *);
773 *intmaxptr = len;
774 break;
775 case PRINT_C_PTRDIFF:
776 ptrdiffptr = va_arg(args, PTRDIFF_T *);
777 *ptrdiffptr = len;
778 break;
779 default:
780 intptr = va_arg(args, int *);
781 *intptr = len;
782 break;
783 }
784 break;
785 case '%': /* Print a "%" character verbatim. */
786 OUTCHAR(str, len, size, ch);
787 break;
788 default: /* Skip other characters. */
789 break;
790 }
791 ch = *format++;
792 state = PRINT_S_DEFAULT;
793 base = cflags = flags = width = 0;
794 precision = -1;
795 break;
796 }
797 out:
798 if (len < size)
799 str[len] = '\0';
800 else if (size > 0)
801 str[size - 1] = '\0';
802
803 if (overflow || len >= INT_MAX) {
804 errno = overflow ? EOVERFLOW : ERANGE;
805 return -1;
806 }
807 return (int)len;
808 }
809
810 static void
811 fmtstr(char *str, size_t *len, size_t size, const char *value, int width,
812 int precision, int flags)
813 {
814 int padlen, strln; /* Amount to pad. */
815 int noprecision = (precision == -1);
816
817 if (value == NULL) /* We're forgiving. */
818 value = "(null)";
819
820 /* If a precision was specified, don't read the string past it. */
821 for (strln = 0; value[strln] != '\0' &&
822 (noprecision || strln < precision); strln++)
823 continue;
824
825 if ((padlen = width - strln) < 0)
826 padlen = 0;
827 if (flags & PRINT_F_MINUS) /* Left justify. */
828 padlen = -padlen;
829
830 while (padlen > 0) { /* Leading spaces. */
831 OUTCHAR(str, *len, size, ' ');
832 padlen--;
833 }
834 while ((noprecision || precision-- > 0) && *value != '\0') {
835 OUTCHAR(str, *len, size, *value);
836 value++;
837 }
838 while (padlen < 0) { /* Trailing spaces. */
839 OUTCHAR(str, *len, size, ' ');
840 padlen++;
841 }
842 }
843
844 static void
845 fmtint(char *str, size_t *len, size_t size, INTMAX_T value, int base, int width,
846 int precision, int flags)
847 {
848 UINTMAX_T uvalue;
849 char iconvert[MAX_CONVERT_LENGTH];
850 char sign = 0;
851 char hexprefix = 0;
852 int spadlen = 0; /* Amount to space pad. */
853 int zpadlen = 0; /* Amount to zero pad. */
854 int pos;
855 int separators = (flags & PRINT_F_QUOTE);
856 int noprecision = (precision == -1);
857
858 if (flags & PRINT_F_UNSIGNED)
859 uvalue = value;
860 else {
861 uvalue = (value >= 0) ? value : -value;
862 if (value < 0)
863 sign = '-';
864 else if (flags & PRINT_F_PLUS) /* Do a sign. */
865 sign = '+';
866 else if (flags & PRINT_F_SPACE)
867 sign = ' ';
868 }
869
870 pos = convert(uvalue, iconvert, sizeof(iconvert), base,
871 flags & PRINT_F_UP);
872
873 if (flags & PRINT_F_NUM && uvalue != 0) {
874 /*
875 * C99 says: "The result is converted to an `alternative form'.
876 * For `o' conversion, it increases the precision, if and only
877 * if necessary, to force the first digit of the result to be a
878 * zero (if the value and precision are both 0, a single 0 is
879 * printed). For `x' (or `X') conversion, a nonzero result has
880 * `0x' (or `0X') prefixed to it." (7.19.6.1, 6)
881 */
882 switch (base) {
883 case 8:
884 if (precision <= pos)
885 precision = pos + 1;
886 break;
887 case 16:
888 hexprefix = (flags & PRINT_F_UP) ? 'X' : 'x';
889 break;
890 }
891 }
892
893 if (separators) /* Get the number of group separators we'll print. */
894 separators = getnumsep(pos);
895
896 zpadlen = precision - pos - separators;
897 spadlen = width /* Minimum field width. */
898 - separators /* Number of separators. */
899 - MAX(precision, pos) /* Number of integer digits. */
900 - ((sign != 0) ? 1 : 0) /* Will we print a sign? */
901 - ((hexprefix != 0) ? 2 : 0); /* Will we print a prefix? */
902
903 if (zpadlen < 0)
904 zpadlen = 0;
905 if (spadlen < 0)
906 spadlen = 0;
907
908 /*
909 * C99 says: "If the `0' and `-' flags both appear, the `0' flag is
910 * ignored. For `d', `i', `o', `u', `x', and `X' conversions, if a
911 * precision is specified, the `0' flag is ignored." (7.19.6.1, 6)
912 */
913 if (flags & PRINT_F_MINUS) /* Left justify. */
914 spadlen = -spadlen;
915 else if (flags & PRINT_F_ZERO && noprecision) {
916 zpadlen += spadlen;
917 spadlen = 0;
918 }
919 while (spadlen > 0) { /* Leading spaces. */
920 OUTCHAR(str, *len, size, ' ');
921 spadlen--;
922 }
923 if (sign != 0) /* Sign. */
924 OUTCHAR(str, *len, size, sign);
925 if (hexprefix != 0) { /* A "0x" or "0X" prefix. */
926 OUTCHAR(str, *len, size, '0');
927 OUTCHAR(str, *len, size, hexprefix);
928 }
929 while (zpadlen > 0) { /* Leading zeros. */
930 OUTCHAR(str, *len, size, '0');
931 zpadlen--;
932 }
933 while (pos > 0) { /* The actual digits. */
934 pos--;
935 OUTCHAR(str, *len, size, iconvert[pos]);
936 if (separators > 0 && pos > 0 && pos % 3 == 0)
937 printsep(str, len, size);
938 }
939 while (spadlen < 0) { /* Trailing spaces. */
940 OUTCHAR(str, *len, size, ' ');
941 spadlen++;
942 }
943 }
944
945 static void
946 fmtflt(char *str, size_t *len, size_t size, LDOUBLE fvalue, int width,
947 int precision, int flags, int *overflow)
948 {
949 LDOUBLE ufvalue;
950 UINTMAX_T intpart;
951 UINTMAX_T fracpart;
952 UINTMAX_T mask;
953 const char *infnan = NULL;
954 char iconvert[MAX_CONVERT_LENGTH];
955 char fconvert[MAX_CONVERT_LENGTH];
956 char econvert[5]; /* "e-300" (without nul-termination). */
957 char esign = 0;
958 char sign = 0;
959 int leadfraczeros = 0;
960 int exponent = 0;
961 int emitpoint = 0;
962 int omitzeros = 0;
963 int omitcount = 0;
964 int padlen = 0;
965 int epos = 0;
966 int fpos = 0;
967 int ipos = 0;
968 int separators = (flags & PRINT_F_QUOTE);
969 int estyle = (flags & PRINT_F_TYPE_E);
970 #if HAVE_LOCALECONV && HAVE_LCONV_DECIMAL_POINT
971 struct lconv *lc = localeconv();
972 #endif /* HAVE_LOCALECONV && HAVE_LCONV_DECIMAL_POINT */
973
974 /*
975 * AIX' man page says the default is 0, but C99 and at least Solaris'
976 * and NetBSD's man pages say the default is 6, and sprintf(3) on AIX
977 * defaults to 6.
978 */
979 if (precision == -1)
980 precision = 6;
981
982 if (fvalue < 0.0)
983 sign = '-';
984 else if (flags & PRINT_F_PLUS) /* Do a sign. */
985 sign = '+';
986 else if (flags & PRINT_F_SPACE)
987 sign = ' ';
988
989 if (ISNAN(fvalue))
990 infnan = (flags & PRINT_F_UP) ? "NAN" : "nan";
991 else if (ISINF(fvalue))
992 infnan = (flags & PRINT_F_UP) ? "INF" : "inf";
993
994 if (infnan != NULL) {
995 if (sign != 0)
996 iconvert[ipos++] = sign;
997 while (*infnan != '\0')
998 iconvert[ipos++] = *infnan++;
999 fmtstr(str, len, size, iconvert, width, ipos, flags);
1000 return;
1001 }
1002
1003 /* "%e" (or "%E") or "%g" (or "%G") conversion. */
1004 if (flags & PRINT_F_TYPE_E || flags & PRINT_F_TYPE_G) {
1005 if (flags & PRINT_F_TYPE_G) {
1006 /*
1007 * If the precision is zero, it is treated as one (cf.
1008 * C99: 7.19.6.1, 8).
1009 */
1010 if (precision == 0)
1011 precision = 1;
1012 /*
1013 * For "%g" (and "%G") conversions, the precision
1014 * specifies the number of significant digits, which
1015 * includes the digits in the integer part. The
1016 * conversion will or will not be using "e-style" (like
1017 * "%e" or "%E" conversions) depending on the precision
1018 * and on the exponent. However, the exponent can be
1019 * affected by rounding the converted value, so we'll
1020 * leave this decision for later. Until then, we'll
1021 * assume that we're going to do an "e-style" conversion
1022 * (in order to get the exponent calculated). For
1023 * "e-style", the precision must be decremented by one.
1024 */
1025 precision--;
1026 /*
1027 * For "%g" (and "%G") conversions, trailing zeros are
1028 * removed from the fractional portion of the result
1029 * unless the "#" flag was specified.
1030 */
1031 if (!(flags & PRINT_F_NUM))
1032 omitzeros = 1;
1033 }
1034 exponent = getexponent(fvalue);
1035 estyle = 1;
1036 }
1037
1038 again:
1039 /*
1040 * Sorry, we only support 9, 19, or 38 digits (that is, the number of
1041 * digits of the 32-bit, the 64-bit, or the 128-bit UINTMAX_MAX value
1042 * minus one) past the decimal point due to our conversion method.
1043 */
1044 switch (sizeof(UINTMAX_T)) {
1045 case 16:
1046 if (precision > 38)
1047 precision = 38;
1048 break;
1049 case 8:
1050 if (precision > 19)
1051 precision = 19;
1052 break;
1053 default:
1054 if (precision > 9)
1055 precision = 9;
1056 break;
1057 }
1058
1059 ufvalue = (fvalue >= 0.0) ? fvalue : -fvalue;
1060 if (estyle) /* We want exactly one integer digit. */
1061 ufvalue /= mypow10(exponent);
1062
1063 if ((intpart = cast(ufvalue)) == UINTMAX_MAX) {
1064 *overflow = 1;
1065 return;
1066 }
1067
1068 /*
1069 * Factor of ten with the number of digits needed for the fractional
1070 * part. For example, if the precision is 3, the mask will be 1000.
1071 */
1072 mask = mypow10(precision);
1073 /*
1074 * We "cheat" by converting the fractional part to integer by
1075 * multiplying by a factor of ten.
1076 */
1077 if ((fracpart = myround(mask * (ufvalue - intpart))) >= mask) {
1078 /*
1079 * For example, ufvalue = 2.99962, intpart = 2, and mask = 1000
1080 * (because precision = 3). Now, myround(1000 * 0.99962) will
1081 * return 1000. So, the integer part must be incremented by one
1082 * and the fractional part must be set to zero.
1083 */
1084 intpart++;
1085 fracpart = 0;
1086 if (estyle && intpart == 10) {
1087 /*
1088 * The value was rounded up to ten, but we only want one
1089 * integer digit if using "e-style". So, the integer
1090 * part must be set to one and the exponent must be
1091 * incremented by one.
1092 */
1093 intpart = 1;
1094 exponent++;
1095 }
1096 }
1097
1098 /*
1099 * Now that we know the real exponent, we can check whether or not to
1100 * use "e-style" for "%g" (and "%G") conversions. If we don't need
1101 * "e-style", the precision must be adjusted and the integer and
1102 * fractional parts must be recalculated from the original value.
1103 *
1104 * C99 says: "Let P equal the precision if nonzero, 6 if the precision
1105 * is omitted, or 1 if the precision is zero. Then, if a conversion
1106 * with style `E' would have an exponent of X:
1107 *
1108 * - if P > X >= -4, the conversion is with style `f' (or `F') and
1109 * precision P - (X + 1).
1110 *
1111 * - otherwise, the conversion is with style `e' (or `E') and precision
1112 * P - 1." (7.19.6.1, 8)
1113 *
1114 * Note that we had decremented the precision by one.
1115 */
1116 if (flags & PRINT_F_TYPE_G && estyle &&
1117 precision + 1 > exponent && exponent >= -4) {
1118 precision -= exponent;
1119 estyle = 0;
1120 goto again;
1121 }
1122
1123 if (estyle) {
1124 if (exponent < 0) {
1125 exponent = -exponent;
1126 esign = '-';
1127 } else
1128 esign = '+';
1129
1130 /*
1131 * Convert the exponent. The sizeof(econvert) is 5. So, the
1132 * econvert buffer can hold e.g. "e+999" and "e-999". We don't
1133 * support an exponent which contains more than three digits.
1134 * Therefore, the following stores are safe.
1135 */
1136 epos = convert(exponent, econvert, 3, 10, 0);
1137 /*
1138 * C99 says: "The exponent always contains at least two digits,
1139 * and only as many more digits as necessary to represent the
1140 * exponent." (7.19.6.1, 8)
1141 */
1142 if (epos == 1)
1143 econvert[epos++] = '0';
1144 econvert[epos++] = esign;
1145 econvert[epos++] = (flags & PRINT_F_UP) ? 'E' : 'e';
1146 }
1147
1148 /* Convert the integer part and the fractional part. */
1149 ipos = convert(intpart, iconvert, sizeof(iconvert), 10, 0);
1150 if (fracpart != 0) /* convert() would return 1 if fracpart == 0. */
1151 fpos = convert(fracpart, fconvert, sizeof(fconvert), 10, 0);
1152
1153 leadfraczeros = precision - fpos;
1154
1155 if (omitzeros) {
1156 if (fpos > 0) /* Omit trailing fractional part zeros. */
1157 while (omitcount < fpos && fconvert[omitcount] == '0')
1158 omitcount++;
1159 else { /* The fractional part is zero, omit it completely. */
1160 omitcount = precision;
1161 leadfraczeros = 0;
1162 }
1163 precision -= omitcount;
1164 }
1165
1166 /*
1167 * Print a decimal point if either the fractional part is non-zero
1168 * and/or the "#" flag was specified.
1169 */
1170 if (precision > 0 || flags & PRINT_F_NUM)
1171 emitpoint = 1;
1172 if (separators) /* Get the number of group separators we'll print. */
1173 separators = getnumsep(ipos);
1174
1175 padlen = width /* Minimum field width. */
1176 - ipos /* Number of integer digits. */
1177 - epos /* Number of exponent characters. */
1178 - precision /* Number of fractional digits. */
1179 - separators /* Number of group separators. */
1180 - (emitpoint ? 1 : 0) /* Will we print a decimal point? */
1181 - ((sign != 0) ? 1 : 0); /* Will we print a sign character? */
1182
1183 if (padlen < 0)
1184 padlen = 0;
1185
1186 /*
1187 * C99 says: "If the `0' and `-' flags both appear, the `0' flag is
1188 * ignored." (7.19.6.1, 6)
1189 */
1190 if (flags & PRINT_F_MINUS) /* Left justifty. */
1191 padlen = -padlen;
1192 else if (flags & PRINT_F_ZERO && padlen > 0) {
1193 if (sign != 0) { /* Sign. */
1194 OUTCHAR(str, *len, size, sign);
1195 sign = 0;
1196 }
1197 while (padlen > 0) { /* Leading zeros. */
1198 OUTCHAR(str, *len, size, '0');
1199 padlen--;
1200 }
1201 }
1202 while (padlen > 0) { /* Leading spaces. */
1203 OUTCHAR(str, *len, size, ' ');
1204 padlen--;
1205 }
1206 if (sign != 0) /* Sign. */
1207 OUTCHAR(str, *len, size, sign);
1208 while (ipos > 0) { /* Integer part. */
1209 ipos--;
1210 OUTCHAR(str, *len, size, iconvert[ipos]);
1211 if (separators > 0 && ipos > 0 && ipos % 3 == 0)
1212 printsep(str, len, size);
1213 }
1214 if (emitpoint) { /* Decimal point. */
1215 #if HAVE_LOCALECONV && HAVE_LCONV_DECIMAL_POINT
1216 if (lc->decimal_point != NULL && *lc->decimal_point != '\0')
1217 OUTCHAR(str, *len, size, *lc->decimal_point);
1218 else /* We'll always print some decimal point character. */
1219 #endif /* HAVE_LOCALECONV && HAVE_LCONV_DECIMAL_POINT */
1220 OUTCHAR(str, *len, size, '.');
1221 }
1222 while (leadfraczeros > 0) { /* Leading fractional part zeros. */
1223 OUTCHAR(str, *len, size, '0');
1224 leadfraczeros--;
1225 }
1226 while (fpos > omitcount) { /* The remaining fractional part. */
1227 fpos--;
1228 OUTCHAR(str, *len, size, fconvert[fpos]);
1229 }
1230 while (epos > 0) { /* Exponent. */
1231 epos--;
1232 OUTCHAR(str, *len, size, econvert[epos]);
1233 }
1234 while (padlen < 0) { /* Trailing spaces. */
1235 OUTCHAR(str, *len, size, ' ');
1236 padlen++;
1237 }
1238 }
1239
1240 static void
1241 printsep(char *str, size_t *len, size_t size)
1242 {
1243 #if HAVE_LOCALECONV && HAVE_LCONV_THOUSANDS_SEP
1244 struct lconv *lc = localeconv();
1245 int i;
1246
1247 if (lc->thousands_sep != NULL)
1248 for (i = 0; lc->thousands_sep[i] != '\0'; i++)
1249 OUTCHAR(str, *len, size, lc->thousands_sep[i]);
1250 else
1251 #endif /* HAVE_LOCALECONV && HAVE_LCONV_THOUSANDS_SEP */
1252 OUTCHAR(str, *len, size, ',');
1253 }
1254
1255 static int
1256 getnumsep(int digits)
1257 {
1258 int separators = (digits - ((digits % 3 == 0) ? 1 : 0)) / 3;
1259 #if HAVE_LOCALECONV && HAVE_LCONV_THOUSANDS_SEP
1260 int strln;
1261 struct lconv *lc = localeconv();
1262
1263 /* We support an arbitrary separator length (including zero). */
1264 if (lc->thousands_sep != NULL) {
1265 for (strln = 0; lc->thousands_sep[strln] != '\0'; strln++)
1266 continue;
1267 separators *= strln;
1268 }
1269 #endif /* HAVE_LOCALECONV && HAVE_LCONV_THOUSANDS_SEP */
1270 return separators;
1271 }
1272
1273 static int
1274 getexponent(LDOUBLE value)
1275 {
1276 LDOUBLE tmp = (value >= 0.0) ? value : -value;
1277 int exponent = 0;
1278
1279 /*
1280 * We check for LDOUBLE_MAX_10_EXP >= exponent >= LDOUBLE_MIN_10_EXP in
1281 * order to work around possible endless loops which could happen (at
1282 * least) in the second loop (at least) if we're called with an infinite
1283 * value. However, we checked for infinity before calling this function
1284 * using our ISINF() macro, so this might be somewhat paranoid.
1285 */
1286 while (tmp < 1.0 && tmp > 0.0 && --exponent >= LDOUBLE_MIN_10_EXP)
1287 tmp *= 10;
1288 while (tmp >= 10.0 && ++exponent <= LDOUBLE_MAX_10_EXP)
1289 tmp /= 10;
1290
1291 return exponent;
1292 }
1293
1294 static int
1295 convert(UINTMAX_T value, char *buf, size_t size, int base, int caps)
1296 {
1297 const char *digits = caps ? "0123456789ABCDEF" : "0123456789abcdef";
1298 size_t pos = 0;
1299
1300 /* We return an unterminated buffer with the digits in reverse order. */
1301 do {
1302 buf[pos++] = digits[value % base];
1303 value /= base;
1304 } while (value != 0 && pos < size);
1305
1306 return (int)pos;
1307 }
1308
1309 static UINTMAX_T
1310 cast(LDOUBLE value)
1311 {
1312 UINTMAX_T result;
1313
1314 /*
1315 * We check for ">=" and not for ">" because if UINTMAX_MAX cannot be
1316 * represented exactly as an LDOUBLE value (but is less than LDBL_MAX),
1317 * it may be increased to the nearest higher representable value for the
1318 * comparison (cf. C99: 6.3.1.4, 2). It might then equal the LDOUBLE
1319 * value although converting the latter to UINTMAX_T would overflow.
1320 */
1321 if (value >= UINTMAX_MAX)
1322 return UINTMAX_MAX;
1323
1324 result = value;
1325 /*
1326 * At least on NetBSD/sparc64 3.0.2 and 4.99.30, casting long double to
1327 * an integer type converts e.g. 1.9 to 2 instead of 1 (which violates
1328 * the standard). Sigh.
1329 */
1330 return (result <= value) ? result : result - 1;
1331 }
1332
1333 static UINTMAX_T
1334 myround(LDOUBLE value)
1335 {
1336 UINTMAX_T intpart = cast(value);
1337
1338 if (intpart == UINTMAX_MAX)
1339 return UINTMAX_MAX;
1340
1341 return ((value -= intpart) < 0.5) ? intpart : intpart + 1;
1342 }
1343
1344 static LDOUBLE
1345 mypow10(int exponent)
1346 {
1347 LDOUBLE result = 1;
1348
1349 while (exponent > 0) {
1350 result *= 10;
1351 exponent--;
1352 }
1353 while (exponent < 0) {
1354 result /= 10;
1355 exponent++;
1356 }
1357 return result;
1358 }
1359 #endif /* !HAVE_VSNPRINTF */
1360
1361 #if !HAVE_VASPRINTF
1362 #if NEED_MYMEMCPY
1363 static void *
1364 mymemcpy(void *dst, const void *src, size_t len)
1365 {
1366 const char *from = (const char *)src;
1367 char *to = (char*)dst;
1368
1369 /* No need for optimization, we use this only to replace va_copy(3). */
1370 while (len-- > 0)
1371 *to++ = *from++;
1372 return dst;
1373 }
1374 #endif /* NEED_MYMEMCPY */
1375
1376 int
1377 rpl_vasprintf(char **ret, const char *format, va_list ap)
1378 {
1379 size_t size;
1380 int len;
1381 va_list aq;
1382
1383 VA_COPY(aq, ap);
1384 #if !HAVE_VSNPRINTF
1385 len = rpl_vsnprintf(NULL, 0, format, aq);
1386 #else
1387 len = vsnprintf(NULL, 0, format, aq);
1388 #endif
1389 VA_END_COPY(aq);
1390 if (len < 0 || (*ret = (char*)malloc(size = len + 1)) == NULL)
1391 return -1;
1392 #if !HAVE_VSNPRINTF
1393 return rpl_vsnprintf(*ret, size, format, ap);
1394 #else
1395 return vsnprintf(*ret, size, format, ap);
1396 #endif
1397 }
1398 #endif /* !HAVE_VASPRINTF */
1399
1400 #if !HAVE_SNPRINTF
1401 #if HAVE_STDARG_H
1402 int
1403 rpl_snprintf(char *str, size_t size, const char *format, ...)
1404 #else
1405 int
1406 rpl_snprintf(va_alist) va_dcl
1407 #endif /* HAVE_STDARG_H */
1408 {
1409 #if !HAVE_STDARG_H
1410 char *str;
1411 size_t size;
1412 char *format;
1413 #endif /* HAVE_STDARG_H */
1414 va_list ap;
1415 int len;
1416
1417 VA_START(ap, format);
1418 VA_SHIFT(ap, str, char *);
1419 VA_SHIFT(ap, size, size_t);
1420 VA_SHIFT(ap, format, const char *);
1421 #if !HAVE_VSNPRINTF
1422 len = rpl_vsnprintf(str, size, format, ap);
1423 #else
1424 len = vsnprintf(str, size, format, ap);
1425 #endif
1426 va_end(ap);
1427 return len;
1428 }
1429 #endif /* !HAVE_SNPRINTF */
1430
1431 #if !HAVE_ASPRINTF
1432 #if HAVE_STDARG_H
1433 int
1434 rpl_asprintf(char **ret, const char *format, ...)
1435 #else
1436 int
1437 rpl_asprintf(va_alist) va_dcl
1438 #endif /* HAVE_STDARG_H */
1439 {
1440 #if !HAVE_STDARG_H
1441 char **ret;
1442 char *format;
1443 #endif /* HAVE_STDARG_H */
1444 va_list ap;
1445 int len;
1446
1447 VA_START(ap, format);
1448 VA_SHIFT(ap, ret, char **);
1449 VA_SHIFT(ap, format, const char *);
1450 #if !HAVE_VASPRINTF
1451 len = rpl_vasprintf(ret, format, ap);
1452 #else
1453 len = vasprintf(ret, format, ap);
1454 #endif
1455 va_end(ap);
1456 return len;
1457 }
1458 #endif /* !HAVE_ASPRINTF */
1459 #else /* Dummy declaration to avoid empty translation unit warnings. */
1460 int main(int argc, char **argv);
1461 #endif /* !HAVE_SNPRINTF || !HAVE_VSNPRINTF || !HAVE_ASPRINTF || [...] */