Actually hook powernow.4 into the build.
[dragonfly.git] / contrib / mpfr / vasprintf.c
blobc22703598eefe29ecaa3ec5bf20862111e2e07b1
1 /* mpfr_vasprintf -- main function for the printf functions family
2 plus helper macros & functions.
4 Copyright 2007, 2008, 2009 Free Software Foundation, Inc.
5 Contributed by the Arenaire and Cacao projects, INRIA.
7 This file is part of the GNU MPFR Library.
9 The GNU MPFR Library is free software; you can redistribute it and/or modify
10 it under the terms of the GNU Lesser General Public License as published by
11 the Free Software Foundation; either version 2.1 of the License, or (at your
12 option) any later version.
14 The GNU MPFR Library is distributed in the hope that it will be useful, but
15 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
16 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
17 License for more details.
19 You should have received a copy of the GNU Lesser General Public License
20 along with the GNU MPFR Library; see the file COPYING.LIB. If not, write to
21 the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
22 MA 02110-1301, USA. */
24 #ifdef HAVE_CONFIG_H
25 #include "config.h"
26 #endif
28 /* The mpfr_printf-like functions are defined only if stdarg.h exists */
29 #ifdef HAVE_STDARG
31 #include <stdarg.h>
33 #ifdef HAVE_WCHAR_H
34 #include <wchar.h>
35 #endif
37 #if defined (__cplusplus)
38 #include <cstddef>
39 #define __STDC_LIMIT_MACROS /* SIZE_MAX defined with stdint.h inclusion */
40 #else
41 #include <stddef.h> /* for ptrdiff_t */
42 #endif
44 #if HAVE_INTTYPES_H
45 # include <inttypes.h> /* for intmax_t */
46 #else
47 # if HAVE_STDINT_H
48 # include <stdint.h>
49 # endif
50 #endif
52 #include <string.h> /* for strlen, memcpy and others */
54 #include "mpfr-impl.h"
56 /* Define a length modifier corresponding to mp_prec_t.
57 We use literal string instead of literal character so as to permit future
58 extension to long long int ("ll"). */
59 #if _MPFR_PREC_FORMAT == 1
60 #define MPFR_PREC_FORMAT_TYPE "h"
61 #define MPFR_PREC_FORMAT_SIZE 1
62 #elif _MPFR_PREC_FORMAT == 2
63 #define MPFR_PREC_FORMAT_TYPE ""
64 #define MPFR_PREC_FORMAT_SIZE 0
65 #elif _MPFR_PREC_FORMAT == 3
66 #define MPFR_PREC_FORMAT_TYPE "l"
67 #define MPFR_PREC_FORMAT_SIZE 1
68 #else
69 #error "mpfr_prec_t size not supported"
70 #endif
72 #if (__GMP_MP_SIZE_T_INT == 1)
73 #define MPFR_EXP_FORMAT_SPEC "i"
74 #elif (__GMP_MP_SIZE_T_INT == 0)
75 #define MPFR_EXP_FORMAT_SPEC "li"
76 #else
77 #error "mp_exp_t size not supported"
78 #endif
80 /* Output for special values defined in the C99 standard */
81 #define MPFR_NAN_STRING_LC "nan"
82 #define MPFR_NAN_STRING_UC "NAN"
83 #define MPFR_NAN_STRING_LENGTH 3
84 #define MPFR_INF_STRING_LC "inf"
85 #define MPFR_INF_STRING_UC "INF"
86 #define MPFR_INF_STRING_LENGTH 3
88 /* The implicit \0 is useless, but we do not write num_to_text[16]
89 otherwise g++ complains. */
90 static const char num_to_text[] = "0123456789abcdef";
92 /* some macro and functions for parsing format string */
94 /* Read an integer; saturate to INT_MAX. */
95 #define READ_INT(ap, format, specinfo, field, label_out) \
96 do { \
97 while (*(format)) \
98 { \
99 int _i; \
100 switch (*(format)) \
102 case '0': \
103 case '1': \
104 case '2': \
105 case '3': \
106 case '4': \
107 case '5': \
108 case '6': \
109 case '7': \
110 case '8': \
111 case '9': \
112 specinfo.field = (specinfo.field <= INT_MAX / 10) ? \
113 specinfo.field * 10 : INT_MAX; \
114 _i = *(format) - '0'; \
115 MPFR_ASSERTN (_i >= 0 && _i <= 9); \
116 specinfo.field = (specinfo.field <= INT_MAX - _i) ? \
117 specinfo.field + _i : INT_MAX; \
118 ++(format); \
119 break; \
120 case '*': \
121 specinfo.field = va_arg ((ap), int); \
122 ++(format); \
123 default: \
124 goto label_out; \
127 } while (0)
129 /* arg_t contains all the types described by the 'type' field of the
130 format string */
131 enum arg_t
133 NONE,
134 CHAR_ARG,
135 SHORT_ARG,
136 LONG_ARG,
137 LONG_LONG_ARG,
138 QUAD_ARG,
139 INTMAX_ARG,
140 SIZE_ARG,
141 PTRDIFF_ARG,
142 LONG_DOUBLE_ARG,
143 MPF_ARG,
144 MPQ_ARG,
145 MP_LIMB_ARG,
146 MP_LIMB_ARRAY_ARG,
147 MPZ_ARG,
148 MPFR_PREC_ARG,
149 MPFR_ARG,
150 UNSUPPORTED
153 /* Each conversion specification of the format string will be translated in a
154 printf_spec structure by the parser.
155 This structure is adapted from the GNU libc one. */
156 struct printf_spec
158 unsigned int alt:1; /* # flag */
159 unsigned int space:1; /* Space flag */
160 unsigned int left:1; /* - flag */
161 unsigned int showsign:1; /* + flag */
162 unsigned int group:1; /* ' flag */
164 int width; /* Width */
165 int prec; /* Precision */
167 enum arg_t arg_type; /* Type of argument */
168 mp_rnd_t rnd_mode; /* Rounding mode */
169 char spec; /* Conversion specifier */
171 char pad; /* Padding character */
174 static void
175 specinfo_init (struct printf_spec *specinfo)
177 specinfo->alt = 0;
178 specinfo->space = 0;
179 specinfo->left = 0;
180 specinfo->showsign = 0;
181 specinfo->group = 0;
182 specinfo->width = 0;
183 specinfo->prec = 0;
184 specinfo->arg_type = NONE;
185 specinfo->rnd_mode = GMP_RNDN;
186 specinfo->spec = 'i';
187 specinfo->pad = ' ';
190 static const char *
191 parse_flags (const char *format, struct printf_spec *specinfo)
193 while (*format)
195 switch (*format)
197 case '0':
198 specinfo->pad = '0';
199 ++format;
200 break;
201 case '#':
202 specinfo->alt = 1;
203 ++format;
204 break;
205 case '+':
206 specinfo->showsign = 1;
207 ++format;
208 break;
209 case ' ':
210 specinfo->space = 1;
211 ++format;
212 break;
213 case '-':
214 specinfo->left = 1;
215 ++format;
216 break;
217 case '\'':
218 /* Single UNIX Specification for thousand separator */
219 specinfo->group = 1;
220 ++format;
221 break;
222 default:
223 return format;
226 return format;
229 static const char *
230 parse_arg_type (const char *format, struct printf_spec *specinfo)
232 switch (*format)
234 case '\0':
235 break;
236 case 'h':
237 if (*++format == 'h')
238 #ifndef NPRINTF_HH
240 ++format;
241 specinfo->arg_type = CHAR_ARG;
243 #else
244 specinfo->arg_type = UNSUPPORTED;
245 #endif
246 else
247 specinfo->arg_type = SHORT_ARG;
248 break;
249 case 'l':
250 if (*++format == 'l')
252 ++format;
253 #if defined (HAVE_LONG_LONG) && !defined(NPRINTF_LL)
254 specinfo->arg_type = LONG_LONG_ARG;
255 #else
256 specinfo->arg_type = UNSUPPORTED;
257 #endif
258 break;
260 else
262 specinfo->arg_type = LONG_ARG;
263 break;
265 case 'j':
266 ++format;
267 #if defined(_MPFR_H_HAVE_INTMAX_T) && !defined(NPRINTF_J)
268 specinfo->arg_type = INTMAX_ARG;
269 #else
270 specinfo->arg_type = UNSUPPORTED;
271 #endif
272 break;
273 case 'z':
274 ++format;
275 specinfo->arg_type = SIZE_ARG;
276 break;
277 case 't':
278 ++format;
279 #ifndef NPRINTF_T
280 specinfo->arg_type = PTRDIFF_ARG;
281 #else
282 specinfo->arg_type = UNSUPPORTED;
283 #endif
284 break;
285 case 'L':
286 ++format;
287 #ifndef NPRINTF_L
288 specinfo->arg_type = LONG_DOUBLE_ARG;
289 #else
290 specinfo->arg_type = UNSUPPORTED;
291 #endif
292 break;
293 case 'F':
294 ++format;
295 specinfo->arg_type = MPF_ARG;
296 break;
297 case 'Q':
298 ++format;
299 specinfo->arg_type = MPQ_ARG;
300 break;
301 case 'M':
302 ++format;
303 /* The 'M' specifier was added in gmp 4.2.0 */
304 specinfo->arg_type = MP_LIMB_ARG;
305 break;
306 case 'N':
307 ++format;
308 specinfo->arg_type = MP_LIMB_ARRAY_ARG;
309 break;
310 case 'Z':
311 ++format;
312 specinfo->arg_type = MPZ_ARG;
313 break;
315 /* mpfr specific specifiers */
316 case 'P':
317 ++format;
318 specinfo->arg_type = MPFR_PREC_ARG;
319 break;
320 case 'R':
321 ++format;
322 specinfo->arg_type = MPFR_ARG;
324 return format;
328 /* some macros and functions filling the buffer */
330 /* CONSUME_VA_ARG removes from va_list AP the type expected by SPECINFO */
332 /* With a C++ compiler wchar_t and enumeration in va_list are converted to
333 integer type : int, unsigned int, long or unsigned long (unfortunately,
334 this is implementation dependant).
335 We follow gmp which assumes in print/doprnt.c that wchar_t is converted
336 to int. */
337 #ifdef HAVE_WCHAR_H
338 #define CASE_LONG_ARG(specinfo, ap) \
339 case LONG_ARG: \
340 if (((specinfo).spec == 'd') || ((specinfo).spec == 'i') \
341 || ((specinfo).spec == 'o') || ((specinfo).spec == 'u') \
342 || ((specinfo).spec == 'x') || ((specinfo).spec == 'X')) \
343 (void) va_arg ((ap), long); \
344 else if ((specinfo).spec == 'c') \
345 (void) va_arg ((ap), wint_t); \
346 else if ((specinfo).spec == 's') \
347 (void) va_arg ((ap), int); /* we assume integer promotion */ \
348 break;
349 #else
350 #define CASE_LONG_ARG(specinfo, ap) \
351 case LONG_ARG: \
352 (void) va_arg ((ap), long); \
353 break;
354 #endif
356 #if defined(_MPFR_H_HAVE_INTMAX_T)
357 #define CASE_INTMAX_ARG(specinfo, ap) \
358 case INTMAX_ARG: \
359 (void) va_arg ((ap), intmax_t); \
360 break;
361 #else
362 #define CASE_INTMAX_ARG(specinfo, ap)
363 #endif
365 #ifdef HAVE_LONG_LONG
366 #define CASE_LONG_LONG_ARG(specinfo, ap) \
367 case LONG_LONG_ARG: \
368 (void) va_arg ((ap), long long); \
369 break;
370 #else
371 #define CASE_LONG_LONG_ARG(specinfo, ap)
372 #endif
374 #define CONSUME_VA_ARG(specinfo, ap) \
375 do { \
376 switch ((specinfo).arg_type) \
378 case CHAR_ARG: \
379 case SHORT_ARG: \
380 (void) va_arg ((ap), int); \
381 break; \
382 CASE_LONG_ARG (specinfo, ap) \
383 CASE_LONG_LONG_ARG (specinfo, ap) \
384 CASE_INTMAX_ARG (specinfo, ap) \
385 case SIZE_ARG: \
386 (void) va_arg ((ap), size_t); \
387 break; \
388 case PTRDIFF_ARG: \
389 (void) va_arg ((ap), ptrdiff_t); \
390 break; \
391 case LONG_DOUBLE_ARG: \
392 (void) va_arg ((ap), long double); \
393 break; \
394 case MPF_ARG: \
395 (void) va_arg ((ap), mpf_srcptr); \
396 break; \
397 case MPQ_ARG: \
398 (void) va_arg ((ap), mpq_srcptr); \
399 break; \
400 case MP_LIMB_ARG: \
401 (void) va_arg ((ap), mp_ptr); \
402 break; \
403 case MP_LIMB_ARRAY_ARG: \
404 (void) va_arg ((ap), mp_ptr); \
405 (void) va_arg ((ap), mp_size_t); \
406 break; \
407 case MPZ_ARG: \
408 (void) va_arg ((ap), mpz_srcptr); \
409 break; \
410 default: \
411 switch ((specinfo).spec) \
413 case 'd': \
414 case 'i': \
415 case 'o': \
416 case 'u': \
417 case 'x': \
418 case 'X': \
419 case 'c': \
420 (void) va_arg ((ap), int); \
421 break; \
422 case 'f': \
423 case 'F': \
424 case 'e': \
425 case 'E': \
426 case 'g': \
427 case 'G': \
428 case 'a': \
429 case 'A': \
430 (void) va_arg ((ap), double); \
431 break; \
432 case 's': \
433 (void) va_arg ((ap), char *); \
434 break; \
435 case 'p': \
436 (void) va_arg ((ap), void *); \
439 } while (0)
441 /* process the format part which does not deal with mpfr types,
442 jump to external label 'error' if gmp_asprintf return -1. */
443 #define FLUSH(flag, start, end, ap, buf_ptr) \
444 do { \
445 const size_t n = (end) - (start); \
446 if ((flag)) \
447 /* previous specifiers are understood by gmp_printf */ \
449 MPFR_TMP_DECL (marker); \
450 char *fmt_copy; \
451 MPFR_TMP_MARK (marker); \
452 fmt_copy = (char*) MPFR_TMP_ALLOC ((n + 1) * sizeof(char)); \
453 strncpy (fmt_copy, (start), n); \
454 fmt_copy[n] = '\0'; \
455 if (sprntf_gmp ((buf_ptr), (fmt_copy), (ap)) == -1) \
457 MPFR_TMP_FREE (marker); \
458 goto error; \
460 (flag) = 0; \
461 MPFR_TMP_FREE (marker); \
463 else if ((start) != (end)) \
464 /* no conversion specification, just simple characters */ \
465 buffer_cat ((buf_ptr), (start), n); \
466 } while (0)
468 struct string_buffer
470 char *start; /* beginning of the buffer */
471 char *curr; /* last character (!= '\0') written */
472 size_t size; /* buffer capacity */
475 static void
476 buffer_init (struct string_buffer *b, size_t s)
478 b->start = (char *) (*__gmp_allocate_func) (s);
479 b->start[0] = '\0';
480 b->curr = b->start;
481 b->size = s;
484 /* Increase buffer size by a number of character being the least multiple of
485 4096 greater than LEN+1. */
486 static void
487 buffer_widen (struct string_buffer *b, size_t len)
489 const size_t pos = b->curr - b->start;
490 const size_t n = sizeof (char) * 4096 * (1 + len / 4096);
492 b->start =
493 (char *) (*__gmp_reallocate_func) (b->start, b->size, b->size + n);
494 b->size += n;
495 b->curr = b->start + pos;
498 /* Concatenate the LEN first characters of the string S to the buffer B and
499 expand it if needed. */
500 static void
501 buffer_cat (struct string_buffer *b, const char *s, size_t len)
503 if (len == 0)
504 return;
506 MPFR_ASSERTN (b->size < SIZE_MAX - len - 1);
507 MPFR_ASSERTD (len <= strlen (s));
508 if (MPFR_UNLIKELY ((b->curr + len + 1) > (b->start + b->size)))
509 buffer_widen (b, len);
511 strncat (b->curr, s, len);
512 b->curr += len;
515 /* Add N characters C to the end of buffer B */
516 static void
517 buffer_pad (struct string_buffer *b, const char c, const size_t n)
519 if (n == 0)
520 return;
522 MPFR_ASSERTN (b->size < SIZE_MAX - n - 1);
523 if (MPFR_UNLIKELY ((b->curr + n + 1) > (b->start + b->size)))
524 buffer_widen (b, n);
526 if (n == 1)
527 *b->curr = c;
528 else
529 memset (b->curr, c, n);
530 b->curr += n;
531 *b->curr = '\0';
534 /* Form a string by concatenating the first LEN characters of STR to TZ
535 zero(s), insert into one character C each 3 characters starting from end
536 to begining and concatenate the result to the buffer B. */
537 static void
538 buffer_sandwich (struct string_buffer *b, char *str, size_t len,
539 const size_t tz, const char c)
541 const size_t step = 3;
542 const size_t size = len + tz;
543 const size_t r = size % step == 0 ? step : size % step;
544 const size_t q = size % step == 0 ? size / step - 1 : size / step;
545 size_t i;
547 if (size == 0)
548 return;
549 if (c == '\0')
551 buffer_cat (b, str, len);
552 buffer_pad (b, '0', tz);
553 return;
556 MPFR_ASSERTN (b->size < SIZE_MAX - size - 1 - q);
557 MPFR_ASSERTD (len <= strlen (str));
558 if (MPFR_UNLIKELY ((b->curr + size + 1 + q) > (b->start + b->size)))
559 buffer_widen (b, size + q);
561 /* first R significant digits */
562 memcpy (b->curr, str, r);
563 b->curr += r;
564 str += r;
565 len -= r;
567 /* blocks of thousands. Warning: STR might end in the middle of a block */
568 for (i = 0; i < q; ++i)
570 *b->curr++ = c;
571 if (MPFR_LIKELY (len > 0))
573 if (MPFR_LIKELY (len >= step))
574 /* step significant digits */
576 memcpy (b->curr, str, step);
577 len -= step;
579 else
580 /* last digits in STR, fill up thousand block with zeros */
582 memcpy (b->curr, str, len);
583 memset (b->curr + len, '0', step - len);
584 len = 0;
587 else
588 /* trailing zeros */
589 memset (b->curr, '0', step);
591 b->curr += step;
592 str += step;
595 *b->curr = '\0';
598 /* let gmp_xprintf process the part it can understand */
599 static int
600 sprntf_gmp (struct string_buffer *b, const char *fmt, va_list ap)
602 int length;
603 char *s;
605 length = gmp_vasprintf (&s, fmt, ap);
606 if (length > 0)
607 buffer_cat (b, s, length);
609 mpfr_free_str (s);
610 return length;
613 /* Helper struct and functions for temporary strings management */
614 /* struct for easy string clearing */
615 struct string_list
617 char *string;
618 struct string_list *next; /* NULL in last node */
621 /* initialisation */
622 static void
623 init_string_list (struct string_list *sl)
625 sl->string = NULL;
626 sl->next = NULL;
629 /* clear all strings in the list */
630 static void
631 clear_string_list (struct string_list *sl)
633 struct string_list *n;
635 while (sl)
637 if (sl->string)
638 mpfr_free_str (sl->string);
639 n = sl->next;
640 (*__gmp_free_func) (sl, sizeof(struct string_list));
641 sl = n;
645 /* add a string in the list */
646 static char *
647 register_string (struct string_list *sl, char *new_string)
649 /* look for the last node */
650 while (sl->next)
651 sl = sl->next;
653 sl->next = (struct string_list*)
654 (*__gmp_allocate_func) (sizeof (struct string_list));
656 sl = sl->next;
657 sl->next = NULL;
658 return sl->string = new_string;
661 /* padding type: where are the padding characters */
662 enum pad_t
664 LEFT, /* spaces in left hand side for right justification */
665 LEADING_ZEROS, /* padding with '0' characters in integral part */
666 RIGHT /* spaces in right hand side for left justification */
669 /* number_parts details how much characters are needed in each part of a float
670 print. */
671 struct number_parts
673 enum pad_t pad_type; /* Padding type */
674 size_t pad_size; /* Number of padding characters */
676 char sign; /* Sign character */
678 char *prefix_ptr; /* Pointer to prefix part */
679 size_t prefix_size; /* Number of characters in *prefix_ptr */
681 char thousands_sep; /* Thousands separator (only with style 'f') */
683 char *ip_ptr; /* Pointer to integral part characters*/
684 size_t ip_size; /* Number of digits in *ip_ptr */
685 int ip_trailing_zeros; /* Number of additional null digits in integral
686 part */
688 char point; /* Decimal point character */
690 int fp_leading_zeros; /* Number of additional leading zeros in fractional
691 part */
692 char *fp_ptr; /* Pointer to fractional part characters */
693 size_t fp_size; /* Number of digits in *fp_ptr */
694 int fp_trailing_zeros; /* Number of additional trailing zeros in fractional
695 part */
697 char *exp_ptr; /* Pointer to exponent part */
698 size_t exp_size; /* Number of characters in *exp_ptr */
700 struct string_list *sl; /* List of string buffers in use: we need such a
701 mechanism because fp_ptr may point into the same
702 string as ip_ptr */
705 /* Determine the different parts of the string representation of the regular
706 number P when SPEC.SPEC is 'a', 'A', or 'b'.
708 return -1 if some field > INT_MAX */
709 static int
710 regular_ab (struct number_parts *np, mpfr_srcptr p,
711 const struct printf_spec spec)
713 int uppercase;
714 int base;
715 char *str;
716 mp_exp_t exp;
718 uppercase = spec.spec == 'A';
720 /* sign */
721 if (MPFR_IS_NEG (p))
722 np->sign = '-';
723 else if (spec.showsign || spec.space)
724 np->sign = spec.showsign ? '+' : ' ';
726 if (spec.spec == 'a' || spec.spec == 'A')
727 /* prefix part */
729 np->prefix_size = 2;
730 str = (char *) (*__gmp_allocate_func) (1 + np->prefix_size);
731 str[0] = '0';
732 str[1] = uppercase ? 'X' : 'x';
733 str[2] = '\0';
734 np->prefix_ptr = register_string (np->sl, str);
737 /* integral part */
738 np->ip_size = 1;
739 base = (spec.spec == 'b') ? 2 : 16;
741 if (spec.spec == 'b' || spec.prec != 0)
742 /* In order to avoid ambiguity in rounding to even case, we will always
743 output at least one fractional digit in binary mode */
745 size_t nsd;
747 /* Number of significant digits:
748 - if no given precision, let mpfr_get_str determine it;
749 - if a zero precision is specified and if we are in binary mode, then
750 ask for two binary digits, one before decimal point, and one after;
751 - if a non-zero precision is specified, then one digit before decimal
752 point plus SPEC.PREC after it. */
753 nsd = spec.prec < 0 ? 0
754 : (spec.prec == 0 && spec.spec == 'b') ? 2 : spec.prec + np->ip_size;
755 str = mpfr_get_str (0, &exp, base, nsd, p, spec.rnd_mode);
756 register_string (np->sl, str);
757 np->ip_ptr = MPFR_IS_NEG (p) ? ++str : str; /* skip sign if any */
759 if (base == 16)
760 /* EXP is the exponent for radix sixteen with decimal point BEFORE the
761 first digit, we want the exponent for radix two and the decimal
762 point AFTER the first digit. */
764 MPFR_ASSERTN (exp > MPFR_EMIN_MIN /4); /* possible overflow */
765 exp = (exp - 1) * 4;
767 else
768 /* EXP is the exponent for decimal point BEFORE the first digit, we
769 want the exponent for decimal point AFTER the first digit. */
771 MPFR_ASSERTN (exp > MPFR_EMIN_MIN); /* possible overflow */
772 --exp;
775 else
776 /* One hexadecimal digit is sufficient but mpfr_get_str returns at least
777 two digits when the base is a power of two.
778 So, in order to avoid double rounding, we will build our own string. */
780 mp_limb_t *pm = MPFR_MANT (p);
781 mp_size_t ps;
782 int digit;
783 unsigned int shift;
784 int rnd_away;
786 /* rnd_away:
787 1 if round away from zero,
788 0 if round to zero,
789 -1 if not decided yet. */
790 rnd_away =
791 spec.rnd_mode == GMP_RNDD ? MPFR_IS_NEG (p) :
792 spec.rnd_mode == GMP_RNDU ? MPFR_IS_POS (p) :
793 spec.rnd_mode == GMP_RNDZ ? 0 : -1;
795 /* exponent for radix-2 with the decimal point after the first
796 hexadecimal digit */
797 MPFR_ASSERTN (MPFR_GET_EXP (p) > MPFR_EMIN_MIN + 3); /* possible
798 overflow */
799 exp = MPFR_GET_EXP (p) - 4;
801 /* Determine the radix-16 digit by grouping the 4 first digits. Even
802 if MPFR_PREC (p) < 4, we can read 4 bits in its first limb */
803 shift = BITS_PER_MP_LIMB - 4;
804 ps = (MPFR_PREC (p) - 1) / BITS_PER_MP_LIMB;
805 digit = pm[ps] >> shift;
807 if (MPFR_PREC (p) > 4)
808 /* round taking into account bits outside the first 4 ones */
810 if (rnd_away == -1)
811 /* Round to nearest mode: we have to decide in that particular
812 case if we have to round away from zero or not */
814 mp_limb_t limb, rb, mask;
816 /* compute rounding bit */
817 mask = MPFR_LIMB_ONE << (shift - 1);
818 rb = pm[ps] & mask;
819 if (rb == 0)
820 rnd_away = 0;
821 else
823 mask = MPFR_LIMB_MASK (shift - 1);
824 limb = pm[ps] & mask;
825 while ((ps > 0) && (limb == 0))
826 limb = pm[--ps];
827 if (limb == 0)
828 /* tie case, round to even */
829 rnd_away = (digit & 1) ? 1 : 0;
830 else
831 rnd_away = 1;
835 MPFR_ASSERTD (rnd_away >= 0); /* rounding direction is defined */
836 if (rnd_away)
838 digit++;
839 if (digit > 15)
840 /* As we want only the first significant digit, we have
841 to shift one position to the left */
843 digit >>= 1;
844 ++exp; /* no possible overflow because
845 exp == EXP(p)-3 */
850 MPFR_ASSERTD ((0 <= digit) && (digit <= 15));
851 np->ip_size = 1;
852 str = (char *)(*__gmp_allocate_func) (1 + np->ip_size);
853 str[0] = num_to_text [digit];
854 str[1] = '\0';
856 np->ip_ptr = register_string (np->sl, str);
859 if (uppercase)
860 /* All digits in upper case */
862 char *s1 = str;
863 while (*s1)
865 switch (*s1)
867 case 'a':
868 *s1 = 'A';
869 break;
870 case 'b':
871 *s1 = 'B';
872 break;
873 case 'c':
874 *s1 = 'C';
875 break;
876 case 'd':
877 *s1 = 'D';
878 break;
879 case 'e':
880 *s1 = 'E';
881 break;
882 case 'f':
883 *s1 = 'F';
884 break;
886 s1++;
890 if (spec.spec == 'b' || spec.prec != 0)
891 /* compute the number of digits in fractional part */
893 char *ptr;
894 size_t str_len;
896 /* the sign has been skipped, skip also the first digit */
897 ++str;
898 str_len = strlen (str);
899 ptr = str + str_len - 1; /* points to the end of str */
901 if (spec.prec < 0)
902 /* remove trailing zeros, if any */
904 while ((*ptr == '0') && (str_len != 0))
906 --ptr;
907 --str_len;
911 if (str_len > INT_MAX)
912 /* too much digits in fractional part */
913 return -1;
915 if (str_len != 0)
916 /* there are some non-zero digits in fractional part */
918 np->fp_ptr = str;
919 np->fp_size = str_len;
920 if ((int) str_len < spec.prec)
921 np->fp_trailing_zeros = spec.prec - str_len;
925 /* decimal point */
926 if ((np->fp_size != 0) || spec.alt)
927 np->point = MPFR_DECIMAL_POINT;
929 /* the exponent part contains the character 'p', or 'P' plus the sign
930 character plus at least one digit and only as many more digits as
931 necessary to represent the exponent.
932 We assume that |EXP| < 10^INT_MAX. */
933 np->exp_size = 3;
935 mp_exp_unsigned_t x;
937 x = SAFE_ABS (mp_exp_unsigned_t, exp);
938 while (x > 9)
940 np->exp_size++;
941 x /= 10;
944 str = (char *) (*__gmp_allocate_func) (1 + np->exp_size);
945 np->exp_ptr = register_string (np->sl, str);
947 char exp_fmt[8]; /* contains at most 7 characters like in "p%+.1i",
948 or "P%+.2li" */
950 exp_fmt[0] = uppercase ? 'P' : 'p';
951 exp_fmt[1] = '\0';
952 strcat (exp_fmt, "%+.1" MPFR_EXP_FORMAT_SPEC);
954 if (sprintf (str, exp_fmt, exp) < 0)
955 return -1;
958 return 0;
961 /* Determine the different parts of the string representation of the regular
962 number P when SPEC.SPEC is 'e', 'E', 'g', or 'G'.
964 return -1 if some field > INT_MAX */
965 static int
966 regular_eg (struct number_parts *np, mpfr_srcptr p,
967 const struct printf_spec spec)
969 char *str;
970 mp_exp_t exp;
972 const int uppercase = spec.spec == 'E' || spec.spec == 'G';
973 const int spec_g = spec.spec == 'g' || spec.spec == 'G';
974 const int keep_trailing_zeros = (spec_g && spec.alt)
975 || (!spec_g && (spec.prec > 0));
977 /* sign */
978 if (MPFR_IS_NEG (p))
979 np->sign = '-';
980 else if (spec.showsign || spec.space)
981 np->sign = spec.showsign ? '+' : ' ';
983 /* integral part */
984 np->ip_size = 1;
986 size_t nsd;
988 /* Number of significant digits:
989 - if no given precision, then let mpfr_get_str determine it,
990 - if a precision is specified, then one digit before decimal point
991 plus SPEC.PREC after it.
992 We use the fact here that mpfr_get_exp allows us to ask for only one
993 significant digit when the base is not a power of 2. */
994 nsd = (spec.prec < 0) ? 0 : spec.prec + np->ip_size;
995 str = mpfr_get_str (0, &exp, 10, nsd, p, spec.rnd_mode);
997 register_string (np->sl, str);
998 np->ip_ptr = MPFR_IS_NEG (p) ? ++str : str; /* skip sign if any */
1000 if (spec.prec != 0)
1001 /* compute the number of digits in fractional part */
1003 char *ptr;
1004 size_t str_len;
1006 /* the sign has been skipped, skip also the first digit */
1007 ++str;
1008 str_len = strlen (str);
1009 ptr = str + str_len - 1; /* points to the end of str */
1011 if (!keep_trailing_zeros)
1012 /* remove trailing zeros, if any */
1014 while ((*ptr == '0') && (str_len != 0))
1016 --ptr;
1017 --str_len;
1021 if (str_len > INT_MAX)
1022 /* too much digits in fractional part */
1023 return -1;
1025 if (str_len != 0)
1026 /* there are some non-zero digits in fractional part */
1028 np->fp_ptr = str;
1029 np->fp_size = str_len;
1030 if ((!spec_g || spec.alt) && (spec.prec > 0)
1031 && ((int)str_len < spec.prec))
1032 /* add missing trailing zeros */
1033 np->fp_trailing_zeros = spec.prec - str_len;
1037 /* decimal point */
1038 if (np->fp_size != 0 || spec.alt)
1039 np->point = MPFR_DECIMAL_POINT;
1041 /* EXP is the exponent for decimal point BEFORE the first digit, we want
1042 the exponent for decimal point AFTER the first digit.
1043 Here, no possible overflow because exp < MPFR_EXP (p) / 3 */
1044 exp--;
1046 /* the exponent part contains the character 'e', or 'E' plus the sign
1047 character plus at least two digits and only as many more digits as
1048 necessary to represent the exponent.
1049 We assume that |EXP| < 10^INT_MAX. */
1050 np->exp_size = 3;
1052 mp_exp_unsigned_t x;
1054 x = SAFE_ABS (mp_exp_unsigned_t, exp);
1055 while (x > 9)
1057 np->exp_size++;
1058 x /= 10;
1061 if (np->exp_size < 4)
1062 np->exp_size = 4;
1064 str = (char *) (*__gmp_allocate_func) (1 + np->exp_size);
1065 np->exp_ptr = register_string (np->sl, str);
1068 char exp_fmt[8]; /* e.g. "e%+.2i", or "E%+.2li" */
1070 exp_fmt[0] = uppercase ? 'E' : 'e';
1071 exp_fmt[1] = '\0';
1072 strcat (exp_fmt, "%+.2" MPFR_EXP_FORMAT_SPEC);
1074 if (sprintf (str, exp_fmt, exp) < 0)
1075 return -1;
1078 return 0;
1081 /* Determine the different parts of the string representation of the regular
1082 number p when spec.spec is 'f', 'F', 'g', or 'G'.
1084 return -1 if some field of number_parts is greater than INT_MAX */
1085 static int
1086 regular_fg (struct number_parts *np, mpfr_srcptr p,
1087 const struct printf_spec spec)
1089 mpfr_t x;
1090 char * str;
1091 const int spec_g = (spec.spec == 'g' || spec.spec == 'G');
1092 const int keep_trailing_zeros = spec_g && spec.alt;
1094 /* sign */
1095 if (MPFR_IS_NEG (p))
1096 np->sign = '-';
1097 else if (spec.showsign || spec.space)
1098 np->sign = spec.showsign ? '+' : ' ';
1100 /* Determine the position of the most significant decimal digit. */
1102 /* Let p = m*10^e with 1 <= m < 10 and p = n*2^d with 0.5 <= d < 1.
1103 We need at most 1+log2(floor(d/3)+1) bits of precision in order to
1104 represent the exact value of e+1 if p >= 1, or |e| if p < 1. */
1105 mp_prec_t m;
1106 mp_prec_t n;
1108 m = (mp_prec_t) SAFE_ABS (mp_exp_unsigned_t, MPFR_GET_EXP (p));
1109 m /= 3;
1110 m++;
1111 n = 1;
1112 while (m != 0)
1114 m >>= 1;
1115 n++;
1118 if (n <= MPFR_PREC (p))
1119 mpfr_init2 (x, MPFR_PREC (p) + 1);
1120 else
1121 mpfr_init2 (x, n);
1124 if (MPFR_GET_EXP (p) <= 0)
1125 /* 0 < p < 1 */
1127 int rnd_to_one;
1129 /* Is p round to +/-1 with rounding mode spec.rnd_mode and precision
1130 spec.prec ? rnd_to_one:
1131 1 if |p| output as "1.00_0"
1132 0 if |p| output as "0.dd_d"
1133 -1 if not decided yet */
1135 if (spec_g || spec.prec >= 0)
1137 mpfr_t y;
1138 mpfr_t u;
1140 mpfr_init2 (u, MPFR_PREC (p));
1142 /* compare y = |p| and 1 - 10^(-spec.prec) */
1143 MPFR_ALIAS (y, p, 1, MPFR_EXP (p));
1144 mpfr_set_si (u, -spec.prec, GMP_RNDN); /* FIXME: analyze error */
1145 mpfr_exp10 (u, u, GMP_RNDN);
1146 mpfr_ui_sub (x, 1, u, GMP_RNDN);
1148 rnd_to_one =
1149 mpfr_cmp (y, x) < 0 ? 0 :
1150 spec.rnd_mode == GMP_RNDD ? MPFR_IS_NEG (p) :
1151 spec.rnd_mode == GMP_RNDU ? MPFR_IS_POS (p) :
1152 spec.rnd_mode == GMP_RNDZ ? 0 : -1;
1154 if (rnd_to_one == -1)
1155 /* round to nearest mode */
1157 /* round to 1 iff y = |p| > 1 - 0.5 * 10^(-spec.prec) */
1158 mpfr_div_2ui (x, u, 1, GMP_RNDN);
1159 mpfr_ui_sub (x, 1, x, GMP_RNDN);
1161 rnd_to_one = mpfr_cmp (y, x) > 0 ? 1 : 0;
1163 mpfr_clear (u);
1165 else
1166 rnd_to_one = 0;
1168 MPFR_ASSERTD (rnd_to_one >= 0); /* rnd_to_one is defined */
1169 if (rnd_to_one)
1170 /* one digit '1' in integral part */
1172 /* integral part */
1173 np->ip_size = 1;
1174 str = (char *) (*__gmp_allocate_func) (1 + np->ip_size);
1175 str[0] = '1';
1176 str[1] = '\0';
1177 np->ip_ptr = register_string (np->sl, str);
1179 if (spec.prec > 0)
1180 /* fractional part */
1182 if (spec_g)
1183 /* with specifier 'g', spec.prec is the number of
1184 significant digits to display, take into account the digit
1185 '1' in the integral part*/
1186 np->fp_trailing_zeros = spec.alt ? spec.prec - 1 : 0;
1187 else
1188 /* with specifier 'f', spec.prec is the number of digits
1189 after the decimal point */
1190 np->fp_trailing_zeros = spec.prec;
1193 else
1194 /* one digit '0' in integral part */
1196 /* integral part */
1197 np->ip_size = 1;
1198 str = (char *) (*__gmp_allocate_func) (1 + np->ip_size);
1199 str[0] = '0';
1200 str[1] = '\0';
1201 np->ip_ptr = register_string (np->sl, str);
1203 if (spec.prec != 0)
1204 /* fractional part */
1206 mpfr_t y;
1208 MPFR_ALIAS (y, p, 1, MPFR_EXP (p)); /* y = |p| */
1209 mpfr_log10 (x, y, GMP_RNDD); /* FIXME: analyze error */
1210 mpfr_floor (x, x);
1211 mpfr_abs (x, x, GMP_RNDD);
1212 /* We have rounded away from zero so that x == |e| (with
1213 p = m*10^e, see above). */
1215 if ((spec.prec > 0 && mpfr_cmp_si (x, spec.prec) > 0)
1216 || (spec_g && mpfr_cmp_ui (x, 5) == 0))
1217 /* p is too small for the given precision,
1218 output "0.0_00" or "0.0_01" depending on rnd_mode */
1220 int rnd_away;
1222 /* rnd_away:
1223 1 if round away from zero,
1224 0 if round to zero,
1225 -1 if not decided yet. */
1226 rnd_away =
1227 spec.rnd_mode == GMP_RNDD ? MPFR_IS_NEG (p) :
1228 spec.rnd_mode == GMP_RNDU ? MPFR_IS_POS (p) :
1229 spec.rnd_mode == GMP_RNDZ ? 0 : -1;
1231 if (rnd_away == -1)
1232 /* round to nearest mode */
1234 /* round away iff |p| with x = 0.5 * 10^(-spec.prec) */
1235 mpfr_set_si (x, -spec.prec, GMP_RNDN);
1236 mpfr_exp10 (x, x, GMP_RNDN);
1237 mpfr_div_2ui (x, x, 1, GMP_RNDN);
1239 rnd_away = mpfr_cmp (y, x) > 0 ? 1 : 0;
1242 MPFR_ASSERTD (rnd_away >= 0); /* rounding direction is
1243 defined */
1244 if (rnd_away)
1245 /* the last output digit is '1' */
1247 if (spec_g)
1248 /* |p| is output as 0.0001 */
1249 np->fp_leading_zeros = 3;
1250 else
1251 np->fp_leading_zeros = spec.prec - 1;
1253 np->fp_size = 1;
1254 str = (char *) (*__gmp_allocate_func) (1 + np->fp_size);
1255 str[0] = '1';
1256 str[1] = '\0';
1257 np->fp_ptr = register_string (np->sl, str);
1259 else
1260 /* only spec.prec zeros in fractional part */
1261 np->fp_leading_zeros = spec.prec;
1263 else
1264 /* some significant digits can be output in the fractional
1265 part */
1267 mp_exp_t exp;
1268 char *ptr;
1269 size_t str_len;
1270 const size_t nsd = spec.prec < 0 ? 0
1271 : spec.prec - mpfr_get_ui (x, GMP_RNDZ) + 1;
1272 /* WARNING: nsd may equal 1, we use here the fact that
1273 mpfr_get_str can return one digit with base ten
1274 (undocumented feature, see comments in get_str.c) */
1276 str = mpfr_get_str (NULL, &exp, 10, nsd, p, spec.rnd_mode);
1277 register_string (np->sl, str);
1278 np->fp_ptr = MPFR_IS_NEG (p) ? ++str : str; /* skip sign */
1279 np->fp_leading_zeros = exp < 0 ? -exp : 0;
1281 str_len = strlen (str); /* the sign has been skipped */
1282 ptr = str + str_len - 1; /* points to the end of str */
1284 if (!keep_trailing_zeros)
1285 /* remove trailing zeros, if any */
1287 while ((*ptr == '0') && str_len)
1289 --ptr;
1290 --str_len;
1294 if (str_len > INT_MAX)
1295 /* too much digits in fractional part */
1297 mpfr_clear (x);
1298 return -1;
1300 MPFR_ASSERTD (str_len > 0);
1301 np->fp_size = str_len;
1303 if (!spec_g && (spec.prec > 0)
1304 && (np->fp_leading_zeros + np->fp_size < spec.prec))
1305 /* add missing trailing zeros */
1306 np->fp_trailing_zeros = spec.prec - np->fp_leading_zeros
1307 - np->fp_size;
1311 if (spec.alt || np->fp_leading_zeros != 0 || np->fp_size != 0
1312 || np->fp_trailing_zeros != 0)
1313 np->point = MPFR_DECIMAL_POINT;
1315 else
1316 /* 1 <= p */
1318 mp_exp_t exp;
1319 size_t nsd; /* Number of significant digits */
1321 mpfr_abs (x, p, GMP_RNDD); /* With our choice of precision,
1322 x == |p| exactly. */
1323 mpfr_log10 (x, x, GMP_RNDZ);
1324 mpfr_floor (x, x);
1325 mpfr_add_ui (x, x, 1, GMP_RNDZ);
1326 /* We have rounded towards zero so that x == e + 1 (with p = m*10^e,
1327 see above). x is now the number of digits in the integral part. */
1329 MPFR_ASSERTD (mpfr_cmp_si (x, 0) >= 0);
1330 if (mpfr_cmp_ui (x, INT_MAX) > 0)
1331 /* P is too large to print all its integral part digits */
1333 mpfr_clear (x);
1334 return -1;
1337 np->ip_size = mpfr_get_ui (x, GMP_RNDN);
1339 nsd = spec.prec < 0 ? 0 : spec.prec + np->ip_size;
1340 str = mpfr_get_str (NULL, &exp, 10, nsd, p, spec.rnd_mode);
1341 register_string (np->sl, str);
1342 np->ip_ptr = MPFR_IS_NEG (p) ? ++str : str; /* skip sign */
1344 if (spec.group)
1345 /* thousands separator in integral part */
1346 np->thousands_sep = MPFR_THOUSANDS_SEPARATOR;
1348 if (nsd == 0 || (spec_g && !spec.alt))
1349 /* compute how much non-zero digits in integral and fractional
1350 parts */
1352 size_t str_len;
1353 str_len = strlen (str); /* note: the sign has been skipped */
1355 if (np->ip_size > str_len)
1356 /* mpfr_get_str doesn't give the trailing zeros when p is a
1357 multiple of 10 (p integer, so no fractional part) */
1359 np->ip_trailing_zeros = np->ip_size - str_len;
1360 np->ip_size = str_len;
1361 if (spec.alt)
1362 np->point = MPFR_DECIMAL_POINT;
1364 else
1365 /* str may contain some digits which are in fractional part */
1367 char *ptr;
1369 ptr = str + str_len - 1; /* points to the end of str */
1370 str_len -= np->ip_size; /* number of digits in fractional
1371 part */
1373 if (!keep_trailing_zeros)
1374 /* remove trailing zeros, if any */
1376 while ((*ptr == '0') && (str_len != 0))
1378 --ptr;
1379 --str_len;
1383 if (str_len > INT_MAX)
1384 /* too much digits in fractional part */
1386 mpfr_clear (x);
1387 return -1;
1390 if (str_len != 0)
1391 /* some digits in fractional part */
1393 np->point = MPFR_DECIMAL_POINT;
1394 np->fp_ptr = str + np->ip_size;
1395 np->fp_size = str_len;
1397 else if (spec.alt)
1398 np->point = MPFR_DECIMAL_POINT;
1401 else
1402 /* spec.prec digits in fractional part */
1404 MPFR_ASSERTD (np->ip_size == exp);
1406 if (spec.prec != 0)
1408 np->point = MPFR_DECIMAL_POINT;
1409 np->fp_ptr = str + np->ip_size;
1410 np->fp_size = spec.prec;
1412 else if (spec.alt)
1413 np->point = MPFR_DECIMAL_POINT;
1417 mpfr_clear (x);
1418 return 0;
1421 /* partition_number determines the different parts of the string
1422 representation of the number p according to the given specification.
1423 partition_number initializes the given structure np, so all previous
1424 information in that variable is lost.
1425 return the total number of characters to be written.
1426 return -1 if an error occured, in that case np's fields are in an undefined
1427 state but all string buffers have been freed. */
1428 static int
1429 partition_number (struct number_parts *np, mpfr_srcptr p,
1430 struct printf_spec spec)
1432 char *str;
1433 long total;
1434 int uppercase;
1436 /* WARNING: left justification means right space padding */
1437 np->pad_type = spec.left ? RIGHT : spec.pad == '0' ? LEADING_ZEROS : LEFT;
1438 np->pad_size = 0;
1439 np->sign = '\0';
1440 np->prefix_ptr =NULL;
1441 np->prefix_size = 0;
1442 np->thousands_sep = '\0';
1443 np->ip_ptr = NULL;
1444 np->ip_size = 0;
1445 np->ip_trailing_zeros = 0;
1446 np->point = '\0';
1447 np->fp_leading_zeros = 0;
1448 np->fp_ptr = NULL;
1449 np->fp_size = 0;
1450 np->fp_trailing_zeros = 0;
1451 np->exp_ptr = NULL;
1452 np->exp_size = 0;
1453 np->sl = (struct string_list *)
1454 (*__gmp_allocate_func) (sizeof (struct string_list));
1455 init_string_list (np->sl);
1457 uppercase = spec.spec == 'A' || spec.spec == 'E' || spec.spec == 'F'
1458 || spec.spec == 'G';
1460 if (MPFR_UNLIKELY (MPFR_IS_SINGULAR (p)))
1462 if (MPFR_IS_NAN (p))
1464 if (np->pad_type == LEADING_ZEROS)
1465 /* don't want "0000nan", change to right justification padding
1466 with left spaces instead */
1467 np->pad_type = LEFT;
1469 if (uppercase)
1471 np->ip_size = MPFR_NAN_STRING_LENGTH;
1472 str = (char *) (*__gmp_allocate_func) (1 + np->ip_size);
1473 strcpy (str, MPFR_NAN_STRING_UC);
1474 np->ip_ptr = register_string (np->sl, str);
1476 else
1478 np->ip_size = MPFR_NAN_STRING_LENGTH;
1479 str = (char *) (*__gmp_allocate_func) (1 + np->ip_size);
1480 strcpy (str, MPFR_NAN_STRING_LC);
1481 np->ip_ptr = register_string (np->sl, str);
1484 else if (MPFR_IS_INF (p))
1486 if (np->pad_type == LEADING_ZEROS)
1487 /* don't want "0000inf", change to right justification padding
1488 with left spaces instead */
1489 np->pad_type = LEFT;
1491 if (MPFR_IS_NEG (p))
1492 np->sign = '-';
1494 if (uppercase)
1496 np->ip_size = MPFR_INF_STRING_LENGTH;
1497 str = (char *) (*__gmp_allocate_func) (1 + np->ip_size);
1498 strcpy (str, MPFR_INF_STRING_UC);
1499 np->ip_ptr = register_string (np->sl, str);
1501 else
1503 np->ip_size = MPFR_INF_STRING_LENGTH;
1504 str = (char *) (*__gmp_allocate_func) (1 + np->ip_size);
1505 strcpy (str, MPFR_INF_STRING_LC);
1506 np->ip_ptr = register_string (np->sl, str);
1509 else
1510 /* p == 0 */
1512 /* note: for 'g' spec, zero is always displayed with 'f'-style with
1513 precision spec.prec - 1 and the trailing zeros are removed unless
1514 the flag '#' is used. */
1515 if (MPFR_IS_NEG (p))
1516 /* signed zero */
1517 np->sign = '-';
1518 else if (spec.showsign || spec.space)
1519 np->sign = spec.showsign ? '+' : ' ';
1521 if (spec.spec == 'a' || spec.spec == 'A')
1522 /* prefix part */
1524 np->prefix_size = 2;
1525 str = (char *) (*__gmp_allocate_func) (1 + np->prefix_size);
1526 str[0] = '0';
1527 str[1] = uppercase ? 'X' : 'x';
1528 str[2] = '\0';
1529 np->prefix_ptr = register_string (np->sl, str);
1532 /* integral part */
1533 np->ip_size = 1;
1534 str = (char *) (*__gmp_allocate_func) (1 + np->ip_size);
1535 str[0] = '0';
1536 str[1] = '\0';
1537 np->ip_ptr = register_string (np->sl, str);
1539 if (spec.prec > 0
1540 && ((spec.spec != 'g' && spec.prec != 'G') || spec.alt))
1541 /* fractional part */
1543 np->point = MPFR_DECIMAL_POINT;
1544 np->fp_trailing_zeros = (spec.spec == 'g' && spec.prec == 'G') ?
1545 spec.prec - 1 : spec.prec;
1547 else if (spec.alt)
1548 np->point = MPFR_DECIMAL_POINT;
1550 if (spec.spec == 'a' || spec.spec == 'A' || spec.spec == 'b'
1551 || spec.spec == 'e' || spec.spec == 'E')
1552 /* exponent part */
1554 np->exp_size = (spec.spec == 'e' || spec.spec == 'E') ? 4 : 3;
1555 str = (char *) (*__gmp_allocate_func) (1 + np->exp_size);
1556 if (spec.spec == 'e' || spec.spec == 'E')
1557 strcpy (str, uppercase ? "E+00" : "e+00");
1558 else
1559 strcpy (str, uppercase ? "P+0" : "p+0");
1560 np->exp_ptr = register_string (np->sl, str);
1564 else
1565 /* regular p, p != 0 */
1567 if (spec.spec == 'a' || spec.spec == 'A' || spec.spec == 'b')
1569 if (regular_ab (np, p, spec) == -1)
1570 goto error;
1572 else if (spec.spec == 'f' || spec.spec == 'F')
1574 if (regular_fg (np, p, spec) == -1)
1575 goto error;
1577 else if (spec.spec == 'e' || spec.spec == 'E')
1579 if (regular_eg (np, p, spec) == -1)
1580 goto error;
1582 else
1583 /* %g case */
1585 /* Use the C99 rules:
1586 if T > X >= -4 then the conversion is with style 'f'/'F' and
1587 precision T-(X+1).
1588 otherwise, the conversion is with style 'e'/'E' and
1589 precision T-1.
1590 where T is the threshold computed below and X is the exponent
1591 that would be displayed with style 'e'. */
1592 int threshold;
1593 long x;
1594 mpfr_t y;
1596 MPFR_ALIAS (y, p, 1, MPFR_EXP (p)); /* y = |p| */
1598 threshold = (spec.prec < 0) ? 6 : (spec.prec == 0) ? 1 : spec.prec;
1600 mpfr_t z;
1602 mpfr_init2 (z, 53);
1603 mpfr_log10 (z, y, GMP_RNDD);
1604 x = mpfr_get_si (z, GMP_RNDD);
1605 mpfr_clear (z);
1608 if (x < threshold && x >= -5)
1610 if (x == -5)
1611 /* |p| might be rounded to 1e-4 */
1613 int round_to_1em4;
1615 /* round_to_1em4:
1616 1 if |p| rounded to 1e-4,
1617 0 if not,
1618 -1 if not decided yet. */
1619 round_to_1em4 =
1620 spec.rnd_mode == GMP_RNDD ? MPFR_IS_NEG (p) :
1621 spec.rnd_mode == GMP_RNDU ? MPFR_IS_POS (p) :
1622 spec.rnd_mode == GMP_RNDZ ? 0 : -1;
1624 if (round_to_1em4 == -1)
1625 /* round to nearest mode: |p| is output as "1e-04" iff
1626 0 < 10^(-4) - |p| <= 5 * 10^(-threshold-5) */
1628 mpfr_t z;
1630 mpfr_init2 (z, MPFR_PREC (p)); /* FIXME: analyse error*/
1631 mpfr_set_si (z, -threshold, GMP_RNDN);
1632 mpfr_exp10 (z, z, GMP_RNDN);
1633 mpfr_div_2ui (z, z, 1, GMP_RNDN);
1634 mpfr_ui_sub (z, 1, z, GMP_RNDN);
1635 /* here, z = 1 - 10^(-threshold)/2 */
1637 mpfr_div_ui (z, z, 625, GMP_RNDN);
1638 mpfr_div_2ui (z, z, 4, GMP_RNDN);
1640 round_to_1em4 = mpfr_cmp (y, z) < 0 ? 0 : 1;
1641 mpfr_clear (z);
1644 MPFR_ASSERTD (round_to_1em4 >= 0); /* rounding is defined */
1645 if (round_to_1em4)
1646 /* |p| = 0.0000abc_d is output as "1.00_0e-04" with
1647 style 'e', so the conversion is with style 'f' */
1649 spec.prec = threshold + 3;
1651 if (regular_fg (np, p, spec) == -1)
1652 goto error;
1654 else
1655 /* |p| = 0.0000abc_d is output as "a.bc_de-05" with
1656 style 'e', so the conversion is with style 'e' */
1658 spec.prec = threshold - 1;
1660 if (regular_eg (np, p, spec) == -1)
1661 goto error;
1664 else
1665 /* x >= -4, the conversion is with style 'f' */
1667 spec.prec = threshold - 1 - x;
1669 if (regular_fg (np, p, spec) == -1)
1670 goto error;
1673 else
1675 spec.prec = threshold - 1;
1677 if (regular_eg (np, p, spec) == -1)
1678 goto error;
1683 /* compute the number of characters to be written verifying it is not too
1684 much */
1685 total = np->sign ? 1 : 0;
1686 total += np->prefix_size;
1687 total += np->ip_size;
1688 if (MPFR_UNLIKELY (total < 0 || total > INT_MAX))
1689 goto error;
1690 total += np->ip_trailing_zeros;
1691 if (MPFR_UNLIKELY (total < 0 || total > INT_MAX))
1692 goto error;
1693 if (np->thousands_sep)
1694 /* ' flag, style f and the thousands separator in current locale is not
1695 reduced to the null character */
1696 total += (np->ip_size + np->ip_trailing_zeros) / 3;
1697 if (MPFR_UNLIKELY (total < 0 || total > INT_MAX))
1698 goto error;
1699 if (np->point)
1700 ++total;
1701 total += np->fp_leading_zeros;
1702 if (MPFR_UNLIKELY (total < 0 || total > INT_MAX))
1703 goto error;
1704 total += np->fp_size;
1705 if (MPFR_UNLIKELY (total < 0 || total > INT_MAX))
1706 goto error;
1707 total += np->fp_trailing_zeros;
1708 if (MPFR_UNLIKELY (total < 0 || total > INT_MAX))
1709 goto error;
1710 total += np->exp_size;
1711 if (MPFR_UNLIKELY (total < 0 || total > INT_MAX))
1712 goto error;
1714 if (spec.width > total)
1715 /* pad with spaces or zeros depending on np->pad_type */
1717 np->pad_size = spec.width - total;
1718 total += np->pad_size; /* here total == spec.width,
1719 so 0 < total < INT_MAX */
1722 return total;
1724 error:
1725 clear_string_list (np->sl);
1726 np->prefix_ptr = NULL;
1727 np->ip_ptr = NULL;
1728 np->fp_ptr = NULL;
1729 np->exp_ptr = NULL;
1730 return -1;
1733 /* sprnt_fp prints a mpfr_t according to spec.spec specification.
1735 return the size of the string (not counting the terminating '\0')
1736 return -1 if the built string is too long (i.e. has more than
1737 INT_MAX characters). */
1738 static int
1739 sprnt_fp (struct string_buffer *buf, mpfr_srcptr p,
1740 const struct printf_spec spec)
1742 int length;
1743 struct number_parts np;
1745 length = partition_number (&np, p, spec);
1746 if (length < 0)
1747 return -1;
1749 /* right justification padding with left spaces */
1750 if (np.pad_type == LEFT && np.pad_size != 0)
1751 buffer_pad (buf, ' ', np.pad_size);
1753 /* sign character (may be '-', '+', or ' ') */
1754 if (np.sign)
1755 buffer_pad (buf, np.sign, 1);
1757 /* prefix part */
1758 if (np.prefix_ptr)
1759 buffer_cat (buf, np.prefix_ptr, np.prefix_size);
1761 /* right justification padding with leading zeros */
1762 if (np.pad_type == LEADING_ZEROS && np.pad_size != 0)
1763 buffer_pad (buf, '0', np.pad_size);
1765 /* integral part (may also be "nan" or "inf") */
1766 MPFR_ASSERTN (np.ip_ptr != NULL); /* never empty */
1767 if (MPFR_UNLIKELY (np.thousands_sep))
1768 buffer_sandwich (buf, np.ip_ptr, np.ip_size, np.ip_trailing_zeros,
1769 np.thousands_sep);
1770 else
1772 buffer_cat (buf, np.ip_ptr, np.ip_size);
1774 /* trailing zeros in integral part */
1775 if (np.ip_trailing_zeros != 0)
1776 buffer_pad (buf, '0', np.ip_trailing_zeros);
1779 /* decimal point */
1780 if (np.point)
1781 buffer_pad (buf, np.point, 1);
1783 /* leading zeros in fractional part */
1784 if (np.fp_leading_zeros != 0)
1785 buffer_pad (buf, '0', np.fp_leading_zeros);
1787 /* significant digits in fractional part */
1788 if (np.fp_ptr)
1789 buffer_cat (buf, np.fp_ptr, np.fp_size);
1791 /* trailing zeros in fractional part */
1792 if (np.fp_trailing_zeros != 0)
1793 buffer_pad (buf, '0', np.fp_trailing_zeros);
1795 /* exponent part */
1796 if (np.exp_ptr)
1797 buffer_cat (buf, np.exp_ptr, np.exp_size);
1799 /* left justication padding with right spaces */
1800 if (np.pad_type == RIGHT && np.pad_size != 0)
1801 buffer_pad (buf, ' ', np.pad_size);
1803 clear_string_list (np.sl);
1804 return length;
1808 mpfr_vasprintf (char **ptr, const char *fmt, va_list ap)
1810 struct string_buffer buf;
1811 size_t nbchar;
1813 /* informations on the conversion specification filled by the parser */
1814 struct printf_spec spec;
1815 /* flag raised when previous part of fmt need to be processed by
1816 gmp_vsnprintf */
1817 int gmp_fmt_flag;
1818 /* beginning and end of the previous unprocessed part of fmt */
1819 const char *start, *end;
1820 /* pointer to arguments for gmp_vasprintf */
1821 va_list ap2;
1823 MPFR_SAVE_EXPO_DECL (expo);
1824 MPFR_SAVE_EXPO_MARK (expo);
1826 nbchar = 0;
1827 buffer_init (&buf, 4096 * sizeof (char));
1828 gmp_fmt_flag = 0;
1829 va_copy (ap2, ap);
1830 start = fmt;
1831 while (*fmt)
1833 /* Look for the next format specification */
1834 while ((*fmt) && (*fmt != '%'))
1835 ++fmt;
1837 if (*fmt == '\0')
1838 break;
1840 if (*++fmt == '%')
1841 /* %%: go one step further otherwise the second '%' would be
1842 considered as a new conversion specification introducing
1843 character */
1845 ++fmt;
1846 continue;
1849 end = fmt - 1;
1851 /* format string analysis */
1852 specinfo_init (&spec);
1853 fmt = parse_flags (fmt, &spec);
1855 READ_INT (ap, fmt, spec, width, width_analysis);
1856 width_analysis:
1857 if (spec.width < 0)
1859 spec.left = 1;
1860 spec.width = -spec.width;
1861 MPFR_ASSERTN (spec.width < INT_MAX);
1863 if (*fmt == '.')
1865 const char *f = ++fmt;
1866 READ_INT (ap, fmt, spec, prec, prec_analysis);
1867 prec_analysis:
1868 if (f == fmt)
1869 spec.prec = -1;
1871 else
1872 spec.prec = -1;
1874 fmt = parse_arg_type (fmt, &spec);
1875 if (spec.arg_type == UNSUPPORTED)
1876 /* the current architecture doesn't support this type */
1878 goto error;
1880 else if (spec.arg_type == MPFR_ARG)
1882 switch (*fmt)
1884 case '\0':
1885 break;
1886 case '*':
1887 ++fmt;
1888 spec.rnd_mode = (mpfr_rnd_t) va_arg (ap, int);
1889 break;
1890 case 'D':
1891 ++fmt;
1892 spec.rnd_mode = GMP_RNDD;
1893 break;
1894 case 'U':
1895 ++fmt;
1896 spec.rnd_mode = GMP_RNDU;
1897 break;
1898 case 'Z':
1899 ++fmt;
1900 spec.rnd_mode = GMP_RNDZ;
1901 break;
1902 case 'N':
1903 ++fmt;
1904 default:
1905 spec.rnd_mode = GMP_RNDN;
1909 spec.spec = *fmt;
1910 if (*fmt)
1911 fmt++;
1913 /* Format processing */
1914 if (spec.spec == '\0')
1915 /* end of the format string */
1916 break;
1917 else if (spec.spec == 'n')
1918 /* put the number of characters written so far in the location pointed
1919 by the next va_list argument; the types of pointer accepted are the
1920 same as in GMP (except unsupported quad_t) plus pointer to a mpfr_t
1921 so as to be able to accept the same format strings. */
1923 void *p;
1924 size_t nchar;
1926 p = va_arg (ap, void *);
1927 FLUSH (gmp_fmt_flag, start, end, ap2, &buf);
1928 va_end (ap2);
1929 start = fmt;
1930 nchar = buf.curr - buf.start;
1932 switch (spec.arg_type)
1934 case CHAR_ARG:
1935 *(char *) p = (char) nchar;
1936 break;
1937 case SHORT_ARG:
1938 *(short *) p = (short) nchar;
1939 break;
1940 case LONG_ARG:
1941 *(long *) p = (long) nchar;
1942 break;
1943 #ifdef HAVE_LONG_LONG
1944 case LONG_LONG_ARG:
1945 *(long long *) p = (long long) nchar;
1946 break;
1947 #endif
1948 #ifdef _MPFR_H_HAVE_INTMAX_T
1949 case INTMAX_ARG:
1950 *(intmax_t *) p = (intmax_t) nchar;
1951 break;
1952 #endif
1953 case SIZE_ARG:
1954 *(size_t *) p = nchar;
1955 break;
1956 case PTRDIFF_ARG:
1957 *(ptrdiff_t *) p = (ptrdiff_t) nchar;
1958 break;
1959 case MPF_ARG:
1960 mpf_set_ui ((mpf_ptr) p, (unsigned long) nchar);
1961 break;
1962 case MPQ_ARG:
1963 mpq_set_ui ((mpq_ptr) p, (unsigned long) nchar, 1L);
1964 break;
1965 case MP_LIMB_ARG:
1966 *(mp_limb_t *) p = (mp_limb_t) nchar;
1967 break;
1968 case MP_LIMB_ARRAY_ARG:
1970 mp_limb_t *q = (mp_limb_t *) p;
1971 mp_size_t n;
1972 n = va_arg (ap, mp_size_t);
1973 if (n < 0)
1974 n = -n;
1975 else if (n == 0)
1976 break;
1978 /* we assume here that mp_limb_t is wider than int */
1979 *q = (mp_limb_t) nchar;
1980 while (--n != 0)
1982 q++;
1983 *q = (mp_limb_t) 0;
1986 break;
1987 case MPZ_ARG:
1988 mpz_set_ui ((mpz_ptr) p, (unsigned long) nchar);
1989 break;
1991 case MPFR_ARG:
1992 mpfr_set_ui ((mpfr_ptr) p, (unsigned long) nchar,
1993 spec.rnd_mode);
1994 break;
1996 default:
1997 *(int *) p = (int) nchar;
1999 va_copy (ap2, ap); /* after the switch, due to MP_LIMB_ARRAY_ARG
2000 case */
2002 else if (spec.arg_type == MPFR_PREC_ARG)
2003 /* output mp_prec_t variable */
2005 char *s;
2006 char format[MPFR_PREC_FORMAT_SIZE + 6]; /* see examples below */
2007 size_t length;
2008 mpfr_prec_t prec;
2009 prec = va_arg (ap, mpfr_prec_t);
2011 FLUSH (gmp_fmt_flag, start, end, ap2, &buf);
2012 va_end (ap2);
2013 va_copy (ap2, ap);
2014 start = fmt;
2016 /* construct format string, like "%*.*hu" "%*.*u" or "%*.*lu" */
2017 format[0] = '%';
2018 format[1] = '*';
2019 format[2] = '.';
2020 format[3] = '*';
2021 format[4] = '\0';
2022 strcat (format, MPFR_PREC_FORMAT_TYPE);
2023 format[4 + MPFR_PREC_FORMAT_SIZE] = spec.spec;
2024 format[5 + MPFR_PREC_FORMAT_SIZE] = '\0';
2025 length = gmp_asprintf (&s, format, spec.width, spec.prec, prec);
2026 if (buf.size <= INT_MAX - length)
2028 buffer_cat (&buf, s, length);
2029 mpfr_free_str (s);
2031 else
2033 mpfr_free_str (s);
2034 goto overflow_error;
2037 else if (spec.arg_type == MPFR_ARG)
2038 /* output a mpfr_t variable */
2040 mpfr_srcptr p;
2042 p = va_arg (ap, mpfr_srcptr);
2044 FLUSH (gmp_fmt_flag, start, end, ap2, &buf);
2045 va_end (ap2);
2046 va_copy (ap2, ap);
2047 start = fmt;
2049 switch (spec.spec)
2051 case 'a':
2052 case 'A':
2053 case 'b':
2054 case 'e':
2055 case 'E':
2056 case 'f':
2057 case 'F':
2058 case 'g':
2059 case 'G':
2060 if (sprnt_fp (&buf, p, spec) < 0)
2061 goto overflow_error;
2062 break;
2064 default:
2065 /* unsupported specifier */
2066 goto error;
2069 else
2070 /* gmp_printf specification, step forward in the va_list */
2072 CONSUME_VA_ARG (spec, ap);
2073 gmp_fmt_flag = 1;
2077 if (start != fmt)
2078 FLUSH (gmp_fmt_flag, start, fmt, ap2, &buf);
2080 va_end (ap2);
2081 nbchar = buf.curr - buf.start;
2082 MPFR_ASSERTD (nbchar == strlen (buf.start));
2083 buf.start =
2084 (char *) (*__gmp_reallocate_func) (buf.start, buf.size, nbchar + 1);
2085 *ptr = buf.start;
2087 /* If nbchar is larger than INT_MAX, the ISO C99 standard is silent, but
2088 POSIX says concerning the snprintf() function:
2089 "[EOVERFLOW] The value of n is greater than {INT_MAX} or the
2090 number of bytes needed to hold the output excluding the
2091 terminating null is greater than {INT_MAX}." See:
2092 http://www.opengroup.org/onlinepubs/009695399/functions/fprintf.html
2093 But it doesn't say anything concerning the other printf-like functions.
2094 A defect report has been submitted to austin-review-l (item 2532).
2095 So, for the time being, we return a negative value and set the erange
2096 flag, and set errno to EOVERFLOW in POSIX system. */
2097 if (nbchar <= INT_MAX)
2099 MPFR_SAVE_EXPO_FREE (expo);
2100 return nbchar;
2103 overflow_error:
2104 MPFR_SAVE_EXPO_UPDATE_FLAGS(expo, MPFR_FLAGS_ERANGE);
2105 #ifdef EOVERFLOW
2106 errno = EOVERFLOW;
2107 #endif
2109 error:
2110 MPFR_SAVE_EXPO_FREE (expo);
2111 *ptr = NULL;
2112 (*__gmp_free_func) (buf.start, buf.size);
2114 return -1;
2117 #endif /* HAVE_STDARG */