Debian Codegraph @

Modules/_decimal/libmpdec/io.c

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