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