• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2008-2016 Stefan Krah. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  *
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 
29 #include "mpdecimal.h"
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <ctype.h>
34 #include <limits.h>
35 #include <assert.h>
36 #include <errno.h>
37 #include <locale.h>
38 #include "bits.h"
39 #include "constants.h"
40 #include "typearith.h"
41 #include "io.h"
42 
43 
44 /* This file contains functions for decimal <-> string conversions, including
45    PEP-3101 formatting for numeric types. */
46 
47 
48 /* Disable warning that is part of -Wextra since gcc 7.0. */
49 #if defined(__GNUC__) && !defined(__INTEL_COMPILER) && __GNUC__ >= 7
50   #pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
51 #endif
52 
53 
54 /*
55  * Work around the behavior of tolower() and strcasecmp() in certain
56  * locales. For example, in tr_TR.utf8:
57  *
58  * tolower((unsigned char)'I') == 'I'
59  *
60  * u is the exact uppercase version of l; n is strlen(l) or strlen(l)+1
61  */
62 static inline int
_mpd_strneq(const char * s,const char * l,const char * u,size_t n)63 _mpd_strneq(const char *s, const char *l, const char *u, size_t n)
64 {
65     while (--n != SIZE_MAX) {
66         if (*s != *l && *s != *u) {
67             return 0;
68         }
69         s++; u++; l++;
70     }
71 
72     return 1;
73 }
74 
75 static mpd_ssize_t
strtoexp(const char * s)76 strtoexp(const char *s)
77 {
78     char *end;
79     mpd_ssize_t retval;
80 
81     errno = 0;
82     retval = mpd_strtossize(s, &end, 10);
83     if (errno == 0 && !(*s != '\0' && *end == '\0'))
84         errno = EINVAL;
85 
86     return retval;
87 }
88 
89 /*
90  * Scan 'len' words. The most significant word contains 'r' digits,
91  * the remaining words are full words. Skip dpoint. The string 's' must
92  * consist of digits and an optional single decimal point at 'dpoint'.
93  */
94 static void
string_to_coeff(mpd_uint_t * data,const char * s,const char * dpoint,int r,size_t len)95 string_to_coeff(mpd_uint_t *data, const char *s, const char *dpoint, int r,
96                 size_t len)
97 {
98     int j;
99 
100     if (r > 0) {
101         data[--len] = 0;
102         for (j = 0; j < r; j++, s++) {
103             if (s == dpoint) s++;
104             data[len] = 10 * data[len] + (*s - '0');
105         }
106     }
107 
108     while (--len != SIZE_MAX) {
109         data[len] = 0;
110         for (j = 0; j < MPD_RDIGITS; j++, s++) {
111             if (s == dpoint) s++;
112             data[len] = 10 * data[len] + (*s - '0');
113         }
114     }
115 }
116 
117 /*
118  * Partially verify a numeric string of the form:
119  *
120  *     [cdigits][.][cdigits][eE][+-][edigits]
121  *
122  * If successful, return a pointer to the location of the first
123  * relevant coefficient digit. This digit is either non-zero or
124  * part of one of the following patterns:
125  *
126  *     ["0\x00", "0.\x00", "0.E", "0.e", "0E", "0e"]
127  *
128  * The locations of a single optional dot or indicator are stored
129  * in 'dpoint' and 'exp'.
130  *
131  * The end of the string is stored in 'end'. If an indicator [eE]
132  * occurs without trailing [edigits], the condition is caught
133  * later by strtoexp().
134  */
135 static const char *
scan_dpoint_exp(const char * s,const char ** dpoint,const char ** exp,const char ** end)136 scan_dpoint_exp(const char *s, const char **dpoint, const char **exp,
137                 const char **end)
138 {
139     const char *coeff = NULL;
140 
141     *dpoint = NULL;
142     *exp = NULL;
143     for (; *s != '\0'; s++) {
144         switch (*s) {
145         case '.':
146             if (*dpoint != NULL || *exp != NULL)
147                 return NULL;
148             *dpoint = s;
149             break;
150         case 'E': case 'e':
151             if (*exp != NULL)
152                 return NULL;
153             *exp = s;
154             if (*(s+1) == '+' || *(s+1) == '-')
155                 s++;
156             break;
157         default:
158             if (!isdigit((uchar)*s))
159                 return NULL;
160             if (coeff == NULL && *exp == NULL) {
161                 if (*s == '0') {
162                     if (!isdigit((uchar)*(s+1)))
163                         if (!(*(s+1) == '.' &&
164                               isdigit((uchar)*(s+2))))
165                             coeff = s;
166                 }
167                 else {
168                     coeff = s;
169                 }
170             }
171             break;
172 
173         }
174     }
175 
176     *end = s;
177     return coeff;
178 }
179 
180 /* scan the payload of a NaN */
181 static const char *
scan_payload(const char * s,const char ** end)182 scan_payload(const char *s, const char **end)
183 {
184     const char *coeff;
185 
186     while (*s == '0')
187         s++;
188     coeff = s;
189 
190     while (isdigit((uchar)*s))
191         s++;
192     *end = s;
193 
194     return (*s == '\0') ? coeff : NULL;
195 }
196 
197 /* convert a character string to a decimal */
198 void
mpd_qset_string(mpd_t * dec,const char * s,const mpd_context_t * ctx,uint32_t * status)199 mpd_qset_string(mpd_t *dec, const char *s, const mpd_context_t *ctx,
200                 uint32_t *status)
201 {
202     mpd_ssize_t q, r, len;
203     const char *coeff, *end;
204     const char *dpoint = NULL, *exp = NULL;
205     size_t digits;
206     uint8_t sign = MPD_POS;
207 
208     mpd_set_flags(dec, 0);
209     dec->len = 0;
210     dec->exp = 0;
211 
212     /* sign */
213     if (*s == '+') {
214         s++;
215     }
216     else if (*s == '-') {
217         mpd_set_negative(dec);
218         sign = MPD_NEG;
219         s++;
220     }
221 
222     if (_mpd_strneq(s, "nan", "NAN", 3)) { /* NaN */
223         s += 3;
224         mpd_setspecial(dec, sign, MPD_NAN);
225         if (*s == '\0')
226             return;
227         /* validate payload: digits only */
228         if ((coeff = scan_payload(s, &end)) == NULL)
229             goto conversion_error;
230         /* payload consists entirely of zeros */
231         if (*coeff == '\0')
232             return;
233         digits = end - coeff;
234         /* prec >= 1, clamp is 0 or 1 */
235         if (digits > (size_t)(ctx->prec-ctx->clamp))
236             goto conversion_error;
237     } /* sNaN */
238     else if (_mpd_strneq(s, "snan", "SNAN", 4)) {
239         s += 4;
240         mpd_setspecial(dec, sign, MPD_SNAN);
241         if (*s == '\0')
242             return;
243         /* validate payload: digits only */
244         if ((coeff = scan_payload(s, &end)) == NULL)
245             goto conversion_error;
246         /* payload consists entirely of zeros */
247         if (*coeff == '\0')
248             return;
249         digits = end - coeff;
250         if (digits > (size_t)(ctx->prec-ctx->clamp))
251             goto conversion_error;
252     }
253     else if (_mpd_strneq(s, "inf", "INF", 3)) {
254         s += 3;
255         if (*s == '\0' || _mpd_strneq(s, "inity", "INITY", 6)) {
256             /* numeric-value: infinity */
257             mpd_setspecial(dec, sign, MPD_INF);
258             return;
259         }
260         goto conversion_error;
261     }
262     else {
263         /* scan for start of coefficient, decimal point, indicator, end */
264         if ((coeff = scan_dpoint_exp(s, &dpoint, &exp, &end)) == NULL)
265             goto conversion_error;
266 
267         /* numeric-value: [exponent-part] */
268         if (exp) {
269             /* exponent-part */
270             end = exp; exp++;
271             dec->exp = strtoexp(exp);
272             if (errno) {
273                 if (!(errno == ERANGE &&
274                      (dec->exp == MPD_SSIZE_MAX ||
275                       dec->exp == MPD_SSIZE_MIN)))
276                     goto conversion_error;
277             }
278         }
279 
280             digits = end - coeff;
281         if (dpoint) {
282             size_t fracdigits = end-dpoint-1;
283             if (dpoint > coeff) digits--;
284 
285             if (fracdigits > MPD_MAX_PREC) {
286                 goto conversion_error;
287             }
288             if (dec->exp < MPD_SSIZE_MIN+(mpd_ssize_t)fracdigits) {
289                 dec->exp = MPD_SSIZE_MIN;
290             }
291             else {
292                 dec->exp -= (mpd_ssize_t)fracdigits;
293             }
294         }
295         if (digits > MPD_MAX_PREC) {
296             goto conversion_error;
297         }
298         if (dec->exp > MPD_EXP_INF) {
299             dec->exp = MPD_EXP_INF;
300         }
301         if (dec->exp == MPD_SSIZE_MIN) {
302             dec->exp = MPD_SSIZE_MIN+1;
303         }
304     }
305 
306     _mpd_idiv_word(&q, &r, (mpd_ssize_t)digits, MPD_RDIGITS);
307 
308     len = (r == 0) ? q : q+1;
309     if (len == 0) {
310         goto conversion_error; /* GCOV_NOT_REACHED */
311     }
312     if (!mpd_qresize(dec, len, status)) {
313         mpd_seterror(dec, MPD_Malloc_error, status);
314         return;
315     }
316     dec->len = len;
317 
318     string_to_coeff(dec->data, coeff, dpoint, (int)r, len);
319 
320     mpd_setdigits(dec);
321     mpd_qfinalize(dec, ctx, status);
322     return;
323 
324 conversion_error:
325     /* standard wants a positive NaN */
326     mpd_seterror(dec, MPD_Conversion_syntax, status);
327 }
328 
329 /* Print word x with n decimal digits to string s. dot is either NULL
330    or the location of a decimal point. */
331 #define EXTRACT_DIGIT(s, x, d, dot) \
332         if (s == dot) *s++ = '.'; *s++ = '0' + (char)(x / d); x %= d
333 static inline char *
word_to_string(char * s,mpd_uint_t x,int n,char * dot)334 word_to_string(char *s, mpd_uint_t x, int n, char *dot)
335 {
336     switch(n) {
337 #ifdef CONFIG_64
338     case 20: EXTRACT_DIGIT(s, x, 10000000000000000000ULL, dot); /* GCOV_NOT_REACHED */
339     case 19: EXTRACT_DIGIT(s, x, 1000000000000000000ULL, dot);
340     case 18: EXTRACT_DIGIT(s, x, 100000000000000000ULL, dot);
341     case 17: EXTRACT_DIGIT(s, x, 10000000000000000ULL, dot);
342     case 16: EXTRACT_DIGIT(s, x, 1000000000000000ULL, dot);
343     case 15: EXTRACT_DIGIT(s, x, 100000000000000ULL, dot);
344     case 14: EXTRACT_DIGIT(s, x, 10000000000000ULL, dot);
345     case 13: EXTRACT_DIGIT(s, x, 1000000000000ULL, dot);
346     case 12: EXTRACT_DIGIT(s, x, 100000000000ULL, dot);
347     case 11: EXTRACT_DIGIT(s, x, 10000000000ULL, dot);
348 #endif
349     case 10: EXTRACT_DIGIT(s, x, 1000000000UL, dot);
350     case 9:  EXTRACT_DIGIT(s, x, 100000000UL, dot);
351     case 8:  EXTRACT_DIGIT(s, x, 10000000UL, dot);
352     case 7:  EXTRACT_DIGIT(s, x, 1000000UL, dot);
353     case 6:  EXTRACT_DIGIT(s, x, 100000UL, dot);
354     case 5:  EXTRACT_DIGIT(s, x, 10000UL, dot);
355     case 4:  EXTRACT_DIGIT(s, x, 1000UL, dot);
356     case 3:  EXTRACT_DIGIT(s, x, 100UL, dot);
357     case 2:  EXTRACT_DIGIT(s, x, 10UL, dot);
358     default: if (s == dot) *s++ = '.'; *s++ = '0' + (char)x;
359     }
360 
361     *s = '\0';
362     return s;
363 }
364 
365 /* Print exponent x to string s. Undefined for MPD_SSIZE_MIN. */
366 static inline char *
exp_to_string(char * s,mpd_ssize_t x)367 exp_to_string(char *s, mpd_ssize_t x)
368 {
369     char sign = '+';
370 
371     if (x < 0) {
372         sign = '-';
373         x = -x;
374     }
375     *s++ = sign;
376 
377     return word_to_string(s, x, mpd_word_digits(x), NULL);
378 }
379 
380 /* Print the coefficient of dec to string s. len(dec) > 0. */
381 static inline char *
coeff_to_string(char * s,const mpd_t * dec)382 coeff_to_string(char *s, const mpd_t *dec)
383 {
384     mpd_uint_t x;
385     mpd_ssize_t i;
386 
387     /* most significant word */
388     x = mpd_msword(dec);
389     s = word_to_string(s, x, mpd_word_digits(x), NULL);
390 
391     /* remaining full words */
392     for (i=dec->len-2; i >= 0; --i) {
393         x = dec->data[i];
394         s = word_to_string(s, x, MPD_RDIGITS, NULL);
395     }
396 
397     return s;
398 }
399 
400 /* Print the coefficient of dec to string s. len(dec) > 0. dot is either
401    NULL or a pointer to the location of a decimal point. */
402 static inline char *
coeff_to_string_dot(char * s,char * dot,const mpd_t * dec)403 coeff_to_string_dot(char *s, char *dot, const mpd_t *dec)
404 {
405     mpd_uint_t x;
406     mpd_ssize_t i;
407 
408     /* most significant word */
409     x = mpd_msword(dec);
410     s = word_to_string(s, x, mpd_word_digits(x), dot);
411 
412     /* remaining full words */
413     for (i=dec->len-2; i >= 0; --i) {
414         x = dec->data[i];
415         s = word_to_string(s, x, MPD_RDIGITS, dot);
416     }
417 
418     return s;
419 }
420 
421 /* Format type */
422 #define MPD_FMT_LOWER      0x00000000
423 #define MPD_FMT_UPPER      0x00000001
424 #define MPD_FMT_TOSCI      0x00000002
425 #define MPD_FMT_TOENG      0x00000004
426 #define MPD_FMT_EXP        0x00000008
427 #define MPD_FMT_FIXED      0x00000010
428 #define MPD_FMT_PERCENT    0x00000020
429 #define MPD_FMT_SIGN_SPACE 0x00000040
430 #define MPD_FMT_SIGN_PLUS  0x00000080
431 
432 /* Default place of the decimal point for MPD_FMT_TOSCI, MPD_FMT_EXP */
433 #define MPD_DEFAULT_DOTPLACE 1
434 
435 /*
436  * Set *result to the string representation of a decimal. Return the length
437  * of *result, not including the terminating '\0' character.
438  *
439  * Formatting is done according to 'flags'. A return value of -1 with *result
440  * set to NULL indicates MPD_Malloc_error.
441  *
442  * 'dplace' is the default place of the decimal point. It is always set to
443  * MPD_DEFAULT_DOTPLACE except for zeros in combination with MPD_FMT_EXP.
444  */
445 static mpd_ssize_t
_mpd_to_string(char ** result,const mpd_t * dec,int flags,mpd_ssize_t dplace)446 _mpd_to_string(char **result, const mpd_t *dec, int flags, mpd_ssize_t dplace)
447 {
448     char *decstring = NULL, *cp = NULL;
449     mpd_ssize_t ldigits;
450     mpd_ssize_t mem = 0, k;
451 
452     if (mpd_isspecial(dec)) {
453 
454         mem = sizeof "-Infinity%";
455         if (mpd_isnan(dec) && dec->len > 0) {
456             /* diagnostic code */
457             mem += dec->digits;
458         }
459         cp = decstring = mpd_alloc(mem, sizeof *decstring);
460         if (cp == NULL) {
461             *result = NULL;
462             return -1;
463         }
464 
465         if (mpd_isnegative(dec)) {
466             *cp++ = '-';
467         }
468         else if (flags&MPD_FMT_SIGN_SPACE) {
469             *cp++ = ' ';
470         }
471         else if (flags&MPD_FMT_SIGN_PLUS) {
472             *cp++ = '+';
473         }
474 
475         if (mpd_isnan(dec)) {
476             if (mpd_isqnan(dec)) {
477                 strcpy(cp, "NaN");
478                 cp += 3;
479             }
480             else {
481                 strcpy(cp, "sNaN");
482                 cp += 4;
483             }
484             if (dec->len > 0) { /* diagnostic code */
485                 cp = coeff_to_string(cp, dec);
486             }
487         }
488         else if (mpd_isinfinite(dec)) {
489             strcpy(cp, "Infinity");
490             cp += 8;
491         }
492         else { /* debug */
493             abort(); /* GCOV_NOT_REACHED */
494         }
495     }
496     else {
497         assert(dec->len > 0);
498 
499         /*
500          * For easier manipulation of the decimal point's location
501          * and the exponent that is finally printed, the number is
502          * rescaled to a virtual representation with exp = 0. Here
503          * ldigits denotes the number of decimal digits to the left
504          * of the decimal point and remains constant once initialized.
505          *
506          * dplace is the location of the decimal point relative to
507          * the start of the coefficient. Note that 3) always holds
508          * when dplace is shifted.
509          *
510          *   1) ldigits := dec->digits - dec->exp
511          *   2) dplace  := ldigits            (initially)
512          *   3) exp     := ldigits - dplace   (initially exp = 0)
513          *
514          *   0.00000_.____._____000000.
515          *    ^      ^    ^           ^
516          *    |      |    |           |
517          *    |      |    |           `- dplace >= digits
518          *    |      |    `- dplace in the middle of the coefficient
519          *    |      ` dplace = 1 (after the first coefficient digit)
520          *    `- dplace <= 0
521          */
522 
523         ldigits = dec->digits + dec->exp;
524 
525         if (flags&MPD_FMT_EXP) {
526             ;
527         }
528         else if (flags&MPD_FMT_FIXED || (dec->exp <= 0 && ldigits > -6)) {
529             /* MPD_FMT_FIXED: always use fixed point notation.
530              * MPD_FMT_TOSCI, MPD_FMT_TOENG: for a certain range,
531              * override exponent notation. */
532             dplace = ldigits;
533         }
534         else if (flags&MPD_FMT_TOENG) {
535             if (mpd_iszero(dec)) {
536                 /* If the exponent is divisible by three,
537                  * dplace = 1. Otherwise, move dplace one
538                  * or two places to the left. */
539                 dplace = -1 + mod_mpd_ssize_t(dec->exp+2, 3);
540             }
541             else { /* ldigits-1 is the adjusted exponent, which
542                 * should be divisible by three. If not, move
543                 * dplace one or two places to the right. */
544                 dplace += mod_mpd_ssize_t(ldigits-1, 3);
545             }
546         }
547 
548         /*
549          * Basic space requirements:
550          *
551          * [-][.][coeffdigits][E][-][expdigits+1][%]['\0']
552          *
553          * If the decimal point lies outside of the coefficient digits,
554          * space is adjusted accordingly.
555          */
556         if (dplace <= 0) {
557             mem = -dplace + dec->digits + 2;
558         }
559         else if (dplace >= dec->digits) {
560             mem = dplace;
561         }
562         else {
563             mem = dec->digits;
564         }
565         mem += (MPD_EXPDIGITS+1+6);
566 
567         cp = decstring = mpd_alloc(mem, sizeof *decstring);
568         if (cp == NULL) {
569             *result = NULL;
570             return -1;
571         }
572 
573 
574         if (mpd_isnegative(dec)) {
575             *cp++ = '-';
576         }
577         else if (flags&MPD_FMT_SIGN_SPACE) {
578             *cp++ = ' ';
579         }
580         else if (flags&MPD_FMT_SIGN_PLUS) {
581             *cp++ = '+';
582         }
583 
584         if (dplace <= 0) {
585             /* space: -dplace+dec->digits+2 */
586             *cp++ = '0';
587             *cp++ = '.';
588             for (k = 0; k < -dplace; k++) {
589                 *cp++ = '0';
590             }
591             cp = coeff_to_string(cp, dec);
592         }
593         else if (dplace >= dec->digits) {
594             /* space: dplace */
595             cp = coeff_to_string(cp, dec);
596             for (k = 0; k < dplace-dec->digits; k++) {
597                 *cp++ = '0';
598             }
599         }
600         else {
601             /* space: dec->digits+1 */
602             cp = coeff_to_string_dot(cp, cp+dplace, dec);
603         }
604 
605         /*
606          * Conditions for printing an exponent:
607          *
608          *   MPD_FMT_TOSCI, MPD_FMT_TOENG: only if ldigits != dplace
609          *   MPD_FMT_FIXED:                never (ldigits == dplace)
610          *   MPD_FMT_EXP:                  always
611          */
612         if (ldigits != dplace || flags&MPD_FMT_EXP) {
613             /* space: expdigits+2 */
614             *cp++ = (flags&MPD_FMT_UPPER) ? 'E' : 'e';
615             cp = exp_to_string(cp, ldigits-dplace);
616         }
617     }
618 
619     if (flags&MPD_FMT_PERCENT) {
620         *cp++ = '%';
621     }
622 
623     assert(cp < decstring+mem);
624     assert(cp-decstring < MPD_SSIZE_MAX);
625 
626     *cp = '\0';
627     *result = decstring;
628     return (mpd_ssize_t)(cp-decstring);
629 }
630 
631 char *
mpd_to_sci(const mpd_t * dec,int fmt)632 mpd_to_sci(const mpd_t *dec, int fmt)
633 {
634     char *res;
635     int flags = MPD_FMT_TOSCI;
636 
637     flags |= fmt ? MPD_FMT_UPPER : MPD_FMT_LOWER;
638     (void)_mpd_to_string(&res, dec, flags, MPD_DEFAULT_DOTPLACE);
639     return res;
640 }
641 
642 char *
mpd_to_eng(const mpd_t * dec,int fmt)643 mpd_to_eng(const mpd_t *dec, int fmt)
644 {
645     char *res;
646     int flags = MPD_FMT_TOENG;
647 
648     flags |= fmt ? MPD_FMT_UPPER : MPD_FMT_LOWER;
649     (void)_mpd_to_string(&res, dec, flags, MPD_DEFAULT_DOTPLACE);
650     return res;
651 }
652 
653 mpd_ssize_t
mpd_to_sci_size(char ** res,const mpd_t * dec,int fmt)654 mpd_to_sci_size(char **res, const mpd_t *dec, int fmt)
655 {
656     int flags = MPD_FMT_TOSCI;
657 
658     flags |= fmt ? MPD_FMT_UPPER : MPD_FMT_LOWER;
659     return _mpd_to_string(res, dec, flags, MPD_DEFAULT_DOTPLACE);
660 }
661 
662 mpd_ssize_t
mpd_to_eng_size(char ** res,const mpd_t * dec,int fmt)663 mpd_to_eng_size(char **res, const mpd_t *dec, int fmt)
664 {
665     int flags = MPD_FMT_TOENG;
666 
667     flags |= fmt ? MPD_FMT_UPPER : MPD_FMT_LOWER;
668     return _mpd_to_string(res, dec, flags, MPD_DEFAULT_DOTPLACE);
669 }
670 
671 /* Copy a single UTF-8 char to dest. See: The Unicode Standard, version 5.2,
672    chapter 3.9: Well-formed UTF-8 byte sequences. */
673 static int
_mpd_copy_utf8(char dest[5],const char * s)674 _mpd_copy_utf8(char dest[5], const char *s)
675 {
676     const uchar *cp = (const uchar *)s;
677     uchar lb, ub;
678     int count, i;
679 
680 
681     if (*cp == 0) {
682         /* empty string */
683         dest[0] = '\0';
684         return 0;
685     }
686     else if (*cp <= 0x7f) {
687         /* ascii */
688         dest[0] = *cp;
689         dest[1] = '\0';
690         return 1;
691     }
692     else if (0xc2 <= *cp && *cp <= 0xdf) {
693         lb = 0x80; ub = 0xbf;
694         count = 2;
695     }
696     else if (*cp == 0xe0) {
697         lb = 0xa0; ub = 0xbf;
698         count = 3;
699     }
700     else if (*cp <= 0xec) {
701         lb = 0x80; ub = 0xbf;
702         count = 3;
703     }
704     else if (*cp == 0xed) {
705         lb = 0x80; ub = 0x9f;
706         count = 3;
707     }
708     else if (*cp <= 0xef) {
709         lb = 0x80; ub = 0xbf;
710         count = 3;
711     }
712     else if (*cp == 0xf0) {
713         lb = 0x90; ub = 0xbf;
714         count = 4;
715     }
716     else if (*cp <= 0xf3) {
717         lb = 0x80; ub = 0xbf;
718         count = 4;
719     }
720     else if (*cp == 0xf4) {
721         lb = 0x80; ub = 0x8f;
722         count = 4;
723     }
724     else {
725         /* invalid */
726         goto error;
727     }
728 
729     dest[0] = *cp++;
730     if (*cp < lb || ub < *cp) {
731         goto error;
732     }
733     dest[1] = *cp++;
734     for (i = 2; i < count; i++) {
735         if (*cp < 0x80 || 0xbf < *cp) {
736             goto error;
737         }
738         dest[i] = *cp++;
739     }
740     dest[i] = '\0';
741 
742     return count;
743 
744 error:
745     dest[0] = '\0';
746     return -1;
747 }
748 
749 int
mpd_validate_lconv(mpd_spec_t * spec)750 mpd_validate_lconv(mpd_spec_t *spec)
751 {
752     size_t n;
753 #if CHAR_MAX == SCHAR_MAX
754     const char *cp = spec->grouping;
755     while (*cp != '\0') {
756         if (*cp++ < 0) {
757             return -1;
758         }
759     }
760 #endif
761     n = strlen(spec->dot);
762     if (n == 0 || n > 4) {
763         return -1;
764     }
765     if (strlen(spec->sep) > 4) {
766         return -1;
767     }
768 
769     return 0;
770 }
771 
772 int
mpd_parse_fmt_str(mpd_spec_t * spec,const char * fmt,int caps)773 mpd_parse_fmt_str(mpd_spec_t *spec, const char *fmt, int caps)
774 {
775     char *cp = (char *)fmt;
776     int have_align = 0, n;
777 
778     /* defaults */
779     spec->min_width = 0;
780     spec->prec = -1;
781     spec->type = caps ? 'G' : 'g';
782     spec->align = '>';
783     spec->sign = '-';
784     spec->dot = "";
785     spec->sep = "";
786     spec->grouping = "";
787 
788 
789     /* presume that the first character is a UTF-8 fill character */
790     if ((n = _mpd_copy_utf8(spec->fill, cp)) < 0) {
791         return 0;
792     }
793 
794     /* alignment directive, prefixed by a fill character */
795     if (*cp && (*(cp+n) == '<' || *(cp+n) == '>' ||
796                 *(cp+n) == '=' || *(cp+n) == '^')) {
797         cp += n;
798         spec->align = *cp++;
799         have_align = 1;
800     } /* alignment directive */
801     else {
802         /* default fill character */
803         spec->fill[0] = ' ';
804         spec->fill[1] = '\0';
805         if (*cp == '<' || *cp == '>' ||
806             *cp == '=' || *cp == '^') {
807             spec->align = *cp++;
808             have_align = 1;
809         }
810     }
811 
812     /* sign formatting */
813     if (*cp == '+' || *cp == '-' || *cp == ' ') {
814         spec->sign = *cp++;
815     }
816 
817     /* zero padding */
818     if (*cp == '0') {
819         /* zero padding implies alignment, which should not be
820          * specified twice. */
821         if (have_align) {
822             return 0;
823         }
824         spec->align = 'z';
825         spec->fill[0] = *cp++;
826         spec->fill[1] = '\0';
827     }
828 
829     /* minimum width */
830     if (isdigit((uchar)*cp)) {
831         if (*cp == '0') {
832             return 0;
833         }
834         errno = 0;
835         spec->min_width = mpd_strtossize(cp, &cp, 10);
836         if (errno == ERANGE || errno == EINVAL) {
837             return 0;
838         }
839     }
840 
841     /* thousands separator */
842     if (*cp == ',') {
843         spec->dot = ".";
844         spec->sep = ",";
845         spec->grouping = "\003\003";
846         cp++;
847     }
848 
849     /* fraction digits or significant digits */
850     if (*cp == '.') {
851         cp++;
852         if (!isdigit((uchar)*cp)) {
853             return 0;
854         }
855         errno = 0;
856         spec->prec = mpd_strtossize(cp, &cp, 10);
857         if (errno == ERANGE || errno == EINVAL) {
858             return 0;
859         }
860     }
861 
862     /* type */
863     if (*cp == 'E' || *cp == 'e' || *cp == 'F' || *cp == 'f' ||
864         *cp == 'G' || *cp == 'g' || *cp == '%') {
865         spec->type = *cp++;
866     }
867     else if (*cp == 'N' || *cp == 'n') {
868         /* locale specific conversion */
869         struct lconv *lc;
870         /* separator has already been specified */
871         if (*spec->sep) {
872             return 0;
873         }
874         spec->type = *cp++;
875         spec->type = (spec->type == 'N') ? 'G' : 'g';
876         lc = localeconv();
877         spec->dot = lc->decimal_point;
878         spec->sep = lc->thousands_sep;
879         spec->grouping = lc->grouping;
880         if (mpd_validate_lconv(spec) < 0) {
881             return 0; /* GCOV_NOT_REACHED */
882         }
883     }
884 
885     /* check correctness */
886     if (*cp != '\0') {
887         return 0;
888     }
889 
890     return 1;
891 }
892 
893 /*
894  * The following functions assume that spec->min_width <= MPD_MAX_PREC, which
895  * is made sure in mpd_qformat_spec. Then, even with a spec that inserts a
896  * four-byte separator after each digit, nbytes in the following struct
897  * cannot overflow.
898  */
899 
900 /* Multibyte string */
901 typedef struct {
902     mpd_ssize_t nbytes; /* length in bytes */
903     mpd_ssize_t nchars; /* length in chars */
904     mpd_ssize_t cur;    /* current write index */
905     char *data;
906 } mpd_mbstr_t;
907 
908 static inline void
_mpd_bcopy(char * dest,const char * src,mpd_ssize_t n)909 _mpd_bcopy(char *dest, const char *src, mpd_ssize_t n)
910 {
911     while (--n >= 0) {
912         dest[n] = src[n];
913     }
914 }
915 
916 static inline void
_mbstr_copy_char(mpd_mbstr_t * dest,const char * src,mpd_ssize_t n)917 _mbstr_copy_char(mpd_mbstr_t *dest, const char *src, mpd_ssize_t n)
918 {
919     dest->nbytes += n;
920     dest->nchars += (n > 0 ? 1 : 0);
921     dest->cur -= n;
922 
923     if (dest->data != NULL) {
924         _mpd_bcopy(dest->data+dest->cur, src, n);
925     }
926 }
927 
928 static inline void
_mbstr_copy_ascii(mpd_mbstr_t * dest,const char * src,mpd_ssize_t n)929 _mbstr_copy_ascii(mpd_mbstr_t *dest, const char *src, mpd_ssize_t n)
930 {
931     dest->nbytes += n;
932     dest->nchars += n;
933     dest->cur -= n;
934 
935     if (dest->data != NULL) {
936         _mpd_bcopy(dest->data+dest->cur, src, n);
937     }
938 }
939 
940 static inline void
_mbstr_copy_pad(mpd_mbstr_t * dest,mpd_ssize_t n)941 _mbstr_copy_pad(mpd_mbstr_t *dest, mpd_ssize_t n)
942 {
943     dest->nbytes += n;
944     dest->nchars += n;
945     dest->cur -= n;
946 
947     if (dest->data != NULL) {
948         char *cp = dest->data + dest->cur;
949         while (--n >= 0) {
950             cp[n] = '0';
951         }
952     }
953 }
954 
955 /*
956  * Copy a numeric string to dest->data, adding separators in the integer
957  * part according to spec->grouping. If leading zero padding is enabled
958  * and the result is smaller than spec->min_width, continue adding zeros
959  * and separators until the minimum width is reached.
960  *
961  * The final length of dest->data is stored in dest->nbytes. The number
962  * of UTF-8 characters is stored in dest->nchars.
963  *
964  * First run (dest->data == NULL): determine the length of the result
965  * string and store it in dest->nbytes.
966  *
967  * Second run (write to dest->data): data is written in chunks and in
968  * reverse order, starting with the rest of the numeric string.
969  */
970 static void
_mpd_add_sep_dot(mpd_mbstr_t * dest,const char * sign,const char * src,mpd_ssize_t n_src,const char * dot,const char * rest,mpd_ssize_t n_rest,const mpd_spec_t * spec)971 _mpd_add_sep_dot(mpd_mbstr_t *dest,
972                  const char *sign, /* location of optional sign */
973                  const char *src, mpd_ssize_t n_src, /* integer part and length */
974                  const char *dot, /* location of optional decimal point */
975                  const char *rest, mpd_ssize_t n_rest, /* remaining part and length */
976                  const mpd_spec_t *spec)
977 {
978     mpd_ssize_t n_sep, n_sign, consume;
979     const char *g;
980     int pad = 0;
981 
982     n_sign = sign ? 1 : 0;
983     n_sep = (mpd_ssize_t)strlen(spec->sep);
984     /* Initial write index: set to location of '\0' in the output string.
985      * Irrelevant for the first run. */
986     dest->cur = dest->nbytes;
987     dest->nbytes = dest->nchars = 0;
988 
989     _mbstr_copy_ascii(dest, rest, n_rest);
990 
991     if (dot) {
992         _mbstr_copy_char(dest, dot, (mpd_ssize_t)strlen(dot));
993     }
994 
995     g = spec->grouping;
996     consume = *g;
997     while (1) {
998         /* If the group length is 0 or CHAR_MAX or greater than the
999          * number of source bytes, consume all remaining bytes. */
1000         if (*g == 0 || *g == CHAR_MAX || consume > n_src) {
1001             consume = n_src;
1002         }
1003         n_src -= consume;
1004         if (pad) {
1005             _mbstr_copy_pad(dest, consume);
1006         }
1007         else {
1008             _mbstr_copy_ascii(dest, src+n_src, consume);
1009         }
1010 
1011         if (n_src == 0) {
1012             /* Either the real source of intpart digits or the virtual
1013              * source of padding zeros is exhausted. */
1014             if (spec->align == 'z' &&
1015                 dest->nchars + n_sign < spec->min_width) {
1016                 /* Zero padding is set and length < min_width:
1017                  * Generate n_src additional characters. */
1018                 n_src = spec->min_width - (dest->nchars + n_sign);
1019                 /* Next iteration:
1020                  *   case *g == 0 || *g == CHAR_MAX:
1021                  *      consume all padding characters
1022                  *   case consume < g*:
1023                  *      fill remainder of current group
1024                  *   case consume == g*
1025                  *      copying is a no-op */
1026                 consume = *g - consume;
1027                 /* Switch on virtual source of zeros. */
1028                 pad = 1;
1029                 continue;
1030             }
1031             break;
1032         }
1033 
1034         if (n_sep > 0) {
1035             /* If padding is switched on, separators are counted
1036              * as padding characters. This rule does not apply if
1037              * the separator would be the first character of the
1038              * result string. */
1039             if (pad && n_src > 1) n_src -= 1;
1040             _mbstr_copy_char(dest, spec->sep, n_sep);
1041         }
1042 
1043         /* If non-NUL, use the next value for grouping. */
1044         if (*g && *(g+1)) g++;
1045         consume = *g;
1046     }
1047 
1048     if (sign) {
1049         _mbstr_copy_ascii(dest, sign, 1);
1050     }
1051 
1052     if (dest->data) {
1053         dest->data[dest->nbytes] = '\0';
1054     }
1055 }
1056 
1057 /*
1058  * Convert a numeric-string to its locale-specific appearance.
1059  * The string must have one of these forms:
1060  *
1061  *     1) [sign] digits [exponent-part]
1062  *     2) [sign] digits '.' [digits] [exponent-part]
1063  *
1064  * Not allowed, since _mpd_to_string() never returns this form:
1065  *
1066  *     3) [sign] '.' digits [exponent-part]
1067  *
1068  * Input: result->data := original numeric string (ASCII)
1069  *        result->bytes := strlen(result->data)
1070  *        result->nchars := strlen(result->data)
1071  *
1072  * Output: result->data := modified or original string
1073  *         result->bytes := strlen(result->data)
1074  *         result->nchars := number of characters (possibly UTF-8)
1075  */
1076 static int
_mpd_apply_lconv(mpd_mbstr_t * result,const mpd_spec_t * spec,uint32_t * status)1077 _mpd_apply_lconv(mpd_mbstr_t *result, const mpd_spec_t *spec, uint32_t *status)
1078 {
1079     const char *sign = NULL, *intpart = NULL, *dot = NULL;
1080     const char *rest, *dp;
1081     char *decstring;
1082     mpd_ssize_t n_int, n_rest;
1083 
1084     /* original numeric string */
1085     dp = result->data;
1086 
1087     /* sign */
1088     if (*dp == '+' || *dp == '-' || *dp == ' ') {
1089         sign = dp++;
1090     }
1091     /* integer part */
1092     assert(isdigit((uchar)*dp));
1093     intpart = dp++;
1094     while (isdigit((uchar)*dp)) {
1095         dp++;
1096     }
1097     n_int = (mpd_ssize_t)(dp-intpart);
1098     /* decimal point */
1099     if (*dp == '.') {
1100         dp++; dot = spec->dot;
1101     }
1102     /* rest */
1103     rest = dp;
1104     n_rest = result->nbytes - (mpd_ssize_t)(dp-result->data);
1105 
1106     if (dot == NULL && (*spec->sep == '\0' || *spec->grouping == '\0')) {
1107         /* _mpd_add_sep_dot() would not change anything */
1108         return 1;
1109     }
1110 
1111     /* Determine the size of the new decimal string after inserting the
1112      * decimal point, optional separators and optional padding. */
1113     decstring = result->data;
1114     result->data = NULL;
1115     _mpd_add_sep_dot(result, sign, intpart, n_int, dot,
1116                      rest, n_rest, spec);
1117 
1118     result->data = mpd_alloc(result->nbytes+1, 1);
1119     if (result->data == NULL) {
1120         *status |= MPD_Malloc_error;
1121         mpd_free(decstring);
1122         return 0;
1123     }
1124 
1125     /* Perform actual writes. */
1126     _mpd_add_sep_dot(result, sign, intpart, n_int, dot,
1127                      rest, n_rest, spec);
1128 
1129     mpd_free(decstring);
1130     return 1;
1131 }
1132 
1133 /* Add padding to the formatted string if necessary. */
1134 static int
_mpd_add_pad(mpd_mbstr_t * result,const mpd_spec_t * spec,uint32_t * status)1135 _mpd_add_pad(mpd_mbstr_t *result, const mpd_spec_t *spec, uint32_t *status)
1136 {
1137     if (result->nchars < spec->min_width) {
1138         mpd_ssize_t add_chars, add_bytes;
1139         size_t lpad = 0, rpad = 0;
1140         size_t n_fill, len, i, j;
1141         char align = spec->align;
1142         uint8_t err = 0;
1143         char *cp;
1144 
1145         n_fill = strlen(spec->fill);
1146         add_chars = (spec->min_width - result->nchars);
1147         /* max value: MPD_MAX_PREC * 4 */
1148         add_bytes = add_chars * (mpd_ssize_t)n_fill;
1149 
1150         cp = result->data = mpd_realloc(result->data,
1151                                         result->nbytes+add_bytes+1,
1152                                         sizeof *result->data, &err);
1153         if (err) {
1154             *status |= MPD_Malloc_error;
1155             mpd_free(result->data);
1156             return 0;
1157         }
1158 
1159         if (align == 'z') {
1160             align = '=';
1161         }
1162 
1163         if (align == '<') {
1164             rpad = add_chars;
1165         }
1166         else if (align == '>' || align == '=') {
1167             lpad = add_chars;
1168         }
1169         else { /* align == '^' */
1170             lpad = add_chars/2;
1171             rpad = add_chars-lpad;
1172         }
1173 
1174         len = result->nbytes;
1175         if (align == '=' && (*cp == '-' || *cp == '+' || *cp == ' ')) {
1176             /* leave sign in the leading position */
1177             cp++; len--;
1178         }
1179 
1180         memmove(cp+n_fill*lpad, cp, len);
1181         for (i = 0; i < lpad; i++) {
1182             for (j = 0; j < n_fill; j++) {
1183                 cp[i*n_fill+j] = spec->fill[j];
1184             }
1185         }
1186         cp += (n_fill*lpad + len);
1187         for (i = 0; i < rpad; i++) {
1188             for (j = 0; j < n_fill; j++) {
1189                 cp[i*n_fill+j] = spec->fill[j];
1190             }
1191         }
1192 
1193         result->nbytes += add_bytes;
1194         result->nchars += add_chars;
1195         result->data[result->nbytes] = '\0';
1196     }
1197 
1198     return 1;
1199 }
1200 
1201 /* Round a number to prec digits. The adjusted exponent stays the same
1202    or increases by one if rounding up crosses a power of ten boundary.
1203    If result->digits would exceed MPD_MAX_PREC+1, MPD_Invalid_operation
1204    is set and the result is NaN. */
1205 static inline void
_mpd_round(mpd_t * result,const mpd_t * a,mpd_ssize_t prec,const mpd_context_t * ctx,uint32_t * status)1206 _mpd_round(mpd_t *result, const mpd_t *a, mpd_ssize_t prec,
1207            const mpd_context_t *ctx, uint32_t *status)
1208 {
1209     mpd_ssize_t exp = a->exp + a->digits - prec;
1210 
1211     if (prec <= 0) {
1212         mpd_seterror(result, MPD_Invalid_operation, status); /* GCOV_NOT_REACHED */
1213         return; /* GCOV_NOT_REACHED */
1214     }
1215     if (mpd_isspecial(a) || mpd_iszero(a)) {
1216         mpd_qcopy(result, a, status); /* GCOV_NOT_REACHED */
1217         return; /* GCOV_NOT_REACHED */
1218     }
1219 
1220     mpd_qrescale_fmt(result, a, exp, ctx, status);
1221     if (result->digits > prec) {
1222         mpd_qrescale_fmt(result, result, exp+1, ctx, status);
1223     }
1224 }
1225 
1226 /*
1227  * Return the string representation of an mpd_t, formatted according to 'spec'.
1228  * The format specification is assumed to be valid. Memory errors are indicated
1229  * as usual. This function is quiet.
1230  */
1231 char *
mpd_qformat_spec(const mpd_t * dec,const mpd_spec_t * spec,const mpd_context_t * ctx,uint32_t * status)1232 mpd_qformat_spec(const mpd_t *dec, const mpd_spec_t *spec,
1233                  const mpd_context_t *ctx, uint32_t *status)
1234 {
1235     mpd_uint_t dt[MPD_MINALLOC_MAX];
1236     mpd_t tmp = {MPD_STATIC|MPD_STATIC_DATA,0,0,0,MPD_MINALLOC_MAX,dt};
1237     mpd_ssize_t dplace = MPD_DEFAULT_DOTPLACE;
1238     mpd_mbstr_t result;
1239     mpd_spec_t stackspec;
1240     char type = spec->type;
1241     int flags = 0;
1242 
1243 
1244     if (spec->min_width > MPD_MAX_PREC) {
1245         *status |= MPD_Invalid_operation;
1246         return NULL;
1247     }
1248 
1249     if (isupper((uchar)type)) {
1250         type = tolower((uchar)type);
1251         flags |= MPD_FMT_UPPER;
1252     }
1253     if (spec->sign == ' ') {
1254         flags |= MPD_FMT_SIGN_SPACE;
1255     }
1256     else if (spec->sign == '+') {
1257         flags |= MPD_FMT_SIGN_PLUS;
1258     }
1259 
1260     if (mpd_isspecial(dec)) {
1261         if (spec->align == 'z') {
1262             stackspec = *spec;
1263             stackspec.fill[0] = ' ';
1264             stackspec.fill[1] = '\0';
1265             stackspec.align = '>';
1266             spec = &stackspec;
1267         }
1268         if (type == '%') {
1269             flags |= MPD_FMT_PERCENT;
1270         }
1271     }
1272     else {
1273         uint32_t workstatus = 0;
1274         mpd_ssize_t prec;
1275 
1276         switch (type) {
1277         case 'g': flags |= MPD_FMT_TOSCI; break;
1278         case 'e': flags |= MPD_FMT_EXP; break;
1279         case '%': flags |= MPD_FMT_PERCENT;
1280                   if (!mpd_qcopy(&tmp, dec, status)) {
1281                       return NULL;
1282                   }
1283                   tmp.exp += 2;
1284                   dec = &tmp;
1285                   type = 'f'; /* fall through */
1286         case 'f': flags |= MPD_FMT_FIXED; break;
1287         default: abort(); /* debug: GCOV_NOT_REACHED */
1288         }
1289 
1290         if (spec->prec >= 0) {
1291             if (spec->prec > MPD_MAX_PREC) {
1292                 *status |= MPD_Invalid_operation;
1293                 goto error;
1294             }
1295 
1296             switch (type) {
1297             case 'g':
1298                 prec = (spec->prec == 0) ? 1 : spec->prec;
1299                 if (dec->digits > prec) {
1300                     _mpd_round(&tmp, dec, prec, ctx,
1301                                &workstatus);
1302                     dec = &tmp;
1303                 }
1304                 break;
1305             case 'e':
1306                 if (mpd_iszero(dec)) {
1307                     dplace = 1-spec->prec;
1308                 }
1309                 else {
1310                     _mpd_round(&tmp, dec, spec->prec+1, ctx,
1311                                &workstatus);
1312                     dec = &tmp;
1313                 }
1314                 break;
1315             case 'f':
1316                 mpd_qrescale(&tmp, dec, -spec->prec, ctx,
1317                              &workstatus);
1318                 dec = &tmp;
1319                 break;
1320             }
1321         }
1322 
1323         if (type == 'f') {
1324             if (mpd_iszero(dec) && dec->exp > 0) {
1325                 mpd_qrescale(&tmp, dec, 0, ctx, &workstatus);
1326                 dec = &tmp;
1327             }
1328         }
1329 
1330         if (workstatus&MPD_Errors) {
1331             *status |= (workstatus&MPD_Errors);
1332             goto error;
1333         }
1334     }
1335 
1336     /*
1337      * At this point, for all scaled or non-scaled decimals:
1338      *   1) 1 <= digits <= MAX_PREC+1
1339      *   2) adjexp(scaled) = adjexp(orig) [+1]
1340      *   3)   case 'g': MIN_ETINY <= exp <= MAX_EMAX+1
1341      *        case 'e': MIN_ETINY-MAX_PREC <= exp <= MAX_EMAX+1
1342      *        case 'f': MIN_ETINY <= exp <= MAX_EMAX+1
1343      *   4) max memory alloc in _mpd_to_string:
1344      *        case 'g': MAX_PREC+36
1345      *        case 'e': MAX_PREC+36
1346      *        case 'f': 2*MPD_MAX_PREC+30
1347      */
1348     result.nbytes = _mpd_to_string(&result.data, dec, flags, dplace);
1349     result.nchars = result.nbytes;
1350     if (result.nbytes < 0) {
1351         *status |= MPD_Malloc_error;
1352         goto error;
1353     }
1354 
1355     if (*spec->dot != '\0' && !mpd_isspecial(dec)) {
1356         if (result.nchars > MPD_MAX_PREC+36) {
1357             /* Since a group length of one is not explicitly
1358              * disallowed, ensure that it is always possible to
1359              * insert a four byte separator after each digit. */
1360             *status |= MPD_Invalid_operation;
1361             mpd_free(result.data);
1362             goto error;
1363         }
1364         if (!_mpd_apply_lconv(&result, spec, status)) {
1365             goto error;
1366         }
1367     }
1368 
1369     if (spec->min_width) {
1370         if (!_mpd_add_pad(&result, spec, status)) {
1371             goto error;
1372         }
1373     }
1374 
1375     mpd_del(&tmp);
1376     return result.data;
1377 
1378 error:
1379     mpd_del(&tmp);
1380     return NULL;
1381 }
1382 
1383 char *
mpd_qformat(const mpd_t * dec,const char * fmt,const mpd_context_t * ctx,uint32_t * status)1384 mpd_qformat(const mpd_t *dec, const char *fmt, const mpd_context_t *ctx,
1385             uint32_t *status)
1386 {
1387     mpd_spec_t spec;
1388 
1389     if (!mpd_parse_fmt_str(&spec, fmt, 1)) {
1390         *status |= MPD_Invalid_operation;
1391         return NULL;
1392     }
1393 
1394     return mpd_qformat_spec(dec, &spec, ctx, status);
1395 }
1396 
1397 /*
1398  * The specification has a *condition* called Invalid_operation and an
1399  * IEEE *signal* called Invalid_operation. The former corresponds to
1400  * MPD_Invalid_operation, the latter to MPD_IEEE_Invalid_operation.
1401  * MPD_IEEE_Invalid_operation comprises the following conditions:
1402  *
1403  * [MPD_Conversion_syntax, MPD_Division_impossible, MPD_Division_undefined,
1404  *  MPD_Fpu_error, MPD_Invalid_context, MPD_Invalid_operation,
1405  *  MPD_Malloc_error]
1406  *
1407  * In the following functions, 'flag' denotes the condition, 'signal'
1408  * denotes the IEEE signal.
1409  */
1410 
1411 static const char *mpd_flag_string[MPD_NUM_FLAGS] = {
1412     "Clamped",
1413     "Conversion_syntax",
1414     "Division_by_zero",
1415     "Division_impossible",
1416     "Division_undefined",
1417     "Fpu_error",
1418     "Inexact",
1419     "Invalid_context",
1420     "Invalid_operation",
1421     "Malloc_error",
1422     "Not_implemented",
1423     "Overflow",
1424     "Rounded",
1425     "Subnormal",
1426     "Underflow",
1427 };
1428 
1429 static const char *mpd_signal_string[MPD_NUM_FLAGS] = {
1430     "Clamped",
1431     "IEEE_Invalid_operation",
1432     "Division_by_zero",
1433     "IEEE_Invalid_operation",
1434     "IEEE_Invalid_operation",
1435     "IEEE_Invalid_operation",
1436     "Inexact",
1437     "IEEE_Invalid_operation",
1438     "IEEE_Invalid_operation",
1439     "IEEE_Invalid_operation",
1440     "Not_implemented",
1441     "Overflow",
1442     "Rounded",
1443     "Subnormal",
1444     "Underflow",
1445 };
1446 
1447 /* print conditions to buffer, separated by spaces */
1448 int
mpd_snprint_flags(char * dest,int nmemb,uint32_t flags)1449 mpd_snprint_flags(char *dest, int nmemb, uint32_t flags)
1450 {
1451     char *cp;
1452     int n, j;
1453 
1454     assert(nmemb >= MPD_MAX_FLAG_STRING);
1455 
1456     *dest = '\0'; cp = dest;
1457     for (j = 0; j < MPD_NUM_FLAGS; j++) {
1458         if (flags & (1U<<j)) {
1459             n = snprintf(cp, nmemb, "%s ", mpd_flag_string[j]);
1460             if (n < 0 || n >= nmemb) return -1;
1461             cp += n; nmemb -= n;
1462         }
1463     }
1464 
1465     if (cp != dest) {
1466         *(--cp) = '\0';
1467     }
1468 
1469     return (int)(cp-dest);
1470 }
1471 
1472 /* print conditions to buffer, in list form */
1473 int
mpd_lsnprint_flags(char * dest,int nmemb,uint32_t flags,const char * flag_string[])1474 mpd_lsnprint_flags(char *dest, int nmemb, uint32_t flags, const char *flag_string[])
1475 {
1476     char *cp;
1477     int n, j;
1478 
1479     assert(nmemb >= MPD_MAX_FLAG_LIST);
1480     if (flag_string == NULL) {
1481         flag_string = mpd_flag_string;
1482     }
1483 
1484     *dest = '[';
1485     *(dest+1) = '\0';
1486     cp = dest+1;
1487     --nmemb;
1488 
1489     for (j = 0; j < MPD_NUM_FLAGS; j++) {
1490         if (flags & (1U<<j)) {
1491             n = snprintf(cp, nmemb, "%s, ", flag_string[j]);
1492             if (n < 0 || n >= nmemb) return -1;
1493             cp += n; nmemb -= n;
1494         }
1495     }
1496 
1497     /* erase the last ", " */
1498     if (cp != dest+1) {
1499         cp -= 2;
1500     }
1501 
1502     *cp++ = ']';
1503     *cp = '\0';
1504 
1505     return (int)(cp-dest); /* strlen, without NUL terminator */
1506 }
1507 
1508 /* print signals to buffer, in list form */
1509 int
mpd_lsnprint_signals(char * dest,int nmemb,uint32_t flags,const char * signal_string[])1510 mpd_lsnprint_signals(char *dest, int nmemb, uint32_t flags, const char *signal_string[])
1511 {
1512     char *cp;
1513     int n, j;
1514     int ieee_invalid_done = 0;
1515 
1516     assert(nmemb >= MPD_MAX_SIGNAL_LIST);
1517     if (signal_string == NULL) {
1518         signal_string = mpd_signal_string;
1519     }
1520 
1521     *dest = '[';
1522     *(dest+1) = '\0';
1523     cp = dest+1;
1524     --nmemb;
1525 
1526     for (j = 0; j < MPD_NUM_FLAGS; j++) {
1527         uint32_t f = flags & (1U<<j);
1528         if (f) {
1529             if (f&MPD_IEEE_Invalid_operation) {
1530                 if (ieee_invalid_done) {
1531                     continue;
1532                 }
1533                 ieee_invalid_done = 1;
1534             }
1535             n = snprintf(cp, nmemb, "%s, ", signal_string[j]);
1536             if (n < 0 || n >= nmemb) return -1;
1537             cp += n; nmemb -= n;
1538         }
1539     }
1540 
1541     /* erase the last ", " */
1542     if (cp != dest+1) {
1543         cp -= 2;
1544     }
1545 
1546     *cp++ = ']';
1547     *cp = '\0';
1548 
1549     return (int)(cp-dest); /* strlen, without NUL terminator */
1550 }
1551 
1552 /* The following two functions are mainly intended for debugging. */
1553 void
mpd_fprint(FILE * file,const mpd_t * dec)1554 mpd_fprint(FILE *file, const mpd_t *dec)
1555 {
1556     char *decstring;
1557 
1558     decstring = mpd_to_sci(dec, 1);
1559     if (decstring != NULL) {
1560         fprintf(file, "%s\n", decstring);
1561         mpd_free(decstring);
1562     }
1563     else {
1564         fputs("mpd_fprint: output error\n", file); /* GCOV_NOT_REACHED */
1565     }
1566 }
1567 
1568 void
mpd_print(const mpd_t * dec)1569 mpd_print(const mpd_t *dec)
1570 {
1571     char *decstring;
1572 
1573     decstring = mpd_to_sci(dec, 1);
1574     if (decstring != NULL) {
1575         printf("%s\n", decstring);
1576         mpd_free(decstring);
1577     }
1578     else {
1579         fputs("mpd_fprint: output error\n", stderr); /* GCOV_NOT_REACHED */
1580     }
1581 }
1582 
1583 
1584